main.py 39 KB

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