main.py 38 KB

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