main.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434
  1. from fastapi import (
  2. FastAPI,
  3. Request,
  4. Response,
  5. HTTPException,
  6. Depends,
  7. status,
  8. UploadFile,
  9. File,
  10. BackgroundTasks,
  11. )
  12. from fastapi.middleware.cors import CORSMiddleware
  13. from fastapi.responses import StreamingResponse
  14. from fastapi.concurrency import run_in_threadpool
  15. from pydantic import BaseModel, ConfigDict
  16. import os
  17. import re
  18. import copy
  19. import random
  20. import requests
  21. import json
  22. import uuid
  23. import aiohttp
  24. import asyncio
  25. import logging
  26. import time
  27. from urllib.parse import urlparse
  28. from typing import Optional, List, Union
  29. from apps.web.models.models import Models
  30. from apps.web.models.users import Users
  31. from constants import ERROR_MESSAGES
  32. from utils.utils import (
  33. decode_token,
  34. get_current_user,
  35. get_verified_user,
  36. get_admin_user,
  37. )
  38. from config import (
  39. SRC_LOG_LEVELS,
  40. OLLAMA_BASE_URLS,
  41. ENABLE_MODEL_FILTER,
  42. MODEL_FILTER_LIST,
  43. UPLOAD_DIR,
  44. AppConfig,
  45. )
  46. from utils.misc import calculate_sha256
  47. log = logging.getLogger(__name__)
  48. log.setLevel(SRC_LOG_LEVELS["OLLAMA"])
  49. app = FastAPI()
  50. app.add_middleware(
  51. CORSMiddleware,
  52. allow_origins=["*"],
  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.MODEL_CONFIG = [
  61. model.to_form() for model in Models.get_all_models_by_source("ollama")
  62. ]
  63. app.state.config.OLLAMA_BASE_URLS = OLLAMA_BASE_URLS
  64. app.state.MODELS = {}
  65. REQUEST_POOL = []
  66. # TODO: Implement a more intelligent load balancing mechanism for distributing requests among multiple backend instances.
  67. # Current implementation uses a simple round-robin approach (random.choice). Consider incorporating algorithms like weighted round-robin,
  68. # least connections, or least response time for better resource utilization and performance optimization.
  69. @app.middleware("http")
  70. async def check_url(request: Request, call_next):
  71. if len(app.state.MODELS) == 0:
  72. await get_all_models()
  73. else:
  74. pass
  75. response = await call_next(request)
  76. return response
  77. @app.head("/")
  78. @app.get("/")
  79. async def get_status():
  80. return {"status": True}
  81. @app.get("/urls")
  82. async def get_ollama_api_urls(user=Depends(get_admin_user)):
  83. return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
  84. class UrlUpdateForm(BaseModel):
  85. urls: List[str]
  86. @app.post("/urls/update")
  87. async def update_ollama_api_url(form_data: UrlUpdateForm, user=Depends(get_admin_user)):
  88. app.state.config.OLLAMA_BASE_URLS = form_data.urls
  89. log.info(f"app.state.config.OLLAMA_BASE_URLS: {app.state.config.OLLAMA_BASE_URLS}")
  90. return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
  91. @app.get("/cancel/{request_id}")
  92. async def cancel_ollama_request(request_id: str, user=Depends(get_current_user)):
  93. if user:
  94. if request_id in REQUEST_POOL:
  95. REQUEST_POOL.remove(request_id)
  96. return True
  97. else:
  98. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
  99. async def fetch_url(url):
  100. timeout = aiohttp.ClientTimeout(total=5)
  101. try:
  102. async with aiohttp.ClientSession(timeout=timeout) as session:
  103. async with session.get(url) as response:
  104. return await response.json()
  105. except Exception as e:
  106. # Handle connection error here
  107. log.error(f"Connection error: {e}")
  108. return None
  109. def merge_models_lists(model_lists):
  110. merged_models = {}
  111. for idx, model_list in enumerate(model_lists):
  112. if model_list is not None:
  113. for model in model_list:
  114. digest = model["digest"]
  115. if digest not in merged_models:
  116. model["urls"] = [idx]
  117. merged_models[digest] = model
  118. else:
  119. merged_models[digest]["urls"].append(idx)
  120. return list(merged_models.values())
  121. # user=Depends(get_current_user)
  122. async def get_all_models():
  123. log.info("get_all_models()")
  124. tasks = [fetch_url(f"{url}/api/tags") for url in app.state.config.OLLAMA_BASE_URLS]
  125. responses = await asyncio.gather(*tasks)
  126. models = {
  127. "models": merge_models_lists(
  128. map(
  129. lambda response: (response["models"] if response else None),
  130. responses,
  131. )
  132. )
  133. }
  134. for model in models["models"]:
  135. add_custom_info_to_model(model)
  136. app.state.MODELS = {model["model"]: model for model in models["models"]}
  137. return models
  138. def add_custom_info_to_model(model: dict):
  139. model["custom_info"] = next(
  140. (item for item in app.state.MODEL_CONFIG if item.id == model["model"]), None
  141. )
  142. @app.get("/api/tags")
  143. @app.get("/api/tags/{url_idx}")
  144. async def get_ollama_tags(
  145. url_idx: Optional[int] = None, user=Depends(get_verified_user)
  146. ):
  147. if url_idx == None:
  148. models = await get_all_models()
  149. if app.state.config.ENABLE_MODEL_FILTER:
  150. if user.role == "user":
  151. models["models"] = list(
  152. filter(
  153. lambda model: model["name"]
  154. in app.state.config.MODEL_FILTER_LIST,
  155. models["models"],
  156. )
  157. )
  158. return models
  159. return models
  160. else:
  161. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  162. try:
  163. r = requests.request(method="GET", url=f"{url}/api/tags")
  164. r.raise_for_status()
  165. return r.json()
  166. except Exception as e:
  167. log.exception(e)
  168. error_detail = "Open WebUI: Server Connection Error"
  169. if r is not None:
  170. try:
  171. res = r.json()
  172. if "error" in res:
  173. error_detail = f"Ollama: {res['error']}"
  174. except:
  175. error_detail = f"Ollama: {e}"
  176. raise HTTPException(
  177. status_code=r.status_code if r else 500,
  178. detail=error_detail,
  179. )
  180. @app.get("/api/version")
  181. @app.get("/api/version/{url_idx}")
  182. async def get_ollama_versions(url_idx: Optional[int] = None):
  183. if url_idx == None:
  184. # returns lowest version
  185. tasks = [
  186. fetch_url(f"{url}/api/version") for url in app.state.config.OLLAMA_BASE_URLS
  187. ]
  188. responses = await asyncio.gather(*tasks)
  189. responses = list(filter(lambda x: x is not None, responses))
  190. if len(responses) > 0:
  191. lowest_version = min(
  192. responses,
  193. key=lambda x: tuple(
  194. map(int, re.sub(r"^v|-.*", "", x["version"]).split("."))
  195. ),
  196. )
  197. return {"version": lowest_version["version"]}
  198. else:
  199. raise HTTPException(
  200. status_code=500,
  201. detail=ERROR_MESSAGES.OLLAMA_NOT_FOUND,
  202. )
  203. else:
  204. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  205. try:
  206. r = requests.request(method="GET", url=f"{url}/api/version")
  207. r.raise_for_status()
  208. return r.json()
  209. except Exception as e:
  210. log.exception(e)
  211. error_detail = "Open WebUI: Server Connection Error"
  212. if r is not None:
  213. try:
  214. res = r.json()
  215. if "error" in res:
  216. error_detail = f"Ollama: {res['error']}"
  217. except:
  218. error_detail = f"Ollama: {e}"
  219. raise HTTPException(
  220. status_code=r.status_code if r else 500,
  221. detail=error_detail,
  222. )
  223. class ModelNameForm(BaseModel):
  224. name: str
  225. @app.post("/api/pull")
  226. @app.post("/api/pull/{url_idx}")
  227. async def pull_model(
  228. form_data: ModelNameForm, url_idx: int = 0, user=Depends(get_admin_user)
  229. ):
  230. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  231. log.info(f"url: {url}")
  232. r = None
  233. def get_request():
  234. nonlocal url
  235. nonlocal r
  236. request_id = str(uuid.uuid4())
  237. try:
  238. REQUEST_POOL.append(request_id)
  239. def stream_content():
  240. try:
  241. yield json.dumps({"id": request_id, "done": False}) + "\n"
  242. for chunk in r.iter_content(chunk_size=8192):
  243. if request_id in REQUEST_POOL:
  244. yield chunk
  245. else:
  246. log.warning("User: canceled request")
  247. break
  248. finally:
  249. if hasattr(r, "close"):
  250. r.close()
  251. if request_id in REQUEST_POOL:
  252. REQUEST_POOL.remove(request_id)
  253. r = requests.request(
  254. method="POST",
  255. url=f"{url}/api/pull",
  256. data=form_data.model_dump_json(exclude_none=True).encode(),
  257. stream=True,
  258. )
  259. r.raise_for_status()
  260. return StreamingResponse(
  261. stream_content(),
  262. status_code=r.status_code,
  263. headers=dict(r.headers),
  264. )
  265. except Exception as e:
  266. raise e
  267. try:
  268. return await run_in_threadpool(get_request)
  269. except Exception as e:
  270. log.exception(e)
  271. error_detail = "Open WebUI: Server Connection Error"
  272. if r is not None:
  273. try:
  274. res = r.json()
  275. if "error" in res:
  276. error_detail = f"Ollama: {res['error']}"
  277. except:
  278. error_detail = f"Ollama: {e}"
  279. raise HTTPException(
  280. status_code=r.status_code if r else 500,
  281. detail=error_detail,
  282. )
  283. class PushModelForm(BaseModel):
  284. name: str
  285. insecure: Optional[bool] = None
  286. stream: Optional[bool] = None
  287. @app.delete("/api/push")
  288. @app.delete("/api/push/{url_idx}")
  289. async def push_model(
  290. form_data: PushModelForm,
  291. url_idx: Optional[int] = None,
  292. user=Depends(get_admin_user),
  293. ):
  294. if url_idx == None:
  295. if form_data.name in app.state.MODELS:
  296. url_idx = app.state.MODELS[form_data.name]["urls"][0]
  297. else:
  298. raise HTTPException(
  299. status_code=400,
  300. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  301. )
  302. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  303. log.debug(f"url: {url}")
  304. r = None
  305. def get_request():
  306. nonlocal url
  307. nonlocal r
  308. try:
  309. def stream_content():
  310. for chunk in r.iter_content(chunk_size=8192):
  311. yield chunk
  312. r = requests.request(
  313. method="POST",
  314. url=f"{url}/api/push",
  315. data=form_data.model_dump_json(exclude_none=True).encode(),
  316. )
  317. r.raise_for_status()
  318. return StreamingResponse(
  319. stream_content(),
  320. status_code=r.status_code,
  321. headers=dict(r.headers),
  322. )
  323. except Exception as e:
  324. raise e
  325. try:
  326. return await run_in_threadpool(get_request)
  327. except Exception as e:
  328. log.exception(e)
  329. error_detail = "Open WebUI: Server Connection Error"
  330. if r is not None:
  331. try:
  332. res = r.json()
  333. if "error" in res:
  334. error_detail = f"Ollama: {res['error']}"
  335. except:
  336. error_detail = f"Ollama: {e}"
  337. raise HTTPException(
  338. status_code=r.status_code if r else 500,
  339. detail=error_detail,
  340. )
  341. class CreateModelForm(BaseModel):
  342. name: str
  343. modelfile: Optional[str] = None
  344. stream: Optional[bool] = None
  345. path: Optional[str] = None
  346. @app.post("/api/create")
  347. @app.post("/api/create/{url_idx}")
  348. async def create_model(
  349. form_data: CreateModelForm, url_idx: int = 0, user=Depends(get_admin_user)
  350. ):
  351. log.debug(f"form_data: {form_data}")
  352. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  353. log.info(f"url: {url}")
  354. r = None
  355. def get_request():
  356. nonlocal url
  357. nonlocal r
  358. try:
  359. def stream_content():
  360. for chunk in r.iter_content(chunk_size=8192):
  361. yield chunk
  362. r = requests.request(
  363. method="POST",
  364. url=f"{url}/api/create",
  365. data=form_data.model_dump_json(exclude_none=True).encode(),
  366. stream=True,
  367. )
  368. r.raise_for_status()
  369. log.debug(f"r: {r}")
  370. return StreamingResponse(
  371. stream_content(),
  372. status_code=r.status_code,
  373. headers=dict(r.headers),
  374. )
  375. except Exception as e:
  376. raise e
  377. try:
  378. return await run_in_threadpool(get_request)
  379. except Exception as e:
  380. log.exception(e)
  381. error_detail = "Open WebUI: Server Connection Error"
  382. if r is not None:
  383. try:
  384. res = r.json()
  385. if "error" in res:
  386. error_detail = f"Ollama: {res['error']}"
  387. except:
  388. error_detail = f"Ollama: {e}"
  389. raise HTTPException(
  390. status_code=r.status_code if r else 500,
  391. detail=error_detail,
  392. )
  393. class CopyModelForm(BaseModel):
  394. source: str
  395. destination: str
  396. @app.post("/api/copy")
  397. @app.post("/api/copy/{url_idx}")
  398. async def copy_model(
  399. form_data: CopyModelForm,
  400. url_idx: Optional[int] = None,
  401. user=Depends(get_admin_user),
  402. ):
  403. if url_idx == None:
  404. if form_data.source in app.state.MODELS:
  405. url_idx = app.state.MODELS[form_data.source]["urls"][0]
  406. else:
  407. raise HTTPException(
  408. status_code=400,
  409. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.source),
  410. )
  411. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  412. log.info(f"url: {url}")
  413. try:
  414. r = requests.request(
  415. method="POST",
  416. url=f"{url}/api/copy",
  417. data=form_data.model_dump_json(exclude_none=True).encode(),
  418. )
  419. r.raise_for_status()
  420. log.debug(f"r.text: {r.text}")
  421. return True
  422. except Exception as e:
  423. log.exception(e)
  424. error_detail = "Open WebUI: Server Connection Error"
  425. if r is not None:
  426. try:
  427. res = r.json()
  428. if "error" in res:
  429. error_detail = f"Ollama: {res['error']}"
  430. except:
  431. error_detail = f"Ollama: {e}"
  432. raise HTTPException(
  433. status_code=r.status_code if r else 500,
  434. detail=error_detail,
  435. )
  436. @app.delete("/api/delete")
  437. @app.delete("/api/delete/{url_idx}")
  438. async def delete_model(
  439. form_data: ModelNameForm,
  440. url_idx: Optional[int] = None,
  441. user=Depends(get_admin_user),
  442. ):
  443. if url_idx == None:
  444. if form_data.name in app.state.MODELS:
  445. url_idx = app.state.MODELS[form_data.name]["urls"][0]
  446. else:
  447. raise HTTPException(
  448. status_code=400,
  449. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  450. )
  451. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  452. log.info(f"url: {url}")
  453. try:
  454. r = requests.request(
  455. method="DELETE",
  456. url=f"{url}/api/delete",
  457. data=form_data.model_dump_json(exclude_none=True).encode(),
  458. )
  459. r.raise_for_status()
  460. log.debug(f"r.text: {r.text}")
  461. return True
  462. except Exception as e:
  463. log.exception(e)
  464. error_detail = "Open WebUI: Server Connection Error"
  465. if r is not None:
  466. try:
  467. res = r.json()
  468. if "error" in res:
  469. error_detail = f"Ollama: {res['error']}"
  470. except:
  471. error_detail = f"Ollama: {e}"
  472. raise HTTPException(
  473. status_code=r.status_code if r else 500,
  474. detail=error_detail,
  475. )
  476. @app.post("/api/show")
  477. async def show_model_info(form_data: ModelNameForm, user=Depends(get_verified_user)):
  478. if form_data.name not in app.state.MODELS:
  479. raise HTTPException(
  480. status_code=400,
  481. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  482. )
  483. url_idx = random.choice(app.state.MODELS[form_data.name]["urls"])
  484. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  485. log.info(f"url: {url}")
  486. try:
  487. r = requests.request(
  488. method="POST",
  489. url=f"{url}/api/show",
  490. data=form_data.model_dump_json(exclude_none=True).encode(),
  491. )
  492. r.raise_for_status()
  493. return r.json()
  494. except Exception as e:
  495. log.exception(e)
  496. error_detail = "Open WebUI: Server Connection Error"
  497. if r is not None:
  498. try:
  499. res = r.json()
  500. if "error" in res:
  501. error_detail = f"Ollama: {res['error']}"
  502. except:
  503. error_detail = f"Ollama: {e}"
  504. raise HTTPException(
  505. status_code=r.status_code if r else 500,
  506. detail=error_detail,
  507. )
  508. class GenerateEmbeddingsForm(BaseModel):
  509. model: str
  510. prompt: str
  511. options: Optional[dict] = None
  512. keep_alive: Optional[Union[int, str]] = None
  513. @app.post("/api/embeddings")
  514. @app.post("/api/embeddings/{url_idx}")
  515. async def generate_embeddings(
  516. form_data: GenerateEmbeddingsForm,
  517. url_idx: Optional[int] = None,
  518. user=Depends(get_verified_user),
  519. ):
  520. if url_idx == None:
  521. model = form_data.model
  522. if ":" not in model:
  523. model = f"{model}:latest"
  524. if model in app.state.MODELS:
  525. url_idx = random.choice(app.state.MODELS[model]["urls"])
  526. else:
  527. raise HTTPException(
  528. status_code=400,
  529. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  530. )
  531. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  532. log.info(f"url: {url}")
  533. try:
  534. r = requests.request(
  535. method="POST",
  536. url=f"{url}/api/embeddings",
  537. data=form_data.model_dump_json(exclude_none=True).encode(),
  538. )
  539. r.raise_for_status()
  540. return r.json()
  541. except Exception as e:
  542. log.exception(e)
  543. error_detail = "Open WebUI: Server Connection Error"
  544. if r is not None:
  545. try:
  546. res = r.json()
  547. if "error" in res:
  548. error_detail = f"Ollama: {res['error']}"
  549. except:
  550. error_detail = f"Ollama: {e}"
  551. raise HTTPException(
  552. status_code=r.status_code if r else 500,
  553. detail=error_detail,
  554. )
  555. def generate_ollama_embeddings(
  556. form_data: GenerateEmbeddingsForm,
  557. url_idx: Optional[int] = None,
  558. ):
  559. log.info(f"generate_ollama_embeddings {form_data}")
  560. if url_idx == None:
  561. model = form_data.model
  562. if ":" not in model:
  563. model = f"{model}:latest"
  564. if model in app.state.MODELS:
  565. url_idx = random.choice(app.state.MODELS[model]["urls"])
  566. else:
  567. raise HTTPException(
  568. status_code=400,
  569. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  570. )
  571. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  572. log.info(f"url: {url}")
  573. try:
  574. r = requests.request(
  575. method="POST",
  576. url=f"{url}/api/embeddings",
  577. data=form_data.model_dump_json(exclude_none=True).encode(),
  578. )
  579. r.raise_for_status()
  580. data = r.json()
  581. log.info(f"generate_ollama_embeddings {data}")
  582. if "embedding" in data:
  583. return data["embedding"]
  584. else:
  585. raise "Something went wrong :/"
  586. except Exception as e:
  587. log.exception(e)
  588. error_detail = "Open WebUI: Server Connection Error"
  589. if r is not None:
  590. try:
  591. res = r.json()
  592. if "error" in res:
  593. error_detail = f"Ollama: {res['error']}"
  594. except:
  595. error_detail = f"Ollama: {e}"
  596. raise error_detail
  597. class GenerateCompletionForm(BaseModel):
  598. model: str
  599. prompt: str
  600. images: Optional[List[str]] = None
  601. format: Optional[str] = None
  602. options: Optional[dict] = None
  603. system: Optional[str] = None
  604. template: Optional[str] = None
  605. context: Optional[str] = None
  606. stream: Optional[bool] = True
  607. raw: Optional[bool] = None
  608. keep_alive: Optional[Union[int, str]] = None
  609. @app.post("/api/generate")
  610. @app.post("/api/generate/{url_idx}")
  611. async def generate_completion(
  612. form_data: GenerateCompletionForm,
  613. url_idx: Optional[int] = None,
  614. user=Depends(get_verified_user),
  615. ):
  616. if url_idx == None:
  617. model = form_data.model
  618. if ":" not in model:
  619. model = f"{model}:latest"
  620. if model in app.state.MODELS:
  621. url_idx = random.choice(app.state.MODELS[model]["urls"])
  622. else:
  623. raise HTTPException(
  624. status_code=400,
  625. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  626. )
  627. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  628. log.info(f"url: {url}")
  629. r = None
  630. def get_request():
  631. nonlocal form_data
  632. nonlocal r
  633. request_id = str(uuid.uuid4())
  634. try:
  635. REQUEST_POOL.append(request_id)
  636. def stream_content():
  637. try:
  638. if form_data.stream:
  639. yield json.dumps({"id": request_id, "done": False}) + "\n"
  640. for chunk in r.iter_content(chunk_size=8192):
  641. if request_id in REQUEST_POOL:
  642. yield chunk
  643. else:
  644. log.warning("User: canceled request")
  645. break
  646. finally:
  647. if hasattr(r, "close"):
  648. r.close()
  649. if request_id in REQUEST_POOL:
  650. REQUEST_POOL.remove(request_id)
  651. r = requests.request(
  652. method="POST",
  653. url=f"{url}/api/generate",
  654. data=form_data.model_dump_json(exclude_none=True).encode(),
  655. stream=True,
  656. )
  657. r.raise_for_status()
  658. return StreamingResponse(
  659. stream_content(),
  660. status_code=r.status_code,
  661. headers=dict(r.headers),
  662. )
  663. except Exception as e:
  664. raise e
  665. try:
  666. return await run_in_threadpool(get_request)
  667. except Exception as e:
  668. error_detail = "Open WebUI: Server Connection Error"
  669. if r is not None:
  670. try:
  671. res = r.json()
  672. if "error" in res:
  673. error_detail = f"Ollama: {res['error']}"
  674. except:
  675. error_detail = f"Ollama: {e}"
  676. raise HTTPException(
  677. status_code=r.status_code if r else 500,
  678. detail=error_detail,
  679. )
  680. class ChatMessage(BaseModel):
  681. role: str
  682. content: str
  683. images: Optional[List[str]] = None
  684. class GenerateChatCompletionForm(BaseModel):
  685. model: str
  686. messages: List[ChatMessage]
  687. format: Optional[str] = None
  688. options: Optional[dict] = None
  689. template: Optional[str] = None
  690. stream: Optional[bool] = None
  691. keep_alive: Optional[Union[int, str]] = None
  692. @app.post("/api/chat")
  693. @app.post("/api/chat/{url_idx}")
  694. async def generate_chat_completion(
  695. form_data: GenerateChatCompletionForm,
  696. url_idx: Optional[int] = None,
  697. user=Depends(get_verified_user),
  698. ):
  699. if url_idx == None:
  700. model = form_data.model
  701. if ":" not in model:
  702. model = f"{model}:latest"
  703. if model in app.state.MODELS:
  704. url_idx = random.choice(app.state.MODELS[model]["urls"])
  705. else:
  706. raise HTTPException(
  707. status_code=400,
  708. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  709. )
  710. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  711. log.info(f"url: {url}")
  712. r = None
  713. log.debug(
  714. "form_data.model_dump_json(exclude_none=True).encode(): {0} ".format(
  715. form_data.model_dump_json(exclude_none=True).encode()
  716. )
  717. )
  718. def get_request():
  719. nonlocal form_data
  720. nonlocal r
  721. request_id = str(uuid.uuid4())
  722. try:
  723. REQUEST_POOL.append(request_id)
  724. def stream_content():
  725. try:
  726. if form_data.stream:
  727. yield json.dumps({"id": request_id, "done": False}) + "\n"
  728. for chunk in r.iter_content(chunk_size=8192):
  729. if request_id in REQUEST_POOL:
  730. yield chunk
  731. else:
  732. log.warning("User: canceled request")
  733. break
  734. finally:
  735. if hasattr(r, "close"):
  736. r.close()
  737. if request_id in REQUEST_POOL:
  738. REQUEST_POOL.remove(request_id)
  739. r = requests.request(
  740. method="POST",
  741. url=f"{url}/api/chat",
  742. data=form_data.model_dump_json(exclude_none=True).encode(),
  743. stream=True,
  744. )
  745. r.raise_for_status()
  746. return StreamingResponse(
  747. stream_content(),
  748. status_code=r.status_code,
  749. headers=dict(r.headers),
  750. )
  751. except Exception as e:
  752. log.exception(e)
  753. raise e
  754. try:
  755. return await run_in_threadpool(get_request)
  756. except Exception as e:
  757. error_detail = "Open WebUI: Server Connection Error"
  758. if r is not None:
  759. try:
  760. res = r.json()
  761. if "error" in res:
  762. error_detail = f"Ollama: {res['error']}"
  763. except:
  764. error_detail = f"Ollama: {e}"
  765. raise HTTPException(
  766. status_code=r.status_code if r else 500,
  767. detail=error_detail,
  768. )
  769. # TODO: we should update this part once Ollama supports other types
  770. class OpenAIChatMessage(BaseModel):
  771. role: str
  772. content: str
  773. model_config = ConfigDict(extra="allow")
  774. class OpenAIChatCompletionForm(BaseModel):
  775. model: str
  776. messages: List[OpenAIChatMessage]
  777. model_config = ConfigDict(extra="allow")
  778. @app.post("/v1/chat/completions")
  779. @app.post("/v1/chat/completions/{url_idx}")
  780. async def generate_openai_chat_completion(
  781. form_data: OpenAIChatCompletionForm,
  782. url_idx: Optional[int] = None,
  783. user=Depends(get_verified_user),
  784. ):
  785. if url_idx == None:
  786. model = form_data.model
  787. if ":" not in model:
  788. model = f"{model}:latest"
  789. if model in app.state.MODELS:
  790. url_idx = random.choice(app.state.MODELS[model]["urls"])
  791. else:
  792. raise HTTPException(
  793. status_code=400,
  794. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  795. )
  796. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  797. log.info(f"url: {url}")
  798. r = None
  799. def get_request():
  800. nonlocal form_data
  801. nonlocal r
  802. request_id = str(uuid.uuid4())
  803. try:
  804. REQUEST_POOL.append(request_id)
  805. def stream_content():
  806. try:
  807. if form_data.stream:
  808. yield json.dumps(
  809. {"request_id": request_id, "done": False}
  810. ) + "\n"
  811. for chunk in r.iter_content(chunk_size=8192):
  812. if request_id in REQUEST_POOL:
  813. yield chunk
  814. else:
  815. log.warning("User: canceled request")
  816. break
  817. finally:
  818. if hasattr(r, "close"):
  819. r.close()
  820. if request_id in REQUEST_POOL:
  821. REQUEST_POOL.remove(request_id)
  822. r = requests.request(
  823. method="POST",
  824. url=f"{url}/v1/chat/completions",
  825. data=form_data.model_dump_json(exclude_none=True).encode(),
  826. stream=True,
  827. )
  828. r.raise_for_status()
  829. return StreamingResponse(
  830. stream_content(),
  831. status_code=r.status_code,
  832. headers=dict(r.headers),
  833. )
  834. except Exception as e:
  835. raise e
  836. try:
  837. return await run_in_threadpool(get_request)
  838. except Exception as e:
  839. error_detail = "Open WebUI: Server Connection Error"
  840. if r is not None:
  841. try:
  842. res = r.json()
  843. if "error" in res:
  844. error_detail = f"Ollama: {res['error']}"
  845. except:
  846. error_detail = f"Ollama: {e}"
  847. raise HTTPException(
  848. status_code=r.status_code if r else 500,
  849. detail=error_detail,
  850. )
  851. @app.get("/v1/models")
  852. @app.get("/v1/models/{url_idx}")
  853. async def get_openai_models(
  854. url_idx: Optional[int] = None,
  855. user=Depends(get_verified_user),
  856. ):
  857. if url_idx == None:
  858. models = await get_all_models()
  859. if app.state.config.ENABLE_MODEL_FILTER:
  860. if user.role == "user":
  861. models["models"] = list(
  862. filter(
  863. lambda model: model["name"]
  864. in app.state.config.MODEL_FILTER_LIST,
  865. models["models"],
  866. )
  867. )
  868. return {
  869. "data": [
  870. {
  871. "id": model["model"],
  872. "object": "model",
  873. "created": int(time.time()),
  874. "owned_by": "openai",
  875. }
  876. for model in models["models"]
  877. ],
  878. "object": "list",
  879. }
  880. else:
  881. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  882. try:
  883. r = requests.request(method="GET", url=f"{url}/api/tags")
  884. r.raise_for_status()
  885. models = r.json()
  886. return {
  887. "data": [
  888. {
  889. "id": model["model"],
  890. "object": "model",
  891. "created": int(time.time()),
  892. "owned_by": "openai",
  893. }
  894. for model in models["models"]
  895. ],
  896. "object": "list",
  897. }
  898. except Exception as e:
  899. log.exception(e)
  900. error_detail = "Open WebUI: Server Connection Error"
  901. if r is not None:
  902. try:
  903. res = r.json()
  904. if "error" in res:
  905. error_detail = f"Ollama: {res['error']}"
  906. except:
  907. error_detail = f"Ollama: {e}"
  908. raise HTTPException(
  909. status_code=r.status_code if r else 500,
  910. detail=error_detail,
  911. )
  912. class UrlForm(BaseModel):
  913. url: str
  914. class UploadBlobForm(BaseModel):
  915. filename: str
  916. def parse_huggingface_url(hf_url):
  917. try:
  918. # Parse the URL
  919. parsed_url = urlparse(hf_url)
  920. # Get the path and split it into components
  921. path_components = parsed_url.path.split("/")
  922. # Extract the desired output
  923. user_repo = "/".join(path_components[1:3])
  924. model_file = path_components[-1]
  925. return model_file
  926. except ValueError:
  927. return None
  928. async def download_file_stream(
  929. ollama_url, file_url, file_path, file_name, chunk_size=1024 * 1024
  930. ):
  931. done = False
  932. if os.path.exists(file_path):
  933. current_size = os.path.getsize(file_path)
  934. else:
  935. current_size = 0
  936. headers = {"Range": f"bytes={current_size}-"} if current_size > 0 else {}
  937. timeout = aiohttp.ClientTimeout(total=600) # Set the timeout
  938. async with aiohttp.ClientSession(timeout=timeout) as session:
  939. async with session.get(file_url, headers=headers) as response:
  940. total_size = int(response.headers.get("content-length", 0)) + current_size
  941. with open(file_path, "ab+") as file:
  942. async for data in response.content.iter_chunked(chunk_size):
  943. current_size += len(data)
  944. file.write(data)
  945. done = current_size == total_size
  946. progress = round((current_size / total_size) * 100, 2)
  947. yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n'
  948. if done:
  949. file.seek(0)
  950. hashed = calculate_sha256(file)
  951. file.seek(0)
  952. url = f"{ollama_url}/api/blobs/sha256:{hashed}"
  953. response = requests.post(url, data=file)
  954. if response.ok:
  955. res = {
  956. "done": done,
  957. "blob": f"sha256:{hashed}",
  958. "name": file_name,
  959. }
  960. os.remove(file_path)
  961. yield f"data: {json.dumps(res)}\n\n"
  962. else:
  963. raise "Ollama: Could not create blob, Please try again."
  964. # def number_generator():
  965. # for i in range(1, 101):
  966. # yield f"data: {i}\n"
  967. # url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf"
  968. @app.post("/models/download")
  969. @app.post("/models/download/{url_idx}")
  970. async def download_model(
  971. form_data: UrlForm,
  972. url_idx: Optional[int] = None,
  973. ):
  974. allowed_hosts = ["https://huggingface.co/", "https://github.com/"]
  975. if not any(form_data.url.startswith(host) for host in allowed_hosts):
  976. raise HTTPException(
  977. status_code=400,
  978. detail="Invalid file_url. Only URLs from allowed hosts are permitted.",
  979. )
  980. if url_idx == None:
  981. url_idx = 0
  982. url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  983. file_name = parse_huggingface_url(form_data.url)
  984. if file_name:
  985. file_path = f"{UPLOAD_DIR}/{file_name}"
  986. return StreamingResponse(
  987. download_file_stream(url, form_data.url, file_path, file_name),
  988. )
  989. else:
  990. return None
  991. @app.post("/models/upload")
  992. @app.post("/models/upload/{url_idx}")
  993. def upload_model(file: UploadFile = File(...), url_idx: Optional[int] = None):
  994. if url_idx == None:
  995. url_idx = 0
  996. ollama_url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  997. file_path = f"{UPLOAD_DIR}/{file.filename}"
  998. # Save file in chunks
  999. with open(file_path, "wb+") as f:
  1000. for chunk in file.file:
  1001. f.write(chunk)
  1002. def file_process_stream():
  1003. nonlocal ollama_url
  1004. total_size = os.path.getsize(file_path)
  1005. chunk_size = 1024 * 1024
  1006. try:
  1007. with open(file_path, "rb") as f:
  1008. total = 0
  1009. done = False
  1010. while not done:
  1011. chunk = f.read(chunk_size)
  1012. if not chunk:
  1013. done = True
  1014. continue
  1015. total += len(chunk)
  1016. progress = round((total / total_size) * 100, 2)
  1017. res = {
  1018. "progress": progress,
  1019. "total": total_size,
  1020. "completed": total,
  1021. }
  1022. yield f"data: {json.dumps(res)}\n\n"
  1023. if done:
  1024. f.seek(0)
  1025. hashed = calculate_sha256(f)
  1026. f.seek(0)
  1027. url = f"{ollama_url}/api/blobs/sha256:{hashed}"
  1028. response = requests.post(url, data=f)
  1029. if response.ok:
  1030. res = {
  1031. "done": done,
  1032. "blob": f"sha256:{hashed}",
  1033. "name": file.filename,
  1034. }
  1035. os.remove(file_path)
  1036. yield f"data: {json.dumps(res)}\n\n"
  1037. else:
  1038. raise Exception(
  1039. "Ollama: Could not create blob, Please try again."
  1040. )
  1041. except Exception as e:
  1042. res = {"error": str(e)}
  1043. yield f"data: {json.dumps(res)}\n\n"
  1044. return StreamingResponse(file_process_stream(), media_type="text/event-stream")
  1045. # async def upload_model(file: UploadFile = File(), url_idx: Optional[int] = None):
  1046. # if url_idx == None:
  1047. # url_idx = 0
  1048. # url = app.state.config.OLLAMA_BASE_URLS[url_idx]
  1049. # file_location = os.path.join(UPLOAD_DIR, file.filename)
  1050. # total_size = file.size
  1051. # async def file_upload_generator(file):
  1052. # print(file)
  1053. # try:
  1054. # async with aiofiles.open(file_location, "wb") as f:
  1055. # completed_size = 0
  1056. # while True:
  1057. # chunk = await file.read(1024*1024)
  1058. # if not chunk:
  1059. # break
  1060. # await f.write(chunk)
  1061. # completed_size += len(chunk)
  1062. # progress = (completed_size / total_size) * 100
  1063. # print(progress)
  1064. # yield f'data: {json.dumps({"status": "uploading", "percentage": progress, "total": total_size, "completed": completed_size, "done": False})}\n'
  1065. # except Exception as e:
  1066. # print(e)
  1067. # yield f"data: {json.dumps({'status': 'error', 'message': str(e)})}\n"
  1068. # finally:
  1069. # await file.close()
  1070. # print("done")
  1071. # yield f'data: {json.dumps({"status": "completed", "percentage": 100, "total": total_size, "completed": completed_size, "done": True})}\n'
  1072. # return StreamingResponse(
  1073. # file_upload_generator(copy.deepcopy(file)), media_type="text/event-stream"
  1074. # )
  1075. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  1076. async def deprecated_proxy(
  1077. path: str, request: Request, user=Depends(get_verified_user)
  1078. ):
  1079. url = app.state.config.OLLAMA_BASE_URLS[0]
  1080. target_url = f"{url}/{path}"
  1081. body = await request.body()
  1082. headers = dict(request.headers)
  1083. if user.role in ["user", "admin"]:
  1084. if path in ["pull", "delete", "push", "copy", "create"]:
  1085. if user.role != "admin":
  1086. raise HTTPException(
  1087. status_code=status.HTTP_401_UNAUTHORIZED,
  1088. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  1089. )
  1090. else:
  1091. raise HTTPException(
  1092. status_code=status.HTTP_401_UNAUTHORIZED,
  1093. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  1094. )
  1095. headers.pop("host", None)
  1096. headers.pop("authorization", None)
  1097. headers.pop("origin", None)
  1098. headers.pop("referer", None)
  1099. r = None
  1100. def get_request():
  1101. nonlocal r
  1102. request_id = str(uuid.uuid4())
  1103. try:
  1104. REQUEST_POOL.append(request_id)
  1105. def stream_content():
  1106. try:
  1107. if path == "generate":
  1108. data = json.loads(body.decode("utf-8"))
  1109. if not ("stream" in data and data["stream"] == False):
  1110. yield json.dumps({"id": request_id, "done": False}) + "\n"
  1111. elif path == "chat":
  1112. yield json.dumps({"id": request_id, "done": False}) + "\n"
  1113. for chunk in r.iter_content(chunk_size=8192):
  1114. if request_id in REQUEST_POOL:
  1115. yield chunk
  1116. else:
  1117. log.warning("User: canceled request")
  1118. break
  1119. finally:
  1120. if hasattr(r, "close"):
  1121. r.close()
  1122. if request_id in REQUEST_POOL:
  1123. REQUEST_POOL.remove(request_id)
  1124. r = requests.request(
  1125. method=request.method,
  1126. url=target_url,
  1127. data=body,
  1128. headers=headers,
  1129. stream=True,
  1130. )
  1131. r.raise_for_status()
  1132. # r.close()
  1133. return StreamingResponse(
  1134. stream_content(),
  1135. status_code=r.status_code,
  1136. headers=dict(r.headers),
  1137. )
  1138. except Exception as e:
  1139. raise e
  1140. try:
  1141. return await run_in_threadpool(get_request)
  1142. except Exception as e:
  1143. error_detail = "Open WebUI: Server Connection Error"
  1144. if r is not None:
  1145. try:
  1146. res = r.json()
  1147. if "error" in res:
  1148. error_detail = f"Ollama: {res['error']}"
  1149. except:
  1150. error_detail = f"Ollama: {e}"
  1151. raise HTTPException(
  1152. status_code=r.status_code if r else 500,
  1153. detail=error_detail,
  1154. )