main.py 40 KB

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