main.py 43 KB

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