main.py 36 KB

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