main.py 31 KB

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