main.py 39 KB

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