main.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. from fastapi import FastAPI, Request, Response, HTTPException, Depends, status
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from fastapi.responses import StreamingResponse
  4. from fastapi.concurrency import run_in_threadpool
  5. from pydantic import BaseModel, ConfigDict
  6. import random
  7. import requests
  8. import json
  9. import uuid
  10. import aiohttp
  11. import asyncio
  12. from apps.web.models.users import Users
  13. from constants import ERROR_MESSAGES
  14. from utils.utils import decode_token, get_current_user, get_admin_user
  15. from config import OLLAMA_BASE_URL, WEBUI_AUTH
  16. from typing import Optional, List, Union
  17. app = FastAPI()
  18. app.add_middleware(
  19. CORSMiddleware,
  20. allow_origins=["*"],
  21. allow_credentials=True,
  22. allow_methods=["*"],
  23. allow_headers=["*"],
  24. )
  25. app.state.OLLAMA_BASE_URL = OLLAMA_BASE_URL
  26. app.state.OLLAMA_BASE_URLS = [OLLAMA_BASE_URL]
  27. app.state.MODELS = {}
  28. REQUEST_POOL = []
  29. # TODO: Implement a more intelligent load balancing mechanism for distributing requests among multiple backend instances.
  30. # Current implementation uses a simple round-robin approach (random.choice). Consider incorporating algorithms like weighted round-robin,
  31. # least connections, or least response time for better resource utilization and performance optimization.
  32. @app.middleware("http")
  33. async def check_url(request: Request, call_next):
  34. if len(app.state.MODELS) == 0:
  35. await get_all_models()
  36. else:
  37. pass
  38. response = await call_next(request)
  39. return response
  40. @app.get("/urls")
  41. async def get_ollama_api_urls(user=Depends(get_admin_user)):
  42. return {"OLLAMA_BASE_URLS": app.state.OLLAMA_BASE_URLS}
  43. class UrlUpdateForm(BaseModel):
  44. urls: List[str]
  45. @app.post("/urls/update")
  46. async def update_ollama_api_url(form_data: UrlUpdateForm, user=Depends(get_admin_user)):
  47. app.state.OLLAMA_BASE_URLS = form_data.urls
  48. print(app.state.OLLAMA_BASE_URLS)
  49. return {"OLLAMA_BASE_URLS": app.state.OLLAMA_BASE_URLS}
  50. @app.get("/cancel/{request_id}")
  51. async def cancel_ollama_request(request_id: str, user=Depends(get_current_user)):
  52. if user:
  53. if request_id in REQUEST_POOL:
  54. REQUEST_POOL.remove(request_id)
  55. return True
  56. else:
  57. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
  58. async def fetch_url(url):
  59. try:
  60. async with aiohttp.ClientSession() as session:
  61. async with session.get(url) as response:
  62. return await response.json()
  63. except Exception as e:
  64. # Handle connection error here
  65. print(f"Connection error: {e}")
  66. return None
  67. def merge_models_lists(model_lists):
  68. merged_models = {}
  69. for idx, model_list in enumerate(model_lists):
  70. for model in model_list:
  71. digest = model["digest"]
  72. if digest not in merged_models:
  73. model["urls"] = [idx]
  74. merged_models[digest] = model
  75. else:
  76. merged_models[digest]["urls"].append(idx)
  77. return list(merged_models.values())
  78. # user=Depends(get_current_user)
  79. async def get_all_models():
  80. print("get_all_models")
  81. tasks = [fetch_url(f"{url}/api/tags") for url in app.state.OLLAMA_BASE_URLS]
  82. responses = await asyncio.gather(*tasks)
  83. responses = list(filter(lambda x: x is not None, responses))
  84. models = {
  85. "models": merge_models_lists(
  86. map(lambda response: response["models"], responses)
  87. )
  88. }
  89. app.state.MODELS = {model["model"]: model for model in models["models"]}
  90. return models
  91. @app.get("/api/tags")
  92. @app.get("/api/tags/{url_idx}")
  93. async def get_ollama_tags(
  94. url_idx: Optional[int] = None, user=Depends(get_current_user)
  95. ):
  96. if url_idx == None:
  97. return await get_all_models()
  98. else:
  99. url = app.state.OLLAMA_BASE_URLS[url_idx]
  100. try:
  101. r = requests.request(method="GET", url=f"{url}/api/tags")
  102. r.raise_for_status()
  103. return r.json()
  104. except Exception as e:
  105. print(e)
  106. error_detail = "Open WebUI: Server Connection Error"
  107. if r is not None:
  108. try:
  109. res = r.json()
  110. if "error" in res:
  111. error_detail = f"Ollama: {res['error']}"
  112. except:
  113. error_detail = f"Ollama: {e}"
  114. raise HTTPException(
  115. status_code=r.status_code if r else 500,
  116. detail=error_detail,
  117. )
  118. @app.get("/api/version")
  119. @app.get("/api/version/{url_idx}")
  120. async def get_ollama_versions(url_idx: Optional[int] = None):
  121. if url_idx == None:
  122. # returns lowest version
  123. tasks = [fetch_url(f"{url}/api/version") for url in app.state.OLLAMA_BASE_URLS]
  124. responses = await asyncio.gather(*tasks)
  125. responses = list(filter(lambda x: x is not None, responses))
  126. lowest_version = min(
  127. responses, key=lambda x: tuple(map(int, x["version"].split(".")))
  128. )
  129. return {"version": lowest_version["version"]}
  130. else:
  131. url = app.state.OLLAMA_BASE_URLS[url_idx]
  132. try:
  133. r = requests.request(method="GET", url=f"{url}/api/version")
  134. r.raise_for_status()
  135. return r.json()
  136. except Exception as e:
  137. print(e)
  138. error_detail = "Open WebUI: Server Connection Error"
  139. if r is not None:
  140. try:
  141. res = r.json()
  142. if "error" in res:
  143. error_detail = f"Ollama: {res['error']}"
  144. except:
  145. error_detail = f"Ollama: {e}"
  146. raise HTTPException(
  147. status_code=r.status_code if r else 500,
  148. detail=error_detail,
  149. )
  150. class ModelNameForm(BaseModel):
  151. name: str
  152. @app.post("/api/pull")
  153. @app.post("/api/pull/{url_idx}")
  154. async def pull_model(
  155. form_data: ModelNameForm, url_idx: int = 0, user=Depends(get_admin_user)
  156. ):
  157. url = app.state.OLLAMA_BASE_URLS[url_idx]
  158. r = None
  159. def get_request(url):
  160. nonlocal r
  161. try:
  162. def stream_content():
  163. for chunk in r.iter_content(chunk_size=8192):
  164. yield chunk
  165. r = requests.request(
  166. method="POST",
  167. url=f"{url}/api/pull",
  168. data=form_data.model_dump_json(exclude_none=True),
  169. stream=True,
  170. )
  171. r.raise_for_status()
  172. return StreamingResponse(
  173. stream_content(),
  174. status_code=r.status_code,
  175. headers=dict(r.headers),
  176. )
  177. except Exception as e:
  178. raise e
  179. try:
  180. return await run_in_threadpool(get_request(url))
  181. except Exception as e:
  182. print(e)
  183. error_detail = "Open WebUI: Server Connection Error"
  184. if r is not None:
  185. try:
  186. res = r.json()
  187. if "error" in res:
  188. error_detail = f"Ollama: {res['error']}"
  189. except:
  190. error_detail = f"Ollama: {e}"
  191. raise HTTPException(
  192. status_code=r.status_code if r else 500,
  193. detail=error_detail,
  194. )
  195. class PushModelForm(BaseModel):
  196. name: str
  197. insecure: Optional[bool] = None
  198. stream: Optional[bool] = None
  199. @app.delete("/api/push")
  200. @app.delete("/api/push/{url_idx}")
  201. async def push_model(
  202. form_data: PushModelForm,
  203. url_idx: Optional[int] = None,
  204. user=Depends(get_admin_user),
  205. ):
  206. if url_idx == None:
  207. if form_data.name in app.state.MODELS:
  208. url_idx = app.state.MODELS[form_data.name]["urls"][0]
  209. else:
  210. raise HTTPException(
  211. status_code=400,
  212. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  213. )
  214. url = app.state.OLLAMA_BASE_URLS[url_idx]
  215. r = None
  216. def get_request():
  217. nonlocal url
  218. nonlocal r
  219. try:
  220. def stream_content():
  221. for chunk in r.iter_content(chunk_size=8192):
  222. yield chunk
  223. r = requests.request(
  224. method="POST",
  225. url=f"{url}/api/push",
  226. data=form_data.model_dump_json(exclude_none=True),
  227. )
  228. r.raise_for_status()
  229. return StreamingResponse(
  230. stream_content(),
  231. status_code=r.status_code,
  232. headers=dict(r.headers),
  233. )
  234. except Exception as e:
  235. raise e
  236. try:
  237. return await run_in_threadpool(get_request)
  238. except Exception as e:
  239. print(e)
  240. error_detail = "Open WebUI: Server Connection Error"
  241. if r is not None:
  242. try:
  243. res = r.json()
  244. if "error" in res:
  245. error_detail = f"Ollama: {res['error']}"
  246. except:
  247. error_detail = f"Ollama: {e}"
  248. raise HTTPException(
  249. status_code=r.status_code if r else 500,
  250. detail=error_detail,
  251. )
  252. class CreateModelForm(BaseModel):
  253. name: str
  254. modelfile: Optional[str] = None
  255. stream: Optional[bool] = None
  256. path: Optional[str] = None
  257. @app.post("/api/create")
  258. @app.post("/api/create/{url_idx}")
  259. async def create_model(
  260. form_data: CreateModelForm, url_idx: int = 0, user=Depends(get_admin_user)
  261. ):
  262. print(form_data)
  263. url = app.state.OLLAMA_BASE_URLS[url_idx]
  264. r = None
  265. def get_request():
  266. nonlocal url
  267. nonlocal r
  268. try:
  269. def stream_content():
  270. for chunk in r.iter_content(chunk_size=8192):
  271. yield chunk
  272. r = requests.request(
  273. method="POST",
  274. url=f"{url}/api/create",
  275. data=form_data.model_dump_json(exclude_none=True),
  276. stream=True,
  277. )
  278. r.raise_for_status()
  279. print(r)
  280. return StreamingResponse(
  281. stream_content(),
  282. status_code=r.status_code,
  283. headers=dict(r.headers),
  284. )
  285. except Exception as e:
  286. raise e
  287. try:
  288. return await run_in_threadpool(get_request)
  289. except Exception as e:
  290. print(e)
  291. error_detail = "Open WebUI: Server Connection Error"
  292. if r is not None:
  293. try:
  294. res = r.json()
  295. if "error" in res:
  296. error_detail = f"Ollama: {res['error']}"
  297. except:
  298. error_detail = f"Ollama: {e}"
  299. raise HTTPException(
  300. status_code=r.status_code if r else 500,
  301. detail=error_detail,
  302. )
  303. class CopyModelForm(BaseModel):
  304. source: str
  305. destination: str
  306. @app.post("/api/copy")
  307. @app.post("/api/copy/{url_idx}")
  308. async def copy_model(
  309. form_data: CopyModelForm,
  310. url_idx: Optional[int] = None,
  311. user=Depends(get_admin_user),
  312. ):
  313. if url_idx == None:
  314. if form_data.source in app.state.MODELS:
  315. url_idx = app.state.MODELS[form_data.source]["urls"][0]
  316. else:
  317. raise HTTPException(
  318. status_code=400,
  319. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.source),
  320. )
  321. url = app.state.OLLAMA_BASE_URLS[url_idx]
  322. try:
  323. r = requests.request(
  324. method="POST",
  325. url=f"{url}/api/copy",
  326. data=form_data.model_dump_json(exclude_none=True),
  327. )
  328. r.raise_for_status()
  329. print(r.text)
  330. return True
  331. except Exception as e:
  332. print(e)
  333. error_detail = "Open WebUI: Server Connection Error"
  334. if r is not None:
  335. try:
  336. res = r.json()
  337. if "error" in res:
  338. error_detail = f"Ollama: {res['error']}"
  339. except:
  340. error_detail = f"Ollama: {e}"
  341. raise HTTPException(
  342. status_code=r.status_code if r else 500,
  343. detail=error_detail,
  344. )
  345. @app.delete("/api/delete")
  346. @app.delete("/api/delete/{url_idx}")
  347. async def delete_model(
  348. form_data: ModelNameForm,
  349. url_idx: Optional[int] = None,
  350. user=Depends(get_admin_user),
  351. ):
  352. if url_idx == None:
  353. if form_data.name in app.state.MODELS:
  354. url_idx = app.state.MODELS[form_data.name]["urls"][0]
  355. else:
  356. raise HTTPException(
  357. status_code=400,
  358. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  359. )
  360. url = app.state.OLLAMA_BASE_URLS[url_idx]
  361. try:
  362. r = requests.request(
  363. method="DELETE",
  364. url=f"{url}/api/delete",
  365. data=form_data.model_dump_json(exclude_none=True),
  366. )
  367. r.raise_for_status()
  368. print(r.text)
  369. return True
  370. except Exception as e:
  371. print(e)
  372. error_detail = "Open WebUI: Server Connection Error"
  373. if r is not None:
  374. try:
  375. res = r.json()
  376. if "error" in res:
  377. error_detail = f"Ollama: {res['error']}"
  378. except:
  379. error_detail = f"Ollama: {e}"
  380. raise HTTPException(
  381. status_code=r.status_code if r else 500,
  382. detail=error_detail,
  383. )
  384. @app.post("/api/show")
  385. async def show_model_info(form_data: ModelNameForm, user=Depends(get_current_user)):
  386. if form_data.name not in app.state.MODELS:
  387. raise HTTPException(
  388. status_code=400,
  389. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
  390. )
  391. url_idx = random.choice(app.state.MODELS[form_data.name]["urls"])
  392. url = app.state.OLLAMA_BASE_URLS[url_idx]
  393. try:
  394. r = requests.request(
  395. method="POST",
  396. url=f"{url}/api/show",
  397. data=form_data.model_dump_json(exclude_none=True),
  398. )
  399. r.raise_for_status()
  400. return r.json()
  401. except Exception as e:
  402. print(e)
  403. error_detail = "Open WebUI: Server Connection Error"
  404. if r is not None:
  405. try:
  406. res = r.json()
  407. if "error" in res:
  408. error_detail = f"Ollama: {res['error']}"
  409. except:
  410. error_detail = f"Ollama: {e}"
  411. raise HTTPException(
  412. status_code=r.status_code if r else 500,
  413. detail=error_detail,
  414. )
  415. class GenerateEmbeddingsForm(BaseModel):
  416. model: str
  417. prompt: str
  418. options: Optional[dict] = None
  419. keep_alive: Optional[Union[int, str]] = None
  420. @app.post("/api/embeddings")
  421. @app.post("/api/embeddings/{url_idx}")
  422. async def generate_embeddings(
  423. form_data: GenerateEmbeddingsForm,
  424. url_idx: Optional[int] = None,
  425. user=Depends(get_current_user),
  426. ):
  427. if url_idx == None:
  428. if form_data.model in app.state.MODELS:
  429. url_idx = random.choice(app.state.MODELS[form_data.model]["urls"])
  430. else:
  431. raise HTTPException(
  432. status_code=400,
  433. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  434. )
  435. url = app.state.OLLAMA_BASE_URLS[url_idx]
  436. try:
  437. r = requests.request(
  438. method="POST",
  439. url=f"{url}/api/embeddings",
  440. data=form_data.model_dump_json(exclude_none=True),
  441. )
  442. r.raise_for_status()
  443. return r.json()
  444. except Exception as e:
  445. print(e)
  446. error_detail = "Open WebUI: Server Connection Error"
  447. if r is not None:
  448. try:
  449. res = r.json()
  450. if "error" in res:
  451. error_detail = f"Ollama: {res['error']}"
  452. except:
  453. error_detail = f"Ollama: {e}"
  454. raise HTTPException(
  455. status_code=r.status_code if r else 500,
  456. detail=error_detail,
  457. )
  458. class GenerateCompletionForm(BaseModel):
  459. model: str
  460. prompt: str
  461. images: Optional[List[str]] = None
  462. format: Optional[str] = None
  463. options: Optional[dict] = None
  464. system: Optional[str] = None
  465. template: Optional[str] = None
  466. context: Optional[str] = None
  467. stream: Optional[bool] = True
  468. raw: Optional[bool] = None
  469. keep_alive: Optional[Union[int, str]] = None
  470. @app.post("/api/generate")
  471. @app.post("/api/generate/{url_idx}")
  472. async def generate_completion(
  473. form_data: GenerateCompletionForm,
  474. url_idx: Optional[int] = None,
  475. user=Depends(get_current_user),
  476. ):
  477. if url_idx == None:
  478. if form_data.model in app.state.MODELS:
  479. url_idx = random.choice(app.state.MODELS[form_data.model]["urls"])
  480. else:
  481. raise HTTPException(
  482. status_code=400,
  483. detail="error_detail",
  484. )
  485. url = app.state.OLLAMA_BASE_URLS[url_idx]
  486. r = None
  487. def get_request():
  488. nonlocal form_data
  489. nonlocal r
  490. request_id = str(uuid.uuid4())
  491. try:
  492. REQUEST_POOL.append(request_id)
  493. def stream_content():
  494. try:
  495. if form_data.stream:
  496. yield json.dumps({"id": request_id, "done": False}) + "\n"
  497. for chunk in r.iter_content(chunk_size=8192):
  498. if request_id in REQUEST_POOL:
  499. yield chunk
  500. else:
  501. print("User: canceled request")
  502. break
  503. finally:
  504. if hasattr(r, "close"):
  505. r.close()
  506. if request_id in REQUEST_POOL:
  507. REQUEST_POOL.remove(request_id)
  508. r = requests.request(
  509. method="POST",
  510. url=f"{url}/api/generate",
  511. data=form_data.model_dump_json(exclude_none=True),
  512. stream=True,
  513. )
  514. r.raise_for_status()
  515. return StreamingResponse(
  516. stream_content(),
  517. status_code=r.status_code,
  518. headers=dict(r.headers),
  519. )
  520. except Exception as e:
  521. raise e
  522. try:
  523. return await run_in_threadpool(get_request)
  524. except Exception as e:
  525. error_detail = "Open WebUI: Server Connection Error"
  526. if r is not None:
  527. try:
  528. res = r.json()
  529. if "error" in res:
  530. error_detail = f"Ollama: {res['error']}"
  531. except:
  532. error_detail = f"Ollama: {e}"
  533. raise HTTPException(
  534. status_code=r.status_code if r else 500,
  535. detail=error_detail,
  536. )
  537. class ChatMessage(BaseModel):
  538. role: str
  539. content: str
  540. images: Optional[List[str]] = None
  541. class GenerateChatCompletionForm(BaseModel):
  542. model: str
  543. messages: List[ChatMessage]
  544. format: Optional[str] = None
  545. options: Optional[dict] = None
  546. template: Optional[str] = None
  547. stream: Optional[bool] = True
  548. keep_alive: Optional[Union[int, str]] = None
  549. @app.post("/api/chat")
  550. @app.post("/api/chat/{url_idx}")
  551. async def generate_chat_completion(
  552. form_data: GenerateChatCompletionForm,
  553. url_idx: Optional[int] = None,
  554. user=Depends(get_current_user),
  555. ):
  556. if url_idx == None:
  557. if form_data.model in app.state.MODELS:
  558. url_idx = random.choice(app.state.MODELS[form_data.model]["urls"])
  559. else:
  560. raise HTTPException(
  561. status_code=400,
  562. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  563. )
  564. url = app.state.OLLAMA_BASE_URLS[url_idx]
  565. r = None
  566. print(form_data.model_dump_json(exclude_none=True))
  567. def get_request():
  568. nonlocal form_data
  569. nonlocal r
  570. request_id = str(uuid.uuid4())
  571. try:
  572. REQUEST_POOL.append(request_id)
  573. def stream_content():
  574. try:
  575. if form_data.stream:
  576. yield json.dumps({"id": request_id, "done": False}) + "\n"
  577. for chunk in r.iter_content(chunk_size=8192):
  578. if request_id in REQUEST_POOL:
  579. yield chunk
  580. else:
  581. print("User: canceled request")
  582. break
  583. finally:
  584. if hasattr(r, "close"):
  585. r.close()
  586. if request_id in REQUEST_POOL:
  587. REQUEST_POOL.remove(request_id)
  588. r = requests.request(
  589. method="POST",
  590. url=f"{url}/api/chat",
  591. data=form_data.model_dump_json(exclude_none=True),
  592. stream=True,
  593. )
  594. r.raise_for_status()
  595. return StreamingResponse(
  596. stream_content(),
  597. status_code=r.status_code,
  598. headers=dict(r.headers),
  599. )
  600. except Exception as e:
  601. raise e
  602. try:
  603. return await run_in_threadpool(get_request)
  604. except Exception as e:
  605. error_detail = "Open WebUI: Server Connection Error"
  606. if r is not None:
  607. try:
  608. res = r.json()
  609. if "error" in res:
  610. error_detail = f"Ollama: {res['error']}"
  611. except:
  612. error_detail = f"Ollama: {e}"
  613. raise HTTPException(
  614. status_code=r.status_code if r else 500,
  615. detail=error_detail,
  616. )
  617. # TODO: we should update this part once Ollama supports other types
  618. class OpenAIChatMessage(BaseModel):
  619. role: str
  620. content: str
  621. model_config = ConfigDict(extra="allow")
  622. class OpenAIChatCompletionForm(BaseModel):
  623. model: str
  624. messages: List[OpenAIChatMessage]
  625. model_config = ConfigDict(extra="allow")
  626. @app.post("/v1/chat/completions")
  627. @app.post("/v1/chat/completions/{url_idx}")
  628. async def generate_openai_chat_completion(
  629. form_data: OpenAIChatCompletionForm,
  630. url_idx: Optional[int] = None,
  631. user=Depends(get_current_user),
  632. ):
  633. if url_idx == None:
  634. if form_data.model in app.state.MODELS:
  635. url_idx = random.choice(app.state.MODELS[form_data.model]["urls"])
  636. else:
  637. raise HTTPException(
  638. status_code=400,
  639. detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
  640. )
  641. url = app.state.OLLAMA_BASE_URLS[url_idx]
  642. r = None
  643. def get_request():
  644. nonlocal form_data
  645. nonlocal r
  646. request_id = str(uuid.uuid4())
  647. try:
  648. REQUEST_POOL.append(request_id)
  649. def stream_content():
  650. try:
  651. if form_data.stream:
  652. yield json.dumps(
  653. {"request_id": request_id, "done": False}
  654. ) + "\n"
  655. for chunk in r.iter_content(chunk_size=8192):
  656. if request_id in REQUEST_POOL:
  657. yield chunk
  658. else:
  659. print("User: canceled request")
  660. break
  661. finally:
  662. if hasattr(r, "close"):
  663. r.close()
  664. if request_id in REQUEST_POOL:
  665. REQUEST_POOL.remove(request_id)
  666. r = requests.request(
  667. method="POST",
  668. url=f"{url}/v1/chat/completions",
  669. data=form_data.model_dump_json(exclude_none=True),
  670. stream=True,
  671. )
  672. r.raise_for_status()
  673. return StreamingResponse(
  674. stream_content(),
  675. status_code=r.status_code,
  676. headers=dict(r.headers),
  677. )
  678. except Exception as e:
  679. raise e
  680. try:
  681. return await run_in_threadpool(get_request)
  682. except Exception as e:
  683. error_detail = "Open WebUI: Server Connection Error"
  684. if r is not None:
  685. try:
  686. res = r.json()
  687. if "error" in res:
  688. error_detail = f"Ollama: {res['error']}"
  689. except:
  690. error_detail = f"Ollama: {e}"
  691. raise HTTPException(
  692. status_code=r.status_code if r else 500,
  693. detail=error_detail,
  694. )
  695. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  696. async def deprecated_proxy(path: str, request: Request, user=Depends(get_current_user)):
  697. url = app.state.OLLAMA_BASE_URLS[0]
  698. target_url = f"{url}/{path}"
  699. body = await request.body()
  700. headers = dict(request.headers)
  701. if user.role in ["user", "admin"]:
  702. if path in ["pull", "delete", "push", "copy", "create"]:
  703. if user.role != "admin":
  704. raise HTTPException(
  705. status_code=status.HTTP_401_UNAUTHORIZED,
  706. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  707. )
  708. else:
  709. raise HTTPException(
  710. status_code=status.HTTP_401_UNAUTHORIZED,
  711. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  712. )
  713. headers.pop("host", None)
  714. headers.pop("authorization", None)
  715. headers.pop("origin", None)
  716. headers.pop("referer", None)
  717. r = None
  718. def get_request():
  719. nonlocal r
  720. request_id = str(uuid.uuid4())
  721. try:
  722. REQUEST_POOL.append(request_id)
  723. def stream_content():
  724. try:
  725. if path == "generate":
  726. data = json.loads(body.decode("utf-8"))
  727. if not ("stream" in data and data["stream"] == False):
  728. yield json.dumps({"id": request_id, "done": False}) + "\n"
  729. elif path == "chat":
  730. yield json.dumps({"id": request_id, "done": False}) + "\n"
  731. for chunk in r.iter_content(chunk_size=8192):
  732. if request_id in REQUEST_POOL:
  733. yield chunk
  734. else:
  735. print("User: canceled request")
  736. break
  737. finally:
  738. if hasattr(r, "close"):
  739. r.close()
  740. if request_id in REQUEST_POOL:
  741. REQUEST_POOL.remove(request_id)
  742. r = requests.request(
  743. method=request.method,
  744. url=target_url,
  745. data=body,
  746. headers=headers,
  747. stream=True,
  748. )
  749. r.raise_for_status()
  750. # r.close()
  751. return StreamingResponse(
  752. stream_content(),
  753. status_code=r.status_code,
  754. headers=dict(r.headers),
  755. )
  756. except Exception as e:
  757. raise e
  758. try:
  759. return await run_in_threadpool(get_request)
  760. except Exception as e:
  761. error_detail = "Open WebUI: Server Connection Error"
  762. if r is not None:
  763. try:
  764. res = r.json()
  765. if "error" in res:
  766. error_detail = f"Ollama: {res['error']}"
  767. except:
  768. error_detail = f"Ollama: {e}"
  769. raise HTTPException(
  770. status_code=r.status_code if r else 500,
  771. detail=error_detail,
  772. )