main.py 40 KB

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