main.py 39 KB

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