main.py 38 KB

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