main.py 40 KB

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