main.py 46 KB

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