main.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  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, List, 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 utils.task import prompt_template
  31. from config import (
  32. SRC_LOG_LEVELS,
  33. OLLAMA_BASE_URLS,
  34. ENABLE_OLLAMA_API,
  35. AIOHTTP_CLIENT_TIMEOUT,
  36. ENABLE_MODEL_FILTER,
  37. MODEL_FILTER_LIST,
  38. UPLOAD_DIR,
  39. AppConfig,
  40. )
  41. from utils.misc import (
  42. apply_model_params_to_body_ollama,
  43. calculate_sha256,
  44. add_or_update_system_message,
  45. apply_model_params_to_body_openai,
  46. apply_model_system_prompt_to_body,
  47. )
  48. log = logging.getLogger(__name__)
  49. log.setLevel(SRC_LOG_LEVELS["OLLAMA"])
  50. app = FastAPI()
  51. app.add_middleware(
  52. CORSMiddleware,
  53. allow_origins=["*"],
  54. allow_credentials=True,
  55. allow_methods=["*"],
  56. allow_headers=["*"],
  57. )
  58. app.state.config = AppConfig()
  59. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  60. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  61. app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
  62. app.state.config.OLLAMA_BASE_URLS = OLLAMA_BASE_URLS
  63. app.state.MODELS = {}
  64. # TODO: Implement a more intelligent load balancing mechanism for distributing requests among multiple backend instances.
  65. # Current implementation uses a simple round-robin approach (random.choice). Consider incorporating algorithms like weighted round-robin,
  66. # least connections, or least response time for better resource utilization and performance optimization.
  67. @app.middleware("http")
  68. async def check_url(request: Request, call_next):
  69. if len(app.state.MODELS) == 0:
  70. await get_all_models()
  71. else:
  72. pass
  73. response = await call_next(request)
  74. return response
  75. @app.head("/")
  76. @app.get("/")
  77. async def get_status():
  78. return {"status": True}
  79. @app.get("/config")
  80. async def get_config(user=Depends(get_admin_user)):
  81. return {"ENABLE_OLLAMA_API": app.state.config.ENABLE_OLLAMA_API}
  82. class OllamaConfigForm(BaseModel):
  83. enable_ollama_api: Optional[bool] = None
  84. @app.post("/config/update")
  85. async def update_config(form_data: OllamaConfigForm, user=Depends(get_admin_user)):
  86. app.state.config.ENABLE_OLLAMA_API = form_data.enable_ollama_api
  87. return {"ENABLE_OLLAMA_API": app.state.config.ENABLE_OLLAMA_API}
  88. @app.get("/urls")
  89. async def get_ollama_api_urls(user=Depends(get_admin_user)):
  90. return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
  91. class UrlUpdateForm(BaseModel):
  92. urls: List[str]
  93. @app.post("/urls/update")
  94. async def update_ollama_api_url(form_data: UrlUpdateForm, user=Depends(get_admin_user)):
  95. app.state.config.OLLAMA_BASE_URLS = form_data.urls
  96. log.info(f"app.state.config.OLLAMA_BASE_URLS: {app.state.config.OLLAMA_BASE_URLS}")
  97. return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
  98. async def fetch_url(url):
  99. timeout = aiohttp.ClientTimeout(total=5)
  100. try:
  101. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  102. async with session.get(url) as response:
  103. return await response.json()
  104. except Exception as e:
  105. # Handle connection error here
  106. log.error(f"Connection error: {e}")
  107. return None
  108. async def cleanup_response(
  109. response: Optional[aiohttp.ClientResponse],
  110. session: Optional[aiohttp.ClientSession],
  111. ):
  112. if response:
  113. response.close()
  114. if session:
  115. await session.close()
  116. async def post_streaming_url(url: str, payload: str, stream: bool = True):
  117. r = None
  118. try:
  119. session = aiohttp.ClientSession(
  120. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  121. )
  122. r = await session.post(url, data=payload)
  123. r.raise_for_status()
  124. if stream:
  125. return StreamingResponse(
  126. r.content,
  127. status_code=r.status,
  128. headers=dict(r.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. data=form_data.model_dump_json(exclude_none=True).encode(),
  343. )
  344. try:
  345. r.raise_for_status()
  346. log.debug(f"r.text: {r.text}")
  347. return True
  348. except Exception as e:
  349. log.exception(e)
  350. error_detail = "Open WebUI: Server Connection Error"
  351. if r is not None:
  352. try:
  353. res = r.json()
  354. if "error" in res:
  355. error_detail = f"Ollama: {res['error']}"
  356. except Exception:
  357. error_detail = f"Ollama: {e}"
  358. raise HTTPException(
  359. status_code=r.status_code if r else 500,
  360. detail=error_detail,
  361. )
  362. @app.delete("/api/delete")
  363. @app.delete("/api/delete/{url_idx}")
  364. async def delete_model(
  365. form_data: ModelNameForm,
  366. url_idx: Optional[int] = None,
  367. user=Depends(get_admin_user),
  368. ):
  369. if url_idx is None:
  370. if form_data.name in app.state.MODELS:
  371. url_idx = app.state.MODELS[form_data.name]["urls"][0]
  372. else:
  373. raise HTTPException(
  374. status_code=400,
  375. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  376. )
  377. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  378. log.info(f"url: {url}")
  379. r = requests.request(
  380. method="DELETE",
  381. url=f"{url}/api/delete",
  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. data=form_data.model_dump_json(exclude_none=True).encode(),
  416. )
  417. try:
  418. r.raise_for_status()
  419. return r.json()
  420. except Exception as e:
  421. log.exception(e)
  422. error_detail = "Open WebUI: Server Connection Error"
  423. if r is not None:
  424. try:
  425. res = r.json()
  426. if "error" in res:
  427. error_detail = f"Ollama: {res['error']}"
  428. except Exception:
  429. error_detail = f"Ollama: {e}"
  430. raise HTTPException(
  431. status_code=r.status_code if r else 500,
  432. detail=error_detail,
  433. )
  434. class GenerateEmbeddingsForm(BaseModel):
  435. model: str
  436. prompt: str
  437. options: Optional[dict] = None
  438. keep_alive: Optional[Union[int, str]] = None
  439. @app.post("/api/embeddings")
  440. @app.post("/api/embeddings/{url_idx}")
  441. async def generate_embeddings(
  442. form_data: GenerateEmbeddingsForm,
  443. url_idx: Optional[int] = None,
  444. user=Depends(get_verified_user),
  445. ):
  446. if url_idx is None:
  447. model = form_data.model
  448. if ":" not in model:
  449. model = f"{model}:latest"
  450. if model in app.state.MODELS:
  451. url_idx = random.choice(app.state.MODELS[model]["urls"])
  452. else:
  453. raise HTTPException(
  454. status_code=400,
  455. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  456. )
  457. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  458. log.info(f"url: {url}")
  459. r = requests.request(
  460. method="POST",
  461. url=f"{url}/api/embeddings",
  462. data=form_data.model_dump_json(exclude_none=True).encode(),
  463. )
  464. try:
  465. r.raise_for_status()
  466. return r.json()
  467. except Exception as e:
  468. log.exception(e)
  469. error_detail = "Open WebUI: Server Connection Error"
  470. if r is not None:
  471. try:
  472. res = r.json()
  473. if "error" in res:
  474. error_detail = f"Ollama: {res['error']}"
  475. except Exception:
  476. error_detail = f"Ollama: {e}"
  477. raise HTTPException(
  478. status_code=r.status_code if r else 500,
  479. detail=error_detail,
  480. )
  481. def generate_ollama_embeddings(
  482. form_data: GenerateEmbeddingsForm,
  483. url_idx: Optional[int] = None,
  484. ):
  485. log.info(f"generate_ollama_embeddings {form_data}")
  486. if url_idx is None:
  487. model = form_data.model
  488. if ":" not in model:
  489. model = f"{model}:latest"
  490. if model in app.state.MODELS:
  491. url_idx = random.choice(app.state.MODELS[model]["urls"])
  492. else:
  493. raise HTTPException(
  494. status_code=400,
  495. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  496. )
  497. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  498. log.info(f"url: {url}")
  499. r = requests.request(
  500. method="POST",
  501. url=f"{url}/api/embeddings",
  502. data=form_data.model_dump_json(exclude_none=True).encode(),
  503. )
  504. try:
  505. r.raise_for_status()
  506. data = r.json()
  507. log.info(f"generate_ollama_embeddings {data}")
  508. if "embedding" in data:
  509. return data["embedding"]
  510. else:
  511. raise Exception("Something went wrong :/")
  512. except Exception as e:
  513. log.exception(e)
  514. error_detail = "Open WebUI: Server Connection Error"
  515. if r is not None:
  516. try:
  517. res = r.json()
  518. if "error" in res:
  519. error_detail = f"Ollama: {res['error']}"
  520. except Exception:
  521. error_detail = f"Ollama: {e}"
  522. raise Exception(error_detail)
  523. class GenerateCompletionForm(BaseModel):
  524. model: str
  525. prompt: str
  526. images: Optional[List[str]] = None
  527. format: Optional[str] = None
  528. options: Optional[dict] = None
  529. system: Optional[str] = None
  530. template: Optional[str] = None
  531. context: Optional[str] = None
  532. stream: Optional[bool] = True
  533. raw: Optional[bool] = None
  534. keep_alive: Optional[Union[int, str]] = None
  535. @app.post("/api/generate")
  536. @app.post("/api/generate/{url_idx}")
  537. async def generate_completion(
  538. form_data: GenerateCompletionForm,
  539. url_idx: Optional[int] = None,
  540. user=Depends(get_verified_user),
  541. ):
  542. if url_idx is None:
  543. model = form_data.model
  544. if ":" not in model:
  545. model = f"{model}:latest"
  546. if model in app.state.MODELS:
  547. url_idx = random.choice(app.state.MODELS[model]["urls"])
  548. else:
  549. raise HTTPException(
  550. status_code=400,
  551. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  552. )
  553. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  554. log.info(f"url: {url}")
  555. return await post_streaming_url(
  556. f"{url}/api/generate", form_data.model_dump_json(exclude_none=True).encode()
  557. )
  558. class ChatMessage(BaseModel):
  559. role: str
  560. content: str
  561. images: Optional[List[str]] = None
  562. class GenerateChatCompletionForm(BaseModel):
  563. model: str
  564. messages: List[ChatMessage]
  565. format: Optional[str] = None
  566. options: Optional[dict] = None
  567. template: Optional[str] = None
  568. stream: Optional[bool] = None
  569. keep_alive: Optional[Union[int, str]] = None
  570. def get_ollama_url(url_idx: Optional[int], model: str):
  571. if url_idx is None:
  572. if model not in app.state.MODELS:
  573. raise HTTPException(
  574. status_code=400,
  575. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model),
  576. )
  577. url_idx = random.choice(app.state.MODELS[model]["urls"])
  578. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  579. return url
  580. @app.post("/api/chat")
  581. @app.post("/api/chat/{url_idx}")
  582. async def generate_chat_completion(
  583. form_data: GenerateChatCompletionForm,
  584. url_idx: Optional[int] = None,
  585. user=Depends(get_verified_user),
  586. ):
  587. log.debug(f"{form_data.model_dump_json(exclude_none=True).encode()}=")
  588. payload = {
  589. **form_data.model_dump(exclude_none=True, exclude=["metadata"]),
  590. }
  591. payload.pop("metadata")
  592. model_id = form_data.model
  593. model_info = Models.get_model_by_id(model_id)
  594. if model_info:
  595. if model_info.base_model_id:
  596. payload["model"] = model_info.base_model_id
  597. params = model_info.params.model_dump()
  598. if params:
  599. if payload.get("options") is None:
  600. payload["options"] = {}
  601. payload["options"] = apply_model_params_to_body_ollama(
  602. params, payload["options"]
  603. )
  604. payload = apply_model_system_prompt_to_body(params, payload, user)
  605. if ":" not in payload["model"]:
  606. payload["model"] = f"{payload['model']}:latest"
  607. url = get_ollama_url(url_idx, payload["model"])
  608. log.info(f"url: {url}")
  609. log.debug(payload)
  610. return await post_streaming_url(f"{url}/api/chat", json.dumps(payload))
  611. # TODO: we should update this part once Ollama supports other types
  612. class OpenAIChatMessageContent(BaseModel):
  613. type: str
  614. model_config = ConfigDict(extra="allow")
  615. class OpenAIChatMessage(BaseModel):
  616. role: str
  617. content: Union[str, OpenAIChatMessageContent]
  618. model_config = ConfigDict(extra="allow")
  619. class OpenAIChatCompletionForm(BaseModel):
  620. model: str
  621. messages: List[OpenAIChatMessage]
  622. model_config = ConfigDict(extra="allow")
  623. @app.post("/v1/chat/completions")
  624. @app.post("/v1/chat/completions/{url_idx}")
  625. async def generate_openai_chat_completion(
  626. form_data: dict,
  627. url_idx: Optional[int] = None,
  628. user=Depends(get_verified_user),
  629. ):
  630. completion_form = OpenAIChatCompletionForm(**form_data)
  631. payload = {**completion_form.model_dump(exclude_none=True, exclude=["metadata"])}
  632. payload.pop("metadata")
  633. model_id = completion_form.model
  634. model_info = Models.get_model_by_id(model_id)
  635. if model_info:
  636. if model_info.base_model_id:
  637. payload["model"] = model_info.base_model_id
  638. params = model_info.params.model_dump()
  639. if params:
  640. payload = apply_model_params_to_body_openai(params, payload)
  641. payload = apply_model_system_prompt_to_body(params, payload, user)
  642. if ":" not in payload["model"]:
  643. payload["model"] = f"{payload['model']}:latest"
  644. url = get_ollama_url(url_idx, payload["model"])
  645. log.info(f"url: {url}")
  646. return await post_streaming_url(
  647. f"{url}/v1/chat/completions",
  648. json.dumps(payload),
  649. stream=payload.get("stream", False),
  650. )
  651. @app.get("/v1/models")
  652. @app.get("/v1/models/{url_idx}")
  653. async def get_openai_models(
  654. url_idx: Optional[int] = None,
  655. user=Depends(get_verified_user),
  656. ):
  657. if url_idx is None:
  658. models = await get_all_models()
  659. if app.state.config.ENABLE_MODEL_FILTER:
  660. if user.role == "user":
  661. models["models"] = list(
  662. filter(
  663. lambda model: model["name"]
  664. in app.state.config.MODEL_FILTER_LIST,
  665. models["models"],
  666. )
  667. )
  668. return {
  669. "data": [
  670. {
  671. "id": model["model"],
  672. "object": "model",
  673. "created": int(time.time()),
  674. "owned_by": "openai",
  675. }
  676. for model in models["models"]
  677. ],
  678. "object": "list",
  679. }
  680. else:
  681. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  682. try:
  683. r = requests.request(method="GET", url=f"{url}/api/tags")
  684. r.raise_for_status()
  685. models = r.json()
  686. return {
  687. "data": [
  688. {
  689. "id": model["model"],
  690. "object": "model",
  691. "created": int(time.time()),
  692. "owned_by": "openai",
  693. }
  694. for model in models["models"]
  695. ],
  696. "object": "list",
  697. }
  698. except Exception as e:
  699. log.exception(e)
  700. error_detail = "Open WebUI: Server Connection Error"
  701. if r is not None:
  702. try:
  703. res = r.json()
  704. if "error" in res:
  705. error_detail = f"Ollama: {res['error']}"
  706. except Exception:
  707. error_detail = f"Ollama: {e}"
  708. raise HTTPException(
  709. status_code=r.status_code if r else 500,
  710. detail=error_detail,
  711. )
  712. class UrlForm(BaseModel):
  713. url: str
  714. class UploadBlobForm(BaseModel):
  715. filename: str
  716. def parse_huggingface_url(hf_url):
  717. try:
  718. # Parse the URL
  719. parsed_url = urlparse(hf_url)
  720. # Get the path and split it into components
  721. path_components = parsed_url.path.split("/")
  722. # Extract the desired output
  723. model_file = path_components[-1]
  724. return model_file
  725. except ValueError:
  726. return None
  727. async def download_file_stream(
  728. ollama_url, file_url, file_path, file_name, chunk_size=1024 * 1024
  729. ):
  730. done = False
  731. if os.path.exists(file_path):
  732. current_size = os.path.getsize(file_path)
  733. else:
  734. current_size = 0
  735. headers = {"Range": f"bytes={current_size}-"} if current_size > 0 else {}
  736. timeout = aiohttp.ClientTimeout(total=600) # Set the timeout
  737. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  738. async with session.get(file_url, headers=headers) as response:
  739. total_size = int(response.headers.get("content-length", 0)) + current_size
  740. with open(file_path, "ab+") as file:
  741. async for data in response.content.iter_chunked(chunk_size):
  742. current_size += len(data)
  743. file.write(data)
  744. done = current_size == total_size
  745. progress = round((current_size / total_size) * 100, 2)
  746. yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n'
  747. if done:
  748. file.seek(0)
  749. hashed = calculate_sha256(file)
  750. file.seek(0)
  751. url = f"{ollama_url}/api/blobs/sha256:{hashed}"
  752. response = requests.post(url, data=file)
  753. if response.ok:
  754. res = {
  755. "done": done,
  756. "blob": f"sha256:{hashed}",
  757. "name": file_name,
  758. }
  759. os.remove(file_path)
  760. yield f"data: {json.dumps(res)}\n\n"
  761. else:
  762. raise "Ollama: Could not create blob, Please try again."
  763. # url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf"
  764. @app.post("/models/download")
  765. @app.post("/models/download/{url_idx}")
  766. async def download_model(
  767. form_data: UrlForm,
  768. url_idx: Optional[int] = None,
  769. user=Depends(get_admin_user),
  770. ):
  771. allowed_hosts = ["https://huggingface.co/", "https://github.com/"]
  772. if not any(form_data.url.startswith(host) for host in allowed_hosts):
  773. raise HTTPException(
  774. status_code=400,
  775. detail="Invalid file_url. Only URLs from allowed hosts are permitted.",
  776. )
  777. if url_idx is None:
  778. url_idx = 0
  779. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  780. file_name = parse_huggingface_url(form_data.url)
  781. if file_name:
  782. file_path = f"{UPLOAD_DIR}/{file_name}"
  783. return StreamingResponse(
  784. download_file_stream(url, form_data.url, file_path, file_name),
  785. )
  786. else:
  787. return None
  788. @app.post("/models/upload")
  789. @app.post("/models/upload/{url_idx}")
  790. def upload_model(
  791. file: UploadFile = File(...),
  792. url_idx: Optional[int] = None,
  793. user=Depends(get_admin_user),
  794. ):
  795. if url_idx is None:
  796. url_idx = 0
  797. ollama_url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  798. file_path = f"{UPLOAD_DIR}/{file.filename}"
  799. # Save file in chunks
  800. with open(file_path, "wb+") as f:
  801. for chunk in file.file:
  802. f.write(chunk)
  803. def file_process_stream():
  804. nonlocal ollama_url
  805. total_size = os.path.getsize(file_path)
  806. chunk_size = 1024 * 1024
  807. try:
  808. with open(file_path, "rb") as f:
  809. total = 0
  810. done = False
  811. while not done:
  812. chunk = f.read(chunk_size)
  813. if not chunk:
  814. done = True
  815. continue
  816. total += len(chunk)
  817. progress = round((total / total_size) * 100, 2)
  818. res = {
  819. "progress": progress,
  820. "total": total_size,
  821. "completed": total,
  822. }
  823. yield f"data: {json.dumps(res)}\n\n"
  824. if done:
  825. f.seek(0)
  826. hashed = calculate_sha256(f)
  827. f.seek(0)
  828. url = f"{ollama_url}/api/blobs/sha256:{hashed}"
  829. response = requests.post(url, data=f)
  830. if response.ok:
  831. res = {
  832. "done": done,
  833. "blob": f"sha256:{hashed}",
  834. "name": file.filename,
  835. }
  836. os.remove(file_path)
  837. yield f"data: {json.dumps(res)}\n\n"
  838. else:
  839. raise Exception(
  840. "Ollama: Could not create blob, Please try again."
  841. )
  842. except Exception as e:
  843. res = {"error": str(e)}
  844. yield f"data: {json.dumps(res)}\n\n"
  845. return StreamingResponse(file_process_stream(), media_type="text/event-stream")