main.py 36 KB

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