main.py 36 KB

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