main.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. from fastapi import (
  2. FastAPI,
  3. Request,
  4. Response,
  5. HTTPException,
  6. Depends,
  7. status,
  8. UploadFile,
  9. File,
  10. BackgroundTasks,
  11. )
  12. from fastapi.middleware.cors import CORSMiddleware
  13. from fastapi.responses import StreamingResponse
  14. from fastapi.concurrency import run_in_threadpool
  15. from pydantic import BaseModel, ConfigDict
  16. import os
  17. import re
  18. import copy
  19. import random
  20. import requests
  21. import json
  22. import uuid
  23. import aiohttp
  24. import asyncio
  25. import logging
  26. import time
  27. from urllib.parse import urlparse
  28. from typing import Optional, List, Union
  29. from apps.web.models.models import Models
  30. from apps.web.models.users import Users
  31. from constants import ERROR_MESSAGES
  32. from utils.utils import (
  33. decode_token,
  34. get_current_user,
  35. get_verified_user,
  36. get_admin_user,
  37. )
  38. from config import (
  39. SRC_LOG_LEVELS,
  40. OLLAMA_BASE_URLS,
  41. ENABLE_MODEL_FILTER,
  42. MODEL_FILTER_LIST,
  43. UPLOAD_DIR,
  44. AppConfig,
  45. )
  46. from utils.misc import calculate_sha256
  47. log = logging.getLogger(__name__)
  48. log.setLevel(SRC_LOG_LEVELS["OLLAMA"])
  49. app = FastAPI()
  50. app.add_middleware(
  51. CORSMiddleware,
  52. allow_origins=["*"],
  53. allow_credentials=True,
  54. allow_methods=["*"],
  55. allow_headers=["*"],
  56. )
  57. app.state.config = AppConfig()
  58. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  59. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  60. app.state.MODEL_CONFIG = Models.get_all_models()
  61. app.state.config.OLLAMA_BASE_URLS = OLLAMA_BASE_URLS
  62. app.state.MODELS = {}
  63. REQUEST_POOL = []
  64. # TODO: Implement a more intelligent load balancing mechanism for distributing requests among multiple backend instances.
  65. # Current implementation uses a simple round-robin approach (random.choice). Consider incorporating algorithms like weighted round-robin,
  66. # least connections, or least response time for better resource utilization and performance optimization.
  67. @app.middleware("http")
  68. async def check_url(request: Request, call_next):
  69. if len(app.state.MODELS) == 0:
  70. await get_all_models()
  71. else:
  72. pass
  73. response = await call_next(request)
  74. return response
  75. @app.head("/")
  76. @app.get("/")
  77. async def get_status():
  78. return {"status": True}
  79. @app.get("/urls")
  80. async def get_ollama_api_urls(user=Depends(get_admin_user)):
  81. return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
  82. class UrlUpdateForm(BaseModel):
  83. urls: List[str]
  84. @app.post("/urls/update")
  85. async def update_ollama_api_url(form_data: UrlUpdateForm, user=Depends(get_admin_user)):
  86. app.state.config.OLLAMA_BASE_URLS = form_data.urls
  87. log.info(f"app.state.config.OLLAMA_BASE_URLS: {app.state.config.OLLAMA_BASE_URLS}")
  88. return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
  89. @app.get("/cancel/{request_id}")
  90. async def cancel_ollama_request(request_id: str, user=Depends(get_current_user)):
  91. if user:
  92. if request_id in REQUEST_POOL:
  93. REQUEST_POOL.remove(request_id)
  94. return True
  95. else:
  96. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
  97. async def fetch_url(url):
  98. timeout = aiohttp.ClientTimeout(total=5)
  99. try:
  100. async with aiohttp.ClientSession(timeout=timeout) as session:
  101. async with session.get(url) as response:
  102. return await response.json()
  103. except Exception as e:
  104. # Handle connection error here
  105. log.error(f"Connection error: {e}")
  106. return None
  107. def merge_models_lists(model_lists):
  108. merged_models = {}
  109. for idx, model_list in enumerate(model_lists):
  110. if model_list is not None:
  111. for model in model_list:
  112. digest = model["digest"]
  113. if digest not in merged_models:
  114. model["urls"] = [idx]
  115. merged_models[digest] = model
  116. else:
  117. merged_models[digest]["urls"].append(idx)
  118. return list(merged_models.values())
  119. # user=Depends(get_current_user)
  120. async def get_all_models():
  121. log.info("get_all_models()")
  122. tasks = [fetch_url(f"{url}/api/tags") for url in app.state.config.OLLAMA_BASE_URLS]
  123. responses = await asyncio.gather(*tasks)
  124. models = {
  125. "models": merge_models_lists(
  126. map(
  127. lambda response: (response["models"] if response else None),
  128. responses,
  129. )
  130. )
  131. }
  132. for model in models["models"]:
  133. add_custom_info_to_model(model)
  134. app.state.MODELS = {model["model"]: model for model in models["models"]}
  135. return models
  136. def add_custom_info_to_model(model: dict):
  137. model["custom_info"] = next(
  138. (item for item in app.state.MODEL_CONFIG if item.id == model["model"]), None
  139. )
  140. @app.get("/api/tags")
  141. @app.get("/api/tags/{url_idx}")
  142. async def get_ollama_tags(
  143. url_idx: Optional[int] = None, user=Depends(get_verified_user)
  144. ):
  145. if url_idx == None:
  146. models = await get_all_models()
  147. if app.state.config.ENABLE_MODEL_FILTER:
  148. if user.role == "user":
  149. models["models"] = list(
  150. filter(
  151. lambda model: model["name"]
  152. in app.state.config.MODEL_FILTER_LIST,
  153. models["models"],
  154. )
  155. )
  156. return models
  157. return models
  158. else:
  159. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  160. try:
  161. r = requests.request(method="GET", url=f"{url}/api/tags")
  162. r.raise_for_status()
  163. return r.json()
  164. except Exception as e:
  165. log.exception(e)
  166. error_detail = "Open WebUI: Server Connection Error"
  167. if r is not None:
  168. try:
  169. res = r.json()
  170. if "error" in res:
  171. error_detail = f"Ollama: {res['error']}"
  172. except:
  173. error_detail = f"Ollama: {e}"
  174. raise HTTPException(
  175. status_code=r.status_code if r else 500,
  176. detail=error_detail,
  177. )
  178. @app.get("/api/version")
  179. @app.get("/api/version/{url_idx}")
  180. async def get_ollama_versions(url_idx: Optional[int] = None):
  181. if url_idx == None:
  182. # returns lowest version
  183. tasks = [
  184. fetch_url(f"{url}/api/version") for url in app.state.config.OLLAMA_BASE_URLS
  185. ]
  186. responses = await asyncio.gather(*tasks)
  187. responses = list(filter(lambda x: x is not None, responses))
  188. if len(responses) > 0:
  189. lowest_version = min(
  190. responses,
  191. key=lambda x: tuple(
  192. map(int, re.sub(r"^v|-.*", "", x["version"]).split("."))
  193. ),
  194. )
  195. return {"version": lowest_version["version"]}
  196. else:
  197. raise HTTPException(
  198. status_code=500,
  199. detail=ERROR_MESSAGES.OLLAMA_NOT_FOUND,
  200. )
  201. else:
  202. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  203. try:
  204. r = requests.request(method="GET", url=f"{url}/api/version")
  205. r.raise_for_status()
  206. return r.json()
  207. except Exception as e:
  208. log.exception(e)
  209. error_detail = "Open WebUI: Server Connection Error"
  210. if r is not None:
  211. try:
  212. res = r.json()
  213. if "error" in res:
  214. error_detail = f"Ollama: {res['error']}"
  215. except:
  216. error_detail = f"Ollama: {e}"
  217. raise HTTPException(
  218. status_code=r.status_code if r else 500,
  219. detail=error_detail,
  220. )
  221. class ModelNameForm(BaseModel):
  222. name: str
  223. @app.post("/api/pull")
  224. @app.post("/api/pull/{url_idx}")
  225. async def pull_model(
  226. form_data: ModelNameForm, url_idx: int = 0, user=Depends(get_admin_user)
  227. ):
  228. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  229. log.info(f"url: {url}")
  230. r = None
  231. def get_request():
  232. nonlocal url
  233. nonlocal r
  234. request_id = str(uuid.uuid4())
  235. try:
  236. REQUEST_POOL.append(request_id)
  237. def stream_content():
  238. try:
  239. yield json.dumps({"id": request_id, "done": False}) + "\n"
  240. for chunk in r.iter_content(chunk_size=8192):
  241. if request_id in REQUEST_POOL:
  242. yield chunk
  243. else:
  244. log.warning("User: canceled request")
  245. break
  246. finally:
  247. if hasattr(r, "close"):
  248. r.close()
  249. if request_id in REQUEST_POOL:
  250. REQUEST_POOL.remove(request_id)
  251. r = requests.request(
  252. method="POST",
  253. url=f"{url}/api/pull",
  254. data=form_data.model_dump_json(exclude_none=True).encode(),
  255. stream=True,
  256. )
  257. r.raise_for_status()
  258. return StreamingResponse(
  259. stream_content(),
  260. status_code=r.status_code,
  261. headers=dict(r.headers),
  262. )
  263. except Exception as e:
  264. raise e
  265. try:
  266. return await run_in_threadpool(get_request)
  267. except Exception as e:
  268. log.exception(e)
  269. error_detail = "Open WebUI: Server Connection Error"
  270. if r is not None:
  271. try:
  272. res = r.json()
  273. if "error" in res:
  274. error_detail = f"Ollama: {res['error']}"
  275. except:
  276. error_detail = f"Ollama: {e}"
  277. raise HTTPException(
  278. status_code=r.status_code if r else 500,
  279. detail=error_detail,
  280. )
  281. class PushModelForm(BaseModel):
  282. name: str
  283. insecure: Optional[bool] = None
  284. stream: Optional[bool] = None
  285. @app.delete("/api/push")
  286. @app.delete("/api/push/{url_idx}")
  287. async def push_model(
  288. form_data: PushModelForm,
  289. url_idx: Optional[int] = None,
  290. user=Depends(get_admin_user),
  291. ):
  292. if url_idx == None:
  293. if form_data.name in app.state.MODELS:
  294. url_idx = app.state.MODELS[form_data.name]["urls"][0]
  295. else:
  296. raise HTTPException(
  297. status_code=400,
  298. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  299. )
  300. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  301. log.debug(f"url: {url}")
  302. r = None
  303. def get_request():
  304. nonlocal url
  305. nonlocal r
  306. try:
  307. def stream_content():
  308. for chunk in r.iter_content(chunk_size=8192):
  309. yield chunk
  310. r = requests.request(
  311. method="POST",
  312. url=f"{url}/api/push",
  313. data=form_data.model_dump_json(exclude_none=True).encode(),
  314. )
  315. r.raise_for_status()
  316. return StreamingResponse(
  317. stream_content(),
  318. status_code=r.status_code,
  319. headers=dict(r.headers),
  320. )
  321. except Exception as e:
  322. raise e
  323. try:
  324. return await run_in_threadpool(get_request)
  325. except Exception as e:
  326. log.exception(e)
  327. error_detail = "Open WebUI: Server Connection Error"
  328. if r is not None:
  329. try:
  330. res = r.json()
  331. if "error" in res:
  332. error_detail = f"Ollama: {res['error']}"
  333. except:
  334. error_detail = f"Ollama: {e}"
  335. raise HTTPException(
  336. status_code=r.status_code if r else 500,
  337. detail=error_detail,
  338. )
  339. class CreateModelForm(BaseModel):
  340. name: str
  341. modelfile: Optional[str] = None
  342. stream: Optional[bool] = None
  343. path: Optional[str] = None
  344. @app.post("/api/create")
  345. @app.post("/api/create/{url_idx}")
  346. async def create_model(
  347. form_data: CreateModelForm, url_idx: int = 0, user=Depends(get_admin_user)
  348. ):
  349. log.debug(f"form_data: {form_data}")
  350. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  351. log.info(f"url: {url}")
  352. r = None
  353. def get_request():
  354. nonlocal url
  355. nonlocal r
  356. try:
  357. def stream_content():
  358. for chunk in r.iter_content(chunk_size=8192):
  359. yield chunk
  360. r = requests.request(
  361. method="POST",
  362. url=f"{url}/api/create",
  363. data=form_data.model_dump_json(exclude_none=True).encode(),
  364. stream=True,
  365. )
  366. r.raise_for_status()
  367. log.debug(f"r: {r}")
  368. return StreamingResponse(
  369. stream_content(),
  370. status_code=r.status_code,
  371. headers=dict(r.headers),
  372. )
  373. except Exception as e:
  374. raise e
  375. try:
  376. return await run_in_threadpool(get_request)
  377. except Exception as e:
  378. log.exception(e)
  379. error_detail = "Open WebUI: Server Connection Error"
  380. if r is not None:
  381. try:
  382. res = r.json()
  383. if "error" in res:
  384. error_detail = f"Ollama: {res['error']}"
  385. except:
  386. error_detail = f"Ollama: {e}"
  387. raise HTTPException(
  388. status_code=r.status_code if r else 500,
  389. detail=error_detail,
  390. )
  391. class CopyModelForm(BaseModel):
  392. source: str
  393. destination: str
  394. @app.post("/api/copy")
  395. @app.post("/api/copy/{url_idx}")
  396. async def copy_model(
  397. form_data: CopyModelForm,
  398. url_idx: Optional[int] = None,
  399. user=Depends(get_admin_user),
  400. ):
  401. if url_idx == None:
  402. if form_data.source in app.state.MODELS:
  403. url_idx = app.state.MODELS[form_data.source]["urls"][0]
  404. else:
  405. raise HTTPException(
  406. status_code=400,
  407. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.source),
  408. )
  409. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  410. log.info(f"url: {url}")
  411. try:
  412. r = requests.request(
  413. method="POST",
  414. url=f"{url}/api/copy",
  415. data=form_data.model_dump_json(exclude_none=True).encode(),
  416. )
  417. r.raise_for_status()
  418. log.debug(f"r.text: {r.text}")
  419. return True
  420. except Exception as e:
  421. log.exception(e)
  422. error_detail = "Open WebUI: Server Connection Error"
  423. if r is not None:
  424. try:
  425. res = r.json()
  426. if "error" in res:
  427. error_detail = f"Ollama: {res['error']}"
  428. except:
  429. error_detail = f"Ollama: {e}"
  430. raise HTTPException(
  431. status_code=r.status_code if r else 500,
  432. detail=error_detail,
  433. )
  434. @app.delete("/api/delete")
  435. @app.delete("/api/delete/{url_idx}")
  436. async def delete_model(
  437. form_data: ModelNameForm,
  438. url_idx: Optional[int] = None,
  439. user=Depends(get_admin_user),
  440. ):
  441. if url_idx == None:
  442. if form_data.name in app.state.MODELS:
  443. url_idx = app.state.MODELS[form_data.name]["urls"][0]
  444. else:
  445. raise HTTPException(
  446. status_code=400,
  447. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  448. )
  449. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  450. log.info(f"url: {url}")
  451. try:
  452. r = requests.request(
  453. method="DELETE",
  454. url=f"{url}/api/delete",
  455. data=form_data.model_dump_json(exclude_none=True).encode(),
  456. )
  457. r.raise_for_status()
  458. log.debug(f"r.text: {r.text}")
  459. return True
  460. except Exception as e:
  461. log.exception(e)
  462. error_detail = "Open WebUI: Server Connection Error"
  463. if r is not None:
  464. try:
  465. res = r.json()
  466. if "error" in res:
  467. error_detail = f"Ollama: {res['error']}"
  468. except:
  469. error_detail = f"Ollama: {e}"
  470. raise HTTPException(
  471. status_code=r.status_code if r else 500,
  472. detail=error_detail,
  473. )
  474. @app.post("/api/show")
  475. async def show_model_info(form_data: ModelNameForm, user=Depends(get_verified_user)):
  476. if form_data.name not in app.state.MODELS:
  477. raise HTTPException(
  478. status_code=400,
  479. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  480. )
  481. url_idx = random.choice(app.state.MODELS[form_data.name]["urls"])
  482. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  483. log.info(f"url: {url}")
  484. try:
  485. r = requests.request(
  486. method="POST",
  487. url=f"{url}/api/show",
  488. data=form_data.model_dump_json(exclude_none=True).encode(),
  489. )
  490. r.raise_for_status()
  491. return r.json()
  492. except Exception as e:
  493. log.exception(e)
  494. error_detail = "Open WebUI: Server Connection Error"
  495. if r is not None:
  496. try:
  497. res = r.json()
  498. if "error" in res:
  499. error_detail = f"Ollama: {res['error']}"
  500. except:
  501. error_detail = f"Ollama: {e}"
  502. raise HTTPException(
  503. status_code=r.status_code if r else 500,
  504. detail=error_detail,
  505. )
  506. class GenerateEmbeddingsForm(BaseModel):
  507. model: str
  508. prompt: str
  509. options: Optional[dict] = None
  510. keep_alive: Optional[Union[int, str]] = None
  511. @app.post("/api/embeddings")
  512. @app.post("/api/embeddings/{url_idx}")
  513. async def generate_embeddings(
  514. form_data: GenerateEmbeddingsForm,
  515. url_idx: Optional[int] = None,
  516. user=Depends(get_verified_user),
  517. ):
  518. if url_idx == None:
  519. model = form_data.model
  520. if ":" not in model:
  521. model = f"{model}:latest"
  522. if model in app.state.MODELS:
  523. url_idx = random.choice(app.state.MODELS[model]["urls"])
  524. else:
  525. raise HTTPException(
  526. status_code=400,
  527. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  528. )
  529. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  530. log.info(f"url: {url}")
  531. try:
  532. r = requests.request(
  533. method="POST",
  534. url=f"{url}/api/embeddings",
  535. data=form_data.model_dump_json(exclude_none=True).encode(),
  536. )
  537. r.raise_for_status()
  538. return r.json()
  539. except Exception as e:
  540. log.exception(e)
  541. error_detail = "Open WebUI: Server Connection Error"
  542. if r is not None:
  543. try:
  544. res = r.json()
  545. if "error" in res:
  546. error_detail = f"Ollama: {res['error']}"
  547. except:
  548. error_detail = f"Ollama: {e}"
  549. raise HTTPException(
  550. status_code=r.status_code if r else 500,
  551. detail=error_detail,
  552. )
  553. def generate_ollama_embeddings(
  554. form_data: GenerateEmbeddingsForm,
  555. url_idx: Optional[int] = None,
  556. ):
  557. log.info(f"generate_ollama_embeddings {form_data}")
  558. if url_idx == None:
  559. model = form_data.model
  560. if ":" not in model:
  561. model = f"{model}:latest"
  562. if model in app.state.MODELS:
  563. url_idx = random.choice(app.state.MODELS[model]["urls"])
  564. else:
  565. raise HTTPException(
  566. status_code=400,
  567. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  568. )
  569. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  570. log.info(f"url: {url}")
  571. try:
  572. r = requests.request(
  573. method="POST",
  574. url=f"{url}/api/embeddings",
  575. data=form_data.model_dump_json(exclude_none=True).encode(),
  576. )
  577. r.raise_for_status()
  578. data = r.json()
  579. log.info(f"generate_ollama_embeddings {data}")
  580. if "embedding" in data:
  581. return data["embedding"]
  582. else:
  583. raise "Something went wrong :/"
  584. except Exception as e:
  585. log.exception(e)
  586. error_detail = "Open WebUI: Server Connection Error"
  587. if r is not None:
  588. try:
  589. res = r.json()
  590. if "error" in res:
  591. error_detail = f"Ollama: {res['error']}"
  592. except:
  593. error_detail = f"Ollama: {e}"
  594. raise error_detail
  595. class GenerateCompletionForm(BaseModel):
  596. model: str
  597. prompt: str
  598. images: Optional[List[str]] = None
  599. format: Optional[str] = None
  600. options: Optional[dict] = None
  601. system: Optional[str] = None
  602. template: Optional[str] = None
  603. context: Optional[str] = None
  604. stream: Optional[bool] = True
  605. raw: Optional[bool] = None
  606. keep_alive: Optional[Union[int, str]] = None
  607. @app.post("/api/generate")
  608. @app.post("/api/generate/{url_idx}")
  609. async def generate_completion(
  610. form_data: GenerateCompletionForm,
  611. url_idx: Optional[int] = None,
  612. user=Depends(get_verified_user),
  613. ):
  614. if url_idx == None:
  615. model = form_data.model
  616. if ":" not in model:
  617. model = f"{model}:latest"
  618. if model in app.state.MODELS:
  619. url_idx = random.choice(app.state.MODELS[model]["urls"])
  620. else:
  621. raise HTTPException(
  622. status_code=400,
  623. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  624. )
  625. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  626. log.info(f"url: {url}")
  627. r = None
  628. def get_request():
  629. nonlocal form_data
  630. nonlocal r
  631. request_id = str(uuid.uuid4())
  632. try:
  633. REQUEST_POOL.append(request_id)
  634. def stream_content():
  635. try:
  636. if form_data.stream:
  637. yield json.dumps({"id": request_id, "done": False}) + "\n"
  638. for chunk in r.iter_content(chunk_size=8192):
  639. if request_id in REQUEST_POOL:
  640. yield chunk
  641. else:
  642. log.warning("User: canceled request")
  643. break
  644. finally:
  645. if hasattr(r, "close"):
  646. r.close()
  647. if request_id in REQUEST_POOL:
  648. REQUEST_POOL.remove(request_id)
  649. r = requests.request(
  650. method="POST",
  651. url=f"{url}/api/generate",
  652. data=form_data.model_dump_json(exclude_none=True).encode(),
  653. stream=True,
  654. )
  655. r.raise_for_status()
  656. return StreamingResponse(
  657. stream_content(),
  658. status_code=r.status_code,
  659. headers=dict(r.headers),
  660. )
  661. except Exception as e:
  662. raise e
  663. try:
  664. return await run_in_threadpool(get_request)
  665. except Exception as e:
  666. error_detail = "Open WebUI: Server Connection Error"
  667. if r is not None:
  668. try:
  669. res = r.json()
  670. if "error" in res:
  671. error_detail = f"Ollama: {res['error']}"
  672. except:
  673. error_detail = f"Ollama: {e}"
  674. raise HTTPException(
  675. status_code=r.status_code if r else 500,
  676. detail=error_detail,
  677. )
  678. class ChatMessage(BaseModel):
  679. role: str
  680. content: str
  681. images: Optional[List[str]] = None
  682. class GenerateChatCompletionForm(BaseModel):
  683. model: str
  684. messages: List[ChatMessage]
  685. format: Optional[str] = None
  686. options: Optional[dict] = None
  687. template: Optional[str] = None
  688. stream: Optional[bool] = None
  689. keep_alive: Optional[Union[int, str]] = None
  690. @app.post("/api/chat")
  691. @app.post("/api/chat/{url_idx}")
  692. async def generate_chat_completion(
  693. form_data: GenerateChatCompletionForm,
  694. url_idx: Optional[int] = None,
  695. user=Depends(get_verified_user),
  696. ):
  697. if url_idx == None:
  698. model = form_data.model
  699. if ":" not in model:
  700. model = f"{model}:latest"
  701. if model in app.state.MODELS:
  702. url_idx = random.choice(app.state.MODELS[model]["urls"])
  703. else:
  704. raise HTTPException(
  705. status_code=400,
  706. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  707. )
  708. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  709. log.info(f"url: {url}")
  710. r = None
  711. log.debug(
  712. "form_data.model_dump_json(exclude_none=True).encode(): {0} ".format(
  713. form_data.model_dump_json(exclude_none=True).encode()
  714. )
  715. )
  716. def get_request():
  717. nonlocal form_data
  718. nonlocal r
  719. request_id = str(uuid.uuid4())
  720. try:
  721. REQUEST_POOL.append(request_id)
  722. def stream_content():
  723. try:
  724. if form_data.stream:
  725. yield json.dumps({"id": request_id, "done": False}) + "\n"
  726. for chunk in r.iter_content(chunk_size=8192):
  727. if request_id in REQUEST_POOL:
  728. yield chunk
  729. else:
  730. log.warning("User: canceled request")
  731. break
  732. finally:
  733. if hasattr(r, "close"):
  734. r.close()
  735. if request_id in REQUEST_POOL:
  736. REQUEST_POOL.remove(request_id)
  737. r = requests.request(
  738. method="POST",
  739. url=f"{url}/api/chat",
  740. data=form_data.model_dump_json(exclude_none=True).encode(),
  741. stream=True,
  742. )
  743. r.raise_for_status()
  744. return StreamingResponse(
  745. stream_content(),
  746. status_code=r.status_code,
  747. headers=dict(r.headers),
  748. )
  749. except Exception as e:
  750. log.exception(e)
  751. raise e
  752. try:
  753. return await run_in_threadpool(get_request)
  754. except Exception as e:
  755. error_detail = "Open WebUI: Server Connection Error"
  756. if r is not None:
  757. try:
  758. res = r.json()
  759. if "error" in res:
  760. error_detail = f"Ollama: {res['error']}"
  761. except:
  762. error_detail = f"Ollama: {e}"
  763. raise HTTPException(
  764. status_code=r.status_code if r else 500,
  765. detail=error_detail,
  766. )
  767. # TODO: we should update this part once Ollama supports other types
  768. class OpenAIChatMessage(BaseModel):
  769. role: str
  770. content: str
  771. model_config = ConfigDict(extra="allow")
  772. class OpenAIChatCompletionForm(BaseModel):
  773. model: str
  774. messages: List[OpenAIChatMessage]
  775. model_config = ConfigDict(extra="allow")
  776. @app.post("/v1/chat/completions")
  777. @app.post("/v1/chat/completions/{url_idx}")
  778. async def generate_openai_chat_completion(
  779. form_data: OpenAIChatCompletionForm,
  780. url_idx: Optional[int] = None,
  781. user=Depends(get_verified_user),
  782. ):
  783. if url_idx == None:
  784. model = form_data.model
  785. if ":" not in model:
  786. model = f"{model}:latest"
  787. if model in app.state.MODELS:
  788. url_idx = random.choice(app.state.MODELS[model]["urls"])
  789. else:
  790. raise HTTPException(
  791. status_code=400,
  792. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  793. )
  794. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  795. log.info(f"url: {url}")
  796. r = None
  797. def get_request():
  798. nonlocal form_data
  799. nonlocal r
  800. request_id = str(uuid.uuid4())
  801. try:
  802. REQUEST_POOL.append(request_id)
  803. def stream_content():
  804. try:
  805. if form_data.stream:
  806. yield json.dumps(
  807. {"request_id": request_id, "done": False}
  808. ) + "\n"
  809. for chunk in r.iter_content(chunk_size=8192):
  810. if request_id in REQUEST_POOL:
  811. yield chunk
  812. else:
  813. log.warning("User: canceled request")
  814. break
  815. finally:
  816. if hasattr(r, "close"):
  817. r.close()
  818. if request_id in REQUEST_POOL:
  819. REQUEST_POOL.remove(request_id)
  820. r = requests.request(
  821. method="POST",
  822. url=f"{url}/v1/chat/completions",
  823. data=form_data.model_dump_json(exclude_none=True).encode(),
  824. stream=True,
  825. )
  826. r.raise_for_status()
  827. return StreamingResponse(
  828. stream_content(),
  829. status_code=r.status_code,
  830. headers=dict(r.headers),
  831. )
  832. except Exception as e:
  833. raise e
  834. try:
  835. return await run_in_threadpool(get_request)
  836. except Exception as e:
  837. error_detail = "Open WebUI: Server Connection Error"
  838. if r is not None:
  839. try:
  840. res = r.json()
  841. if "error" in res:
  842. error_detail = f"Ollama: {res['error']}"
  843. except:
  844. error_detail = f"Ollama: {e}"
  845. raise HTTPException(
  846. status_code=r.status_code if r else 500,
  847. detail=error_detail,
  848. )
  849. @app.get("/v1/models")
  850. @app.get("/v1/models/{url_idx}")
  851. async def get_openai_models(
  852. url_idx: Optional[int] = None,
  853. user=Depends(get_verified_user),
  854. ):
  855. if url_idx == None:
  856. models = await get_all_models()
  857. if app.state.config.ENABLE_MODEL_FILTER:
  858. if user.role == "user":
  859. models["models"] = list(
  860. filter(
  861. lambda model: model["name"]
  862. in app.state.config.MODEL_FILTER_LIST,
  863. models["models"],
  864. )
  865. )
  866. return {
  867. "data": [
  868. {
  869. "id": model["model"],
  870. "object": "model",
  871. "created": int(time.time()),
  872. "owned_by": "openai",
  873. }
  874. for model in models["models"]
  875. ],
  876. "object": "list",
  877. }
  878. else:
  879. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  880. try:
  881. r = requests.request(method="GET", url=f"{url}/api/tags")
  882. r.raise_for_status()
  883. models = r.json()
  884. return {
  885. "data": [
  886. {
  887. "id": model["model"],
  888. "object": "model",
  889. "created": int(time.time()),
  890. "owned_by": "openai",
  891. }
  892. for model in models["models"]
  893. ],
  894. "object": "list",
  895. }
  896. except Exception as e:
  897. log.exception(e)
  898. error_detail = "Open WebUI: Server Connection Error"
  899. if r is not None:
  900. try:
  901. res = r.json()
  902. if "error" in res:
  903. error_detail = f"Ollama: {res['error']}"
  904. except:
  905. error_detail = f"Ollama: {e}"
  906. raise HTTPException(
  907. status_code=r.status_code if r else 500,
  908. detail=error_detail,
  909. )
  910. class UrlForm(BaseModel):
  911. url: str
  912. class UploadBlobForm(BaseModel):
  913. filename: str
  914. def parse_huggingface_url(hf_url):
  915. try:
  916. # Parse the URL
  917. parsed_url = urlparse(hf_url)
  918. # Get the path and split it into components
  919. path_components = parsed_url.path.split("/")
  920. # Extract the desired output
  921. user_repo = "/".join(path_components[1:3])
  922. model_file = path_components[-1]
  923. return model_file
  924. except ValueError:
  925. return None
  926. async def download_file_stream(
  927. ollama_url, file_url, file_path, file_name, chunk_size=1024 * 1024
  928. ):
  929. done = False
  930. if os.path.exists(file_path):
  931. current_size = os.path.getsize(file_path)
  932. else:
  933. current_size = 0
  934. headers = {"Range": f"bytes={current_size}-"} if current_size > 0 else {}
  935. timeout = aiohttp.ClientTimeout(total=600) # Set the timeout
  936. async with aiohttp.ClientSession(timeout=timeout) as session:
  937. async with session.get(file_url, headers=headers) as response:
  938. total_size = int(response.headers.get("content-length", 0)) + current_size
  939. with open(file_path, "ab+") as file:
  940. async for data in response.content.iter_chunked(chunk_size):
  941. current_size += len(data)
  942. file.write(data)
  943. done = current_size == total_size
  944. progress = round((current_size / total_size) * 100, 2)
  945. yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n'
  946. if done:
  947. file.seek(0)
  948. hashed = calculate_sha256(file)
  949. file.seek(0)
  950. url = f"{ollama_url}/api/blobs/sha256:{hashed}"
  951. response = requests.post(url, data=file)
  952. if response.ok:
  953. res = {
  954. "done": done,
  955. "blob": f"sha256:{hashed}",
  956. "name": file_name,
  957. }
  958. os.remove(file_path)
  959. yield f"data: {json.dumps(res)}\n\n"
  960. else:
  961. raise "Ollama: Could not create blob, Please try again."
  962. # def number_generator():
  963. # for i in range(1, 101):
  964. # yield f"data: {i}\n"
  965. # url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf"
  966. @app.post("/models/download")
  967. @app.post("/models/download/{url_idx}")
  968. async def download_model(
  969. form_data: UrlForm,
  970. url_idx: Optional[int] = None,
  971. ):
  972. allowed_hosts = ["https://huggingface.co/", "https://github.com/"]
  973. if not any(form_data.url.startswith(host) for host in allowed_hosts):
  974. raise HTTPException(
  975. status_code=400,
  976. detail="Invalid file_url. Only URLs from allowed hosts are permitted.",
  977. )
  978. if url_idx == None:
  979. url_idx = 0
  980. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  981. file_name = parse_huggingface_url(form_data.url)
  982. if file_name:
  983. file_path = f"{UPLOAD_DIR}/{file_name}"
  984. return StreamingResponse(
  985. download_file_stream(url, form_data.url, file_path, file_name),
  986. )
  987. else:
  988. return None
  989. @app.post("/models/upload")
  990. @app.post("/models/upload/{url_idx}")
  991. def upload_model(file: UploadFile = File(...), url_idx: Optional[int] = None):
  992. if url_idx == None:
  993. url_idx = 0
  994. ollama_url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  995. file_path = f"{UPLOAD_DIR}/{file.filename}"
  996. # Save file in chunks
  997. with open(file_path, "wb+") as f:
  998. for chunk in file.file:
  999. f.write(chunk)
  1000. def file_process_stream():
  1001. nonlocal ollama_url
  1002. total_size = os.path.getsize(file_path)
  1003. chunk_size = 1024 * 1024
  1004. try:
  1005. with open(file_path, "rb") as f:
  1006. total = 0
  1007. done = False
  1008. while not done:
  1009. chunk = f.read(chunk_size)
  1010. if not chunk:
  1011. done = True
  1012. continue
  1013. total += len(chunk)
  1014. progress = round((total / total_size) * 100, 2)
  1015. res = {
  1016. "progress": progress,
  1017. "total": total_size,
  1018. "completed": total,
  1019. }
  1020. yield f"data: {json.dumps(res)}\n\n"
  1021. if done:
  1022. f.seek(0)
  1023. hashed = calculate_sha256(f)
  1024. f.seek(0)
  1025. url = f"{ollama_url}/api/blobs/sha256:{hashed}"
  1026. response = requests.post(url, data=f)
  1027. if response.ok:
  1028. res = {
  1029. "done": done,
  1030. "blob": f"sha256:{hashed}",
  1031. "name": file.filename,
  1032. }
  1033. os.remove(file_path)
  1034. yield f"data: {json.dumps(res)}\n\n"
  1035. else:
  1036. raise Exception(
  1037. "Ollama: Could not create blob, Please try again."
  1038. )
  1039. except Exception as e:
  1040. res = {"error": str(e)}
  1041. yield f"data: {json.dumps(res)}\n\n"
  1042. return StreamingResponse(file_process_stream(), media_type="text/event-stream")
  1043. # async def upload_model(file: UploadFile = File(), url_idx: Optional[int] = None):
  1044. # if url_idx == None:
  1045. # url_idx = 0
  1046. # url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  1047. # file_location = os.path.join(UPLOAD_DIR, file.filename)
  1048. # total_size = file.size
  1049. # async def file_upload_generator(file):
  1050. # print(file)
  1051. # try:
  1052. # async with aiofiles.open(file_location, "wb") as f:
  1053. # completed_size = 0
  1054. # while True:
  1055. # chunk = await file.read(1024*1024)
  1056. # if not chunk:
  1057. # break
  1058. # await f.write(chunk)
  1059. # completed_size += len(chunk)
  1060. # progress = (completed_size / total_size) * 100
  1061. # print(progress)
  1062. # yield f'data: {json.dumps({"status": "uploading", "percentage": progress, "total": total_size, "completed": completed_size, "done": False})}\n'
  1063. # except Exception as e:
  1064. # print(e)
  1065. # yield f"data: {json.dumps({'status': 'error', 'message': str(e)})}\n"
  1066. # finally:
  1067. # await file.close()
  1068. # print("done")
  1069. # yield f'data: {json.dumps({"status": "completed", "percentage": 100, "total": total_size, "completed": completed_size, "done": True})}\n'
  1070. # return StreamingResponse(
  1071. # file_upload_generator(copy.deepcopy(file)), media_type="text/event-stream"
  1072. # )
  1073. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  1074. async def deprecated_proxy(
  1075. path: str, request: Request, user=Depends(get_verified_user)
  1076. ):
  1077. url = app.state.config.OLLAMA_BASE_URLS[0]
  1078. target_url = f"{url}/{path}"
  1079. body = await request.body()
  1080. headers = dict(request.headers)
  1081. if user.role in ["user", "admin"]:
  1082. if path in ["pull", "delete", "push", "copy", "create"]:
  1083. if user.role != "admin":
  1084. raise HTTPException(
  1085. status_code=status.HTTP_401_UNAUTHORIZED,
  1086. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  1087. )
  1088. else:
  1089. raise HTTPException(
  1090. status_code=status.HTTP_401_UNAUTHORIZED,
  1091. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  1092. )
  1093. headers.pop("host", None)
  1094. headers.pop("authorization", None)
  1095. headers.pop("origin", None)
  1096. headers.pop("referer", None)
  1097. r = None
  1098. def get_request():
  1099. nonlocal r
  1100. request_id = str(uuid.uuid4())
  1101. try:
  1102. REQUEST_POOL.append(request_id)
  1103. def stream_content():
  1104. try:
  1105. if path == "generate":
  1106. data = json.loads(body.decode("utf-8"))
  1107. if not ("stream" in data and data["stream"] == False):
  1108. yield json.dumps({"id": request_id, "done": False}) + "\n"
  1109. elif path == "chat":
  1110. yield json.dumps({"id": request_id, "done": False}) + "\n"
  1111. for chunk in r.iter_content(chunk_size=8192):
  1112. if request_id in REQUEST_POOL:
  1113. yield chunk
  1114. else:
  1115. log.warning("User: canceled request")
  1116. break
  1117. finally:
  1118. if hasattr(r, "close"):
  1119. r.close()
  1120. if request_id in REQUEST_POOL:
  1121. REQUEST_POOL.remove(request_id)
  1122. r = requests.request(
  1123. method=request.method,
  1124. url=target_url,
  1125. data=body,
  1126. headers=headers,
  1127. stream=True,
  1128. )
  1129. r.raise_for_status()
  1130. # r.close()
  1131. return StreamingResponse(
  1132. stream_content(),
  1133. status_code=r.status_code,
  1134. headers=dict(r.headers),
  1135. )
  1136. except Exception as e:
  1137. raise e
  1138. try:
  1139. return await run_in_threadpool(get_request)
  1140. except Exception as e:
  1141. error_detail = "Open WebUI: Server Connection Error"
  1142. if r is not None:
  1143. try:
  1144. res = r.json()
  1145. if "error" in res:
  1146. error_detail = f"Ollama: {res['error']}"
  1147. except:
  1148. error_detail = f"Ollama: {e}"
  1149. raise HTTPException(
  1150. status_code=r.status_code if r else 500,
  1151. detail=error_detail,
  1152. )