main.py 40 KB

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