main.py 39 KB

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