main.py 35 KB

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