main.py 40 KB

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