main.py 40 KB

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