main.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  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.utils 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. class ModelNameForm(BaseModel):
  357. name: str
  358. @app.post("/api/pull")
  359. @app.post("/api/pull/{url_idx}")
  360. async def pull_model(
  361. form_data: ModelNameForm, url_idx: int = 0, user=Depends(get_admin_user)
  362. ):
  363. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  364. log.info(f"url: {url}")
  365. # Admin should be able to pull models from any source
  366. payload = {**form_data.model_dump(exclude_none=True), "insecure": True}
  367. return await post_streaming_url(f"{url}/api/pull", json.dumps(payload))
  368. class PushModelForm(BaseModel):
  369. name: str
  370. insecure: Optional[bool] = None
  371. stream: Optional[bool] = None
  372. @app.delete("/api/push")
  373. @app.delete("/api/push/{url_idx}")
  374. async def push_model(
  375. form_data: PushModelForm,
  376. url_idx: Optional[int] = None,
  377. user=Depends(get_admin_user),
  378. ):
  379. if url_idx is None:
  380. model_list = await get_all_models()
  381. models = {model["model"]: model for model in model_list["models"]}
  382. if form_data.name in models:
  383. url_idx = models[form_data.name]["urls"][0]
  384. else:
  385. raise HTTPException(
  386. status_code=400,
  387. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  388. )
  389. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  390. log.debug(f"url: {url}")
  391. return await post_streaming_url(
  392. f"{url}/api/push", form_data.model_dump_json(exclude_none=True).encode()
  393. )
  394. class CreateModelForm(BaseModel):
  395. name: str
  396. modelfile: Optional[str] = None
  397. stream: Optional[bool] = None
  398. path: Optional[str] = None
  399. @app.post("/api/create")
  400. @app.post("/api/create/{url_idx}")
  401. async def create_model(
  402. form_data: CreateModelForm, url_idx: int = 0, user=Depends(get_admin_user)
  403. ):
  404. log.debug(f"form_data: {form_data}")
  405. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  406. log.info(f"url: {url}")
  407. return await post_streaming_url(
  408. f"{url}/api/create", form_data.model_dump_json(exclude_none=True).encode()
  409. )
  410. class CopyModelForm(BaseModel):
  411. source: str
  412. destination: str
  413. @app.post("/api/copy")
  414. @app.post("/api/copy/{url_idx}")
  415. async def copy_model(
  416. form_data: CopyModelForm,
  417. url_idx: Optional[int] = None,
  418. user=Depends(get_admin_user),
  419. ):
  420. if url_idx is None:
  421. model_list = await get_all_models()
  422. models = {model["model"]: model for model in model_list["models"]}
  423. if form_data.source in models:
  424. url_idx = models[form_data.source]["urls"][0]
  425. else:
  426. raise HTTPException(
  427. status_code=400,
  428. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.source),
  429. )
  430. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  431. log.info(f"url: {url}")
  432. parsed_url = urlparse(url)
  433. base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
  434. api_config = app.state.config.OLLAMA_API_CONFIGS.get(base_url, {})
  435. key = api_config.get("key", None)
  436. headers = {"Content-Type": "application/json"}
  437. if key:
  438. headers["Authorization"] = f"Bearer {key}"
  439. r = requests.request(
  440. method="POST",
  441. url=f"{url}/api/copy",
  442. headers=headers,
  443. data=form_data.model_dump_json(exclude_none=True).encode(),
  444. )
  445. try:
  446. r.raise_for_status()
  447. log.debug(f"r.text: {r.text}")
  448. return True
  449. except Exception as e:
  450. log.exception(e)
  451. error_detail = "Open WebUI: Server Connection Error"
  452. if r is not None:
  453. try:
  454. res = r.json()
  455. if "error" in res:
  456. error_detail = f"Ollama: {res['error']}"
  457. except Exception:
  458. error_detail = f"Ollama: {e}"
  459. raise HTTPException(
  460. status_code=r.status_code if r else 500,
  461. detail=error_detail,
  462. )
  463. @app.delete("/api/delete")
  464. @app.delete("/api/delete/{url_idx}")
  465. async def delete_model(
  466. form_data: ModelNameForm,
  467. url_idx: Optional[int] = None,
  468. user=Depends(get_admin_user),
  469. ):
  470. if url_idx is None:
  471. model_list = await get_all_models()
  472. models = {model["model"]: model for model in model_list["models"]}
  473. if form_data.name in models:
  474. url_idx = models[form_data.name]["urls"][0]
  475. else:
  476. raise HTTPException(
  477. status_code=400,
  478. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  479. )
  480. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  481. log.info(f"url: {url}")
  482. parsed_url = urlparse(url)
  483. base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
  484. api_config = app.state.config.OLLAMA_API_CONFIGS.get(base_url, {})
  485. key = api_config.get("key", None)
  486. headers = {"Content-Type": "application/json"}
  487. if key:
  488. headers["Authorization"] = f"Bearer {key}"
  489. r = requests.request(
  490. method="DELETE",
  491. url=f"{url}/api/delete",
  492. data=form_data.model_dump_json(exclude_none=True).encode(),
  493. headers=headers,
  494. )
  495. try:
  496. r.raise_for_status()
  497. log.debug(f"r.text: {r.text}")
  498. return True
  499. except Exception as e:
  500. log.exception(e)
  501. error_detail = "Open WebUI: Server Connection Error"
  502. if r is not None:
  503. try:
  504. res = r.json()
  505. if "error" in res:
  506. error_detail = f"Ollama: {res['error']}"
  507. except Exception:
  508. error_detail = f"Ollama: {e}"
  509. raise HTTPException(
  510. status_code=r.status_code if r else 500,
  511. detail=error_detail,
  512. )
  513. @app.post("/api/show")
  514. async def show_model_info(form_data: ModelNameForm, user=Depends(get_verified_user)):
  515. model_list = await get_all_models()
  516. models = {model["model"]: model for model in model_list["models"]}
  517. if form_data.name not in models:
  518. raise HTTPException(
  519. status_code=400,
  520. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  521. )
  522. url_idx = random.choice(models[form_data.name]["urls"])
  523. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  524. log.info(f"url: {url}")
  525. parsed_url = urlparse(url)
  526. base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
  527. api_config = app.state.config.OLLAMA_API_CONFIGS.get(base_url, {})
  528. key = api_config.get("key", None)
  529. headers = {"Content-Type": "application/json"}
  530. if key:
  531. headers["Authorization"] = f"Bearer {key}"
  532. r = requests.request(
  533. method="POST",
  534. url=f"{url}/api/show",
  535. headers=headers,
  536. data=form_data.model_dump_json(exclude_none=True).encode(),
  537. )
  538. try:
  539. r.raise_for_status()
  540. return r.json()
  541. except Exception as e:
  542. log.exception(e)
  543. error_detail = "Open WebUI: Server Connection Error"
  544. if r is not None:
  545. try:
  546. res = r.json()
  547. if "error" in res:
  548. error_detail = f"Ollama: {res['error']}"
  549. except Exception:
  550. error_detail = f"Ollama: {e}"
  551. raise HTTPException(
  552. status_code=r.status_code if r else 500,
  553. detail=error_detail,
  554. )
  555. class GenerateEmbeddingsForm(BaseModel):
  556. model: str
  557. prompt: str
  558. options: Optional[dict] = None
  559. keep_alive: Optional[Union[int, str]] = None
  560. class GenerateEmbedForm(BaseModel):
  561. model: str
  562. input: list[str] | str
  563. truncate: Optional[bool] = None
  564. options: Optional[dict] = None
  565. keep_alive: Optional[Union[int, str]] = None
  566. @app.post("/api/embed")
  567. @app.post("/api/embed/{url_idx}")
  568. async def generate_embeddings(
  569. form_data: GenerateEmbedForm,
  570. url_idx: Optional[int] = None,
  571. user=Depends(get_verified_user),
  572. ):
  573. return await generate_ollama_batch_embeddings(form_data, url_idx)
  574. @app.post("/api/embeddings")
  575. @app.post("/api/embeddings/{url_idx}")
  576. async def generate_embeddings(
  577. form_data: GenerateEmbeddingsForm,
  578. url_idx: Optional[int] = None,
  579. user=Depends(get_verified_user),
  580. ):
  581. return await generate_ollama_embeddings(form_data=form_data, url_idx=url_idx)
  582. async def generate_ollama_embeddings(
  583. form_data: GenerateEmbeddingsForm,
  584. url_idx: Optional[int] = None,
  585. ):
  586. log.info(f"generate_ollama_embeddings {form_data}")
  587. if url_idx is None:
  588. model_list = await get_all_models()
  589. models = {model["model"]: model for model in model_list["models"]}
  590. model = form_data.model
  591. if ":" not in model:
  592. model = f"{model}:latest"
  593. if model in models:
  594. url_idx = random.choice(models[model]["urls"])
  595. else:
  596. raise HTTPException(
  597. status_code=400,
  598. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  599. )
  600. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  601. log.info(f"url: {url}")
  602. parsed_url = urlparse(url)
  603. base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
  604. api_config = app.state.config.OLLAMA_API_CONFIGS.get(base_url, {})
  605. key = api_config.get("key", None)
  606. headers = {"Content-Type": "application/json"}
  607. if key:
  608. headers["Authorization"] = f"Bearer {key}"
  609. r = requests.request(
  610. method="POST",
  611. url=f"{url}/api/embeddings",
  612. headers=headers,
  613. data=form_data.model_dump_json(exclude_none=True).encode(),
  614. )
  615. try:
  616. r.raise_for_status()
  617. data = r.json()
  618. log.info(f"generate_ollama_embeddings {data}")
  619. if "embedding" in data:
  620. return data
  621. else:
  622. raise Exception("Something went wrong :/")
  623. except Exception as e:
  624. log.exception(e)
  625. error_detail = "Open WebUI: Server Connection Error"
  626. if r is not None:
  627. try:
  628. res = r.json()
  629. if "error" in res:
  630. error_detail = f"Ollama: {res['error']}"
  631. except Exception:
  632. error_detail = f"Ollama: {e}"
  633. raise HTTPException(
  634. status_code=r.status_code if r else 500,
  635. detail=error_detail,
  636. )
  637. async def generate_ollama_batch_embeddings(
  638. form_data: GenerateEmbedForm,
  639. url_idx: Optional[int] = None,
  640. ):
  641. log.info(f"generate_ollama_batch_embeddings {form_data}")
  642. if url_idx is None:
  643. model_list = await get_all_models()
  644. models = {model["model"]: model for model in model_list["models"]}
  645. model = form_data.model
  646. if ":" not in model:
  647. model = f"{model}:latest"
  648. if model in models:
  649. url_idx = random.choice(models[model]["urls"])
  650. else:
  651. raise HTTPException(
  652. status_code=400,
  653. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  654. )
  655. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  656. log.info(f"url: {url}")
  657. parsed_url = urlparse(url)
  658. base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
  659. api_config = app.state.config.OLLAMA_API_CONFIGS.get(base_url, {})
  660. key = api_config.get("key", None)
  661. headers = {"Content-Type": "application/json"}
  662. if key:
  663. headers["Authorization"] = f"Bearer {key}"
  664. r = requests.request(
  665. method="POST",
  666. url=f"{url}/api/embed",
  667. headers=headers,
  668. data=form_data.model_dump_json(exclude_none=True).encode(),
  669. )
  670. try:
  671. r.raise_for_status()
  672. data = r.json()
  673. log.info(f"generate_ollama_batch_embeddings {data}")
  674. if "embeddings" in data:
  675. return data
  676. else:
  677. raise Exception("Something went wrong :/")
  678. except Exception as e:
  679. log.exception(e)
  680. error_detail = "Open WebUI: Server Connection Error"
  681. if r is not None:
  682. try:
  683. res = r.json()
  684. if "error" in res:
  685. error_detail = f"Ollama: {res['error']}"
  686. except Exception:
  687. error_detail = f"Ollama: {e}"
  688. raise Exception(error_detail)
  689. class GenerateCompletionForm(BaseModel):
  690. model: str
  691. prompt: str
  692. suffix: Optional[str] = None
  693. images: Optional[list[str]] = None
  694. format: Optional[str] = None
  695. options: Optional[dict] = None
  696. system: Optional[str] = None
  697. template: Optional[str] = None
  698. context: Optional[list[int]] = None
  699. stream: Optional[bool] = True
  700. raw: Optional[bool] = None
  701. keep_alive: Optional[Union[int, str]] = None
  702. @app.post("/api/generate")
  703. @app.post("/api/generate/{url_idx}")
  704. async def generate_completion(
  705. form_data: GenerateCompletionForm,
  706. url_idx: Optional[int] = None,
  707. user=Depends(get_verified_user),
  708. ):
  709. if url_idx is None:
  710. model_list = await get_all_models()
  711. models = {model["model"]: model for model in model_list["models"]}
  712. model = form_data.model
  713. if ":" not in model:
  714. model = f"{model}:latest"
  715. if model in models:
  716. url_idx = random.choice(models[model]["urls"])
  717. else:
  718. raise HTTPException(
  719. status_code=400,
  720. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  721. )
  722. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  723. api_config = app.state.config.OLLAMA_API_CONFIGS.get(url, {})
  724. prefix_id = api_config.get("prefix_id", None)
  725. if prefix_id:
  726. form_data.model = form_data.model.replace(f"{prefix_id}.", "")
  727. log.info(f"url: {url}")
  728. return await post_streaming_url(
  729. f"{url}/api/generate", form_data.model_dump_json(exclude_none=True).encode()
  730. )
  731. class ChatMessage(BaseModel):
  732. role: str
  733. content: str
  734. images: Optional[list[str]] = None
  735. class GenerateChatCompletionForm(BaseModel):
  736. model: str
  737. messages: list[ChatMessage]
  738. format: Optional[str] = None
  739. options: Optional[dict] = None
  740. template: Optional[str] = None
  741. stream: Optional[bool] = True
  742. keep_alive: Optional[Union[int, str]] = None
  743. async def get_ollama_url(url_idx: Optional[int], model: str):
  744. if url_idx is None:
  745. model_list = await get_all_models()
  746. models = {model["model"]: model for model in model_list["models"]}
  747. if model not in models:
  748. raise HTTPException(
  749. status_code=400,
  750. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model),
  751. )
  752. url_idx = random.choice(models[model]["urls"])
  753. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  754. return url
  755. @app.post("/api/chat")
  756. @app.post("/api/chat/{url_idx}")
  757. async def generate_chat_completion(
  758. form_data: GenerateChatCompletionForm,
  759. url_idx: Optional[int] = None,
  760. user=Depends(get_verified_user),
  761. bypass_filter: Optional[bool] = False,
  762. ):
  763. payload = {**form_data.model_dump(exclude_none=True)}
  764. log.debug(f"generate_chat_completion() - 1.payload = {payload}")
  765. if "metadata" in payload:
  766. del payload["metadata"]
  767. model_id = payload["model"]
  768. model_info = Models.get_model_by_id(model_id)
  769. if model_info:
  770. if model_info.base_model_id:
  771. payload["model"] = model_info.base_model_id
  772. params = model_info.params.model_dump()
  773. if params:
  774. if payload.get("options") is None:
  775. payload["options"] = {}
  776. payload["options"] = apply_model_params_to_body_ollama(
  777. params, payload["options"]
  778. )
  779. payload = apply_model_system_prompt_to_body(params, payload, user)
  780. # Check if user has access to the model
  781. if not bypass_filter and user.role == "user":
  782. if not (
  783. user.id == model_info.user_id
  784. or has_access(
  785. user.id, type="read", access_control=model_info.access_control
  786. )
  787. ):
  788. raise HTTPException(
  789. status_code=403,
  790. detail="Model not found",
  791. )
  792. elif not bypass_filter:
  793. if user.role != "admin":
  794. raise HTTPException(
  795. status_code=403,
  796. detail="Model not found",
  797. )
  798. if ":" not in payload["model"]:
  799. payload["model"] = f"{payload['model']}:latest"
  800. url = await get_ollama_url(url_idx, payload["model"])
  801. log.info(f"url: {url}")
  802. log.debug(f"generate_chat_completion() - 2.payload = {payload}")
  803. parsed_url = urlparse(url)
  804. base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
  805. api_config = app.state.config.OLLAMA_API_CONFIGS.get(base_url, {})
  806. prefix_id = api_config.get("prefix_id", None)
  807. if prefix_id:
  808. payload["model"] = payload["model"].replace(f"{prefix_id}.", "")
  809. return await post_streaming_url(
  810. f"{url}/api/chat",
  811. json.dumps(payload),
  812. stream=form_data.stream,
  813. content_type="application/x-ndjson",
  814. )
  815. # TODO: we should update this part once Ollama supports other types
  816. class OpenAIChatMessageContent(BaseModel):
  817. type: str
  818. model_config = ConfigDict(extra="allow")
  819. class OpenAIChatMessage(BaseModel):
  820. role: str
  821. content: Union[str, list[OpenAIChatMessageContent]]
  822. model_config = ConfigDict(extra="allow")
  823. class OpenAIChatCompletionForm(BaseModel):
  824. model: str
  825. messages: list[OpenAIChatMessage]
  826. model_config = ConfigDict(extra="allow")
  827. @app.post("/v1/chat/completions")
  828. @app.post("/v1/chat/completions/{url_idx}")
  829. async def generate_openai_chat_completion(
  830. form_data: dict,
  831. url_idx: Optional[int] = None,
  832. user=Depends(get_verified_user),
  833. ):
  834. try:
  835. completion_form = OpenAIChatCompletionForm(**form_data)
  836. except Exception as e:
  837. log.exception(e)
  838. raise HTTPException(
  839. status_code=400,
  840. detail=str(e),
  841. )
  842. payload = {**completion_form.model_dump(exclude_none=True, exclude=["metadata"])}
  843. if "metadata" in payload:
  844. del payload["metadata"]
  845. model_id = completion_form.model
  846. if ":" not in model_id:
  847. model_id = f"{model_id}:latest"
  848. model_info = Models.get_model_by_id(model_id)
  849. if model_info:
  850. if model_info.base_model_id:
  851. payload["model"] = model_info.base_model_id
  852. params = model_info.params.model_dump()
  853. if params:
  854. payload = apply_model_params_to_body_openai(params, payload)
  855. payload = apply_model_system_prompt_to_body(params, payload, user)
  856. # Check if user has access to the model
  857. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  858. if not (
  859. user.id == model_info.user_id
  860. or has_access(
  861. user.id, type="read", access_control=model_info.access_control
  862. )
  863. ):
  864. raise HTTPException(
  865. status_code=403,
  866. detail="Model not found",
  867. )
  868. else:
  869. if user.role != "admin":
  870. raise HTTPException(
  871. status_code=403,
  872. detail="Model not found",
  873. )
  874. if ":" not in payload["model"]:
  875. payload["model"] = f"{payload['model']}:latest"
  876. url = await get_ollama_url(url_idx, payload["model"])
  877. log.info(f"url: {url}")
  878. api_config = app.state.config.OLLAMA_API_CONFIGS.get(url, {})
  879. prefix_id = api_config.get("prefix_id", None)
  880. if prefix_id:
  881. payload["model"] = payload["model"].replace(f"{prefix_id}.", "")
  882. return await post_streaming_url(
  883. f"{url}/v1/chat/completions",
  884. json.dumps(payload),
  885. stream=payload.get("stream", False),
  886. )
  887. @app.get("/v1/models")
  888. @app.get("/v1/models/{url_idx}")
  889. async def get_openai_models(
  890. url_idx: Optional[int] = None,
  891. user=Depends(get_verified_user),
  892. ):
  893. models = []
  894. if url_idx is None:
  895. model_list = await get_all_models()
  896. models = [
  897. {
  898. "id": model["model"],
  899. "object": "model",
  900. "created": int(time.time()),
  901. "owned_by": "openai",
  902. }
  903. for model in model_list["models"]
  904. ]
  905. else:
  906. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  907. try:
  908. r = requests.request(method="GET", url=f"{url}/api/tags")
  909. r.raise_for_status()
  910. model_list = r.json()
  911. models = [
  912. {
  913. "id": model["model"],
  914. "object": "model",
  915. "created": int(time.time()),
  916. "owned_by": "openai",
  917. }
  918. for model in models["models"]
  919. ]
  920. except Exception as e:
  921. log.exception(e)
  922. error_detail = "Open WebUI: Server Connection Error"
  923. if r is not None:
  924. try:
  925. res = r.json()
  926. if "error" in res:
  927. error_detail = f"Ollama: {res['error']}"
  928. except Exception:
  929. error_detail = f"Ollama: {e}"
  930. raise HTTPException(
  931. status_code=r.status_code if r else 500,
  932. detail=error_detail,
  933. )
  934. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  935. # Filter models based on user access control
  936. filtered_models = []
  937. for model in models:
  938. model_info = Models.get_model_by_id(model["id"])
  939. if model_info:
  940. if user.id == model_info.user_id or has_access(
  941. user.id, type="read", access_control=model_info.access_control
  942. ):
  943. filtered_models.append(model)
  944. models = filtered_models
  945. return {
  946. "data": models,
  947. "object": "list",
  948. }
  949. class UrlForm(BaseModel):
  950. url: str
  951. class UploadBlobForm(BaseModel):
  952. filename: str
  953. def parse_huggingface_url(hf_url):
  954. try:
  955. # Parse the URL
  956. parsed_url = urlparse(hf_url)
  957. # Get the path and split it into components
  958. path_components = parsed_url.path.split("/")
  959. # Extract the desired output
  960. model_file = path_components[-1]
  961. return model_file
  962. except ValueError:
  963. return None
  964. async def download_file_stream(
  965. ollama_url, file_url, file_path, file_name, chunk_size=1024 * 1024
  966. ):
  967. done = False
  968. if os.path.exists(file_path):
  969. current_size = os.path.getsize(file_path)
  970. else:
  971. current_size = 0
  972. headers = {"Range": f"bytes={current_size}-"} if current_size > 0 else {}
  973. timeout = aiohttp.ClientTimeout(total=600) # Set the timeout
  974. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  975. async with session.get(file_url, headers=headers) as response:
  976. total_size = int(response.headers.get("content-length", 0)) + current_size
  977. with open(file_path, "ab+") as file:
  978. async for data in response.content.iter_chunked(chunk_size):
  979. current_size += len(data)
  980. file.write(data)
  981. done = current_size == total_size
  982. progress = round((current_size / total_size) * 100, 2)
  983. yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n'
  984. if done:
  985. file.seek(0)
  986. hashed = calculate_sha256(file)
  987. file.seek(0)
  988. url = f"{ollama_url}/api/blobs/sha256:{hashed}"
  989. response = requests.post(url, data=file)
  990. if response.ok:
  991. res = {
  992. "done": done,
  993. "blob": f"sha256:{hashed}",
  994. "name": file_name,
  995. }
  996. os.remove(file_path)
  997. yield f"data: {json.dumps(res)}\n\n"
  998. else:
  999. raise "Ollama: Could not create blob, Please try again."
  1000. # url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf"
  1001. @app.post("/models/download")
  1002. @app.post("/models/download/{url_idx}")
  1003. async def download_model(
  1004. form_data: UrlForm,
  1005. url_idx: Optional[int] = None,
  1006. user=Depends(get_admin_user),
  1007. ):
  1008. allowed_hosts = ["https://huggingface.co/", "https://github.com/"]
  1009. if not any(form_data.url.startswith(host) for host in allowed_hosts):
  1010. raise HTTPException(
  1011. status_code=400,
  1012. detail="Invalid file_url. Only URLs from allowed hosts are permitted.",
  1013. )
  1014. if url_idx is None:
  1015. url_idx = 0
  1016. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  1017. file_name = parse_huggingface_url(form_data.url)
  1018. if file_name:
  1019. file_path = f"{UPLOAD_DIR}/{file_name}"
  1020. return StreamingResponse(
  1021. download_file_stream(url, form_data.url, file_path, file_name),
  1022. )
  1023. else:
  1024. return None
  1025. @app.post("/models/upload")
  1026. @app.post("/models/upload/{url_idx}")
  1027. def upload_model(
  1028. file: UploadFile = File(...),
  1029. url_idx: Optional[int] = None,
  1030. user=Depends(get_admin_user),
  1031. ):
  1032. if url_idx is None:
  1033. url_idx = 0
  1034. ollama_url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  1035. file_path = f"{UPLOAD_DIR}/{file.filename}"
  1036. # Save file in chunks
  1037. with open(file_path, "wb+") as f:
  1038. for chunk in file.file:
  1039. f.write(chunk)
  1040. def file_process_stream():
  1041. nonlocal ollama_url
  1042. total_size = os.path.getsize(file_path)
  1043. chunk_size = 1024 * 1024
  1044. try:
  1045. with open(file_path, "rb") as f:
  1046. total = 0
  1047. done = False
  1048. while not done:
  1049. chunk = f.read(chunk_size)
  1050. if not chunk:
  1051. done = True
  1052. continue
  1053. total += len(chunk)
  1054. progress = round((total / total_size) * 100, 2)
  1055. res = {
  1056. "progress": progress,
  1057. "total": total_size,
  1058. "completed": total,
  1059. }
  1060. yield f"data: {json.dumps(res)}\n\n"
  1061. if done:
  1062. f.seek(0)
  1063. hashed = calculate_sha256(f)
  1064. f.seek(0)
  1065. url = f"{ollama_url}/api/blobs/sha256:{hashed}"
  1066. response = requests.post(url, data=f)
  1067. if response.ok:
  1068. res = {
  1069. "done": done,
  1070. "blob": f"sha256:{hashed}",
  1071. "name": file.filename,
  1072. }
  1073. os.remove(file_path)
  1074. yield f"data: {json.dumps(res)}\n\n"
  1075. else:
  1076. raise Exception(
  1077. "Ollama: Could not create blob, Please try again."
  1078. )
  1079. except Exception as e:
  1080. res = {"error": str(e)}
  1081. yield f"data: {json.dumps(res)}\n\n"
  1082. return StreamingResponse(file_process_stream(), media_type="text/event-stream")