main.py 40 KB

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