main.py 32 KB

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