main.py 33 KB

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