main.py 40 KB

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