main.py 33 KB

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