main.py 34 KB

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