main.py 30 KB

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