main.py 35 KB

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