main.py 46 KB

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