main.py 36 KB

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