main.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  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. AIOHTTP_CLIENT_TIMEOUT,
  15. CORS_ALLOW_ORIGIN,
  16. ENABLE_MODEL_FILTER,
  17. ENABLE_OLLAMA_API,
  18. MODEL_FILTER_LIST,
  19. OLLAMA_BASE_URLS,
  20. UPLOAD_DIR,
  21. AppConfig,
  22. )
  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=5)
  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. @app.post("/api/embed")
  443. @app.post("/api/embed/{url_idx}")
  444. @app.post("/api/embeddings")
  445. @app.post("/api/embeddings/{url_idx}")
  446. async def generate_embeddings(
  447. form_data: GenerateEmbeddingsForm,
  448. url_idx: Optional[int] = None,
  449. user=Depends(get_verified_user),
  450. ):
  451. if url_idx is None:
  452. model = form_data.model
  453. if ":" not in model:
  454. model = f"{model}:latest"
  455. if model in app.state.MODELS:
  456. url_idx = random.choice(app.state.MODELS[model]["urls"])
  457. else:
  458. raise HTTPException(
  459. status_code=400,
  460. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  461. )
  462. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  463. log.info(f"url: {url}")
  464. r = requests.request(
  465. method="POST",
  466. url=f"{url}/api/embed",
  467. headers={"Content-Type": "application/json"},
  468. data=form_data.model_dump_json(exclude_none=True).encode(),
  469. )
  470. try:
  471. r.raise_for_status()
  472. return r.json()
  473. except Exception as e:
  474. log.exception(e)
  475. error_detail = "Open WebUI: Server Connection Error"
  476. if r is not None:
  477. try:
  478. res = r.json()
  479. if "error" in res:
  480. error_detail = f"Ollama: {res['error']}"
  481. except Exception:
  482. error_detail = f"Ollama: {e}"
  483. raise HTTPException(
  484. status_code=r.status_code if r else 500,
  485. detail=error_detail,
  486. )
  487. def generate_ollama_embeddings(
  488. form_data: GenerateEmbeddingsForm,
  489. url_idx: Optional[int] = None,
  490. ):
  491. log.info(f"generate_ollama_embeddings {form_data}")
  492. if url_idx is None:
  493. model = form_data.model
  494. if ":" not in model:
  495. model = f"{model}:latest"
  496. if model in app.state.MODELS:
  497. url_idx = random.choice(app.state.MODELS[model]["urls"])
  498. else:
  499. raise HTTPException(
  500. status_code=400,
  501. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  502. )
  503. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  504. log.info(f"url: {url}")
  505. r = requests.request(
  506. method="POST",
  507. url=f"{url}/api/embeddings",
  508. headers={"Content-Type": "application/json"},
  509. data=form_data.model_dump_json(exclude_none=True).encode(),
  510. )
  511. try:
  512. r.raise_for_status()
  513. data = r.json()
  514. log.info(f"generate_ollama_embeddings {data}")
  515. if "embedding" in data:
  516. return data["embedding"]
  517. else:
  518. raise Exception("Something went wrong :/")
  519. except Exception as e:
  520. log.exception(e)
  521. error_detail = "Open WebUI: Server Connection Error"
  522. if r is not None:
  523. try:
  524. res = r.json()
  525. if "error" in res:
  526. error_detail = f"Ollama: {res['error']}"
  527. except Exception:
  528. error_detail = f"Ollama: {e}"
  529. raise Exception(error_detail)
  530. class GenerateCompletionForm(BaseModel):
  531. model: str
  532. prompt: str
  533. images: Optional[list[str]] = None
  534. format: Optional[str] = None
  535. options: Optional[dict] = None
  536. system: Optional[str] = None
  537. template: Optional[str] = None
  538. context: Optional[str] = None
  539. stream: Optional[bool] = True
  540. raw: Optional[bool] = None
  541. keep_alive: Optional[Union[int, str]] = None
  542. @app.post("/api/generate")
  543. @app.post("/api/generate/{url_idx}")
  544. async def generate_completion(
  545. form_data: GenerateCompletionForm,
  546. url_idx: Optional[int] = None,
  547. user=Depends(get_verified_user),
  548. ):
  549. if url_idx is None:
  550. model = form_data.model
  551. if ":" not in model:
  552. model = f"{model}:latest"
  553. if model in app.state.MODELS:
  554. url_idx = random.choice(app.state.MODELS[model]["urls"])
  555. else:
  556. raise HTTPException(
  557. status_code=400,
  558. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  559. )
  560. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  561. log.info(f"url: {url}")
  562. return await post_streaming_url(
  563. f"{url}/api/generate", form_data.model_dump_json(exclude_none=True).encode()
  564. )
  565. class ChatMessage(BaseModel):
  566. role: str
  567. content: str
  568. images: Optional[list[str]] = None
  569. class GenerateChatCompletionForm(BaseModel):
  570. model: str
  571. messages: list[ChatMessage]
  572. format: Optional[str] = None
  573. options: Optional[dict] = None
  574. template: Optional[str] = None
  575. stream: Optional[bool] = None
  576. keep_alive: Optional[Union[int, str]] = None
  577. def get_ollama_url(url_idx: Optional[int], model: str):
  578. if url_idx is None:
  579. if model not in app.state.MODELS:
  580. raise HTTPException(
  581. status_code=400,
  582. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model),
  583. )
  584. url_idx = random.choice(app.state.MODELS[model]["urls"])
  585. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  586. return url
  587. @app.post("/api/chat")
  588. @app.post("/api/chat/{url_idx}")
  589. async def generate_chat_completion(
  590. form_data: GenerateChatCompletionForm,
  591. url_idx: Optional[int] = None,
  592. user=Depends(get_verified_user),
  593. ):
  594. payload = {**form_data.model_dump(exclude_none=True)}
  595. log.debug(f"{payload = }")
  596. if "metadata" in payload:
  597. del payload["metadata"]
  598. model_id = form_data.model
  599. if app.state.config.ENABLE_MODEL_FILTER:
  600. if user.role == "user" and model_id not in app.state.config.MODEL_FILTER_LIST:
  601. raise HTTPException(
  602. status_code=403,
  603. detail="Model not found",
  604. )
  605. model_info = Models.get_model_by_id(model_id)
  606. if model_info:
  607. if model_info.base_model_id:
  608. payload["model"] = model_info.base_model_id
  609. params = model_info.params.model_dump()
  610. if params:
  611. if payload.get("options") is None:
  612. payload["options"] = {}
  613. payload["options"] = apply_model_params_to_body_ollama(
  614. params, payload["options"]
  615. )
  616. payload = apply_model_system_prompt_to_body(params, payload, user)
  617. if ":" not in payload["model"]:
  618. payload["model"] = f"{payload['model']}:latest"
  619. url = get_ollama_url(url_idx, payload["model"])
  620. log.info(f"url: {url}")
  621. log.debug(payload)
  622. return await post_streaming_url(
  623. f"{url}/api/chat", json.dumps(payload), content_type="application/x-ndjson"
  624. )
  625. # TODO: we should update this part once Ollama supports other types
  626. class OpenAIChatMessageContent(BaseModel):
  627. type: str
  628. model_config = ConfigDict(extra="allow")
  629. class OpenAIChatMessage(BaseModel):
  630. role: str
  631. content: Union[str, OpenAIChatMessageContent]
  632. model_config = ConfigDict(extra="allow")
  633. class OpenAIChatCompletionForm(BaseModel):
  634. model: str
  635. messages: list[OpenAIChatMessage]
  636. model_config = ConfigDict(extra="allow")
  637. @app.post("/v1/chat/completions")
  638. @app.post("/v1/chat/completions/{url_idx}")
  639. async def generate_openai_chat_completion(
  640. form_data: dict,
  641. url_idx: Optional[int] = None,
  642. user=Depends(get_verified_user),
  643. ):
  644. completion_form = OpenAIChatCompletionForm(**form_data)
  645. payload = {**completion_form.model_dump(exclude_none=True, exclude=["metadata"])}
  646. if "metadata" in payload:
  647. del payload["metadata"]
  648. model_id = completion_form.model
  649. if app.state.config.ENABLE_MODEL_FILTER:
  650. if user.role == "user" and model_id not in app.state.config.MODEL_FILTER_LIST:
  651. raise HTTPException(
  652. status_code=403,
  653. detail="Model not found",
  654. )
  655. model_info = Models.get_model_by_id(model_id)
  656. if model_info:
  657. if model_info.base_model_id:
  658. payload["model"] = model_info.base_model_id
  659. params = model_info.params.model_dump()
  660. if params:
  661. payload = apply_model_params_to_body_openai(params, payload)
  662. payload = apply_model_system_prompt_to_body(params, payload, user)
  663. if ":" not in payload["model"]:
  664. payload["model"] = f"{payload['model']}:latest"
  665. url = get_ollama_url(url_idx, payload["model"])
  666. log.info(f"url: {url}")
  667. return await post_streaming_url(
  668. f"{url}/v1/chat/completions",
  669. json.dumps(payload),
  670. stream=payload.get("stream", False),
  671. )
  672. @app.get("/v1/models")
  673. @app.get("/v1/models/{url_idx}")
  674. async def get_openai_models(
  675. url_idx: Optional[int] = None,
  676. user=Depends(get_verified_user),
  677. ):
  678. if url_idx is None:
  679. models = await get_all_models()
  680. if app.state.config.ENABLE_MODEL_FILTER:
  681. if user.role == "user":
  682. models["models"] = list(
  683. filter(
  684. lambda model: model["name"]
  685. in app.state.config.MODEL_FILTER_LIST,
  686. models["models"],
  687. )
  688. )
  689. return {
  690. "data": [
  691. {
  692. "id": model["model"],
  693. "object": "model",
  694. "created": int(time.time()),
  695. "owned_by": "openai",
  696. }
  697. for model in models["models"]
  698. ],
  699. "object": "list",
  700. }
  701. else:
  702. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  703. try:
  704. r = requests.request(method="GET", url=f"{url}/api/tags")
  705. r.raise_for_status()
  706. models = r.json()
  707. return {
  708. "data": [
  709. {
  710. "id": model["model"],
  711. "object": "model",
  712. "created": int(time.time()),
  713. "owned_by": "openai",
  714. }
  715. for model in models["models"]
  716. ],
  717. "object": "list",
  718. }
  719. except Exception as e:
  720. log.exception(e)
  721. error_detail = "Open WebUI: Server Connection Error"
  722. if r is not None:
  723. try:
  724. res = r.json()
  725. if "error" in res:
  726. error_detail = f"Ollama: {res['error']}"
  727. except Exception:
  728. error_detail = f"Ollama: {e}"
  729. raise HTTPException(
  730. status_code=r.status_code if r else 500,
  731. detail=error_detail,
  732. )
  733. class UrlForm(BaseModel):
  734. url: str
  735. class UploadBlobForm(BaseModel):
  736. filename: str
  737. def parse_huggingface_url(hf_url):
  738. try:
  739. # Parse the URL
  740. parsed_url = urlparse(hf_url)
  741. # Get the path and split it into components
  742. path_components = parsed_url.path.split("/")
  743. # Extract the desired output
  744. model_file = path_components[-1]
  745. return model_file
  746. except ValueError:
  747. return None
  748. async def download_file_stream(
  749. ollama_url, file_url, file_path, file_name, chunk_size=1024 * 1024
  750. ):
  751. done = False
  752. if os.path.exists(file_path):
  753. current_size = os.path.getsize(file_path)
  754. else:
  755. current_size = 0
  756. headers = {"Range": f"bytes={current_size}-"} if current_size > 0 else {}
  757. timeout = aiohttp.ClientTimeout(total=600) # Set the timeout
  758. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  759. async with session.get(file_url, headers=headers) as response:
  760. total_size = int(response.headers.get("content-length", 0)) + current_size
  761. with open(file_path, "ab+") as file:
  762. async for data in response.content.iter_chunked(chunk_size):
  763. current_size += len(data)
  764. file.write(data)
  765. done = current_size == total_size
  766. progress = round((current_size / total_size) * 100, 2)
  767. yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n'
  768. if done:
  769. file.seek(0)
  770. hashed = calculate_sha256(file)
  771. file.seek(0)
  772. url = f"{ollama_url}/api/blobs/sha256:{hashed}"
  773. response = requests.post(url, data=file)
  774. if response.ok:
  775. res = {
  776. "done": done,
  777. "blob": f"sha256:{hashed}",
  778. "name": file_name,
  779. }
  780. os.remove(file_path)
  781. yield f"data: {json.dumps(res)}\n\n"
  782. else:
  783. raise "Ollama: Could not create blob, Please try again."
  784. # url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf"
  785. @app.post("/models/download")
  786. @app.post("/models/download/{url_idx}")
  787. async def download_model(
  788. form_data: UrlForm,
  789. url_idx: Optional[int] = None,
  790. user=Depends(get_admin_user),
  791. ):
  792. allowed_hosts = ["https://huggingface.co/", "https://github.com/"]
  793. if not any(form_data.url.startswith(host) for host in allowed_hosts):
  794. raise HTTPException(
  795. status_code=400,
  796. detail="Invalid file_url. Only URLs from allowed hosts are permitted.",
  797. )
  798. if url_idx is None:
  799. url_idx = 0
  800. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  801. file_name = parse_huggingface_url(form_data.url)
  802. if file_name:
  803. file_path = f"{UPLOAD_DIR}/{file_name}"
  804. return StreamingResponse(
  805. download_file_stream(url, form_data.url, file_path, file_name),
  806. )
  807. else:
  808. return None
  809. @app.post("/models/upload")
  810. @app.post("/models/upload/{url_idx}")
  811. def upload_model(
  812. file: UploadFile = File(...),
  813. url_idx: Optional[int] = None,
  814. user=Depends(get_admin_user),
  815. ):
  816. if url_idx is None:
  817. url_idx = 0
  818. ollama_url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  819. file_path = f"{UPLOAD_DIR}/{file.filename}"
  820. # Save file in chunks
  821. with open(file_path, "wb+") as f:
  822. for chunk in file.file:
  823. f.write(chunk)
  824. def file_process_stream():
  825. nonlocal ollama_url
  826. total_size = os.path.getsize(file_path)
  827. chunk_size = 1024 * 1024
  828. try:
  829. with open(file_path, "rb") as f:
  830. total = 0
  831. done = False
  832. while not done:
  833. chunk = f.read(chunk_size)
  834. if not chunk:
  835. done = True
  836. continue
  837. total += len(chunk)
  838. progress = round((total / total_size) * 100, 2)
  839. res = {
  840. "progress": progress,
  841. "total": total_size,
  842. "completed": total,
  843. }
  844. yield f"data: {json.dumps(res)}\n\n"
  845. if done:
  846. f.seek(0)
  847. hashed = calculate_sha256(f)
  848. f.seek(0)
  849. url = f"{ollama_url}/api/blobs/sha256:{hashed}"
  850. response = requests.post(url, data=f)
  851. if response.ok:
  852. res = {
  853. "done": done,
  854. "blob": f"sha256:{hashed}",
  855. "name": file.filename,
  856. }
  857. os.remove(file_path)
  858. yield f"data: {json.dumps(res)}\n\n"
  859. else:
  860. raise Exception(
  861. "Ollama: Could not create blob, Please try again."
  862. )
  863. except Exception as e:
  864. res = {"error": str(e)}
  865. yield f"data: {json.dumps(res)}\n\n"
  866. return StreamingResponse(file_process_stream(), media_type="text/event-stream")