main.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. from fastapi import FastAPI, Request, HTTPException, Depends
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from fastapi.responses import StreamingResponse, FileResponse
  4. import requests
  5. import aiohttp
  6. import asyncio
  7. import json
  8. import logging
  9. from pydantic import BaseModel
  10. from starlette.background import BackgroundTask
  11. from apps.webui.models.models import Models
  12. from constants import ERROR_MESSAGES
  13. from utils.utils import (
  14. get_verified_user,
  15. get_admin_user,
  16. )
  17. from utils.misc import (
  18. apply_model_params_to_body_openai,
  19. apply_model_system_prompt_to_body,
  20. )
  21. from config import (
  22. SRC_LOG_LEVELS,
  23. ENABLE_OPENAI_API,
  24. AIOHTTP_CLIENT_TIMEOUT,
  25. OPENAI_API_BASE_URLS,
  26. OPENAI_API_KEYS,
  27. CACHE_DIR,
  28. ENABLE_MODEL_FILTER,
  29. MODEL_FILTER_LIST,
  30. AppConfig,
  31. )
  32. from typing import Optional, Literal, overload
  33. import hashlib
  34. from pathlib import Path
  35. log = logging.getLogger(__name__)
  36. log.setLevel(SRC_LOG_LEVELS["OPENAI"])
  37. app = FastAPI()
  38. app.add_middleware(
  39. CORSMiddleware,
  40. allow_origins=["*"],
  41. allow_credentials=True,
  42. allow_methods=["*"],
  43. allow_headers=["*"],
  44. )
  45. app.state.config = AppConfig()
  46. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  47. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  48. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  49. app.state.config.OPENAI_API_BASE_URLS = OPENAI_API_BASE_URLS
  50. app.state.config.OPENAI_API_KEYS = OPENAI_API_KEYS
  51. app.state.MODELS = {}
  52. @app.middleware("http")
  53. async def check_url(request: Request, call_next):
  54. if len(app.state.MODELS) == 0:
  55. await get_all_models()
  56. response = await call_next(request)
  57. return response
  58. @app.get("/config")
  59. async def get_config(user=Depends(get_admin_user)):
  60. return {"ENABLE_OPENAI_API": app.state.config.ENABLE_OPENAI_API}
  61. class OpenAIConfigForm(BaseModel):
  62. enable_openai_api: Optional[bool] = None
  63. @app.post("/config/update")
  64. async def update_config(form_data: OpenAIConfigForm, user=Depends(get_admin_user)):
  65. app.state.config.ENABLE_OPENAI_API = form_data.enable_openai_api
  66. return {"ENABLE_OPENAI_API": app.state.config.ENABLE_OPENAI_API}
  67. class UrlsUpdateForm(BaseModel):
  68. urls: list[str]
  69. class KeysUpdateForm(BaseModel):
  70. keys: list[str]
  71. @app.get("/urls")
  72. async def get_openai_urls(user=Depends(get_admin_user)):
  73. return {"OPENAI_API_BASE_URLS": app.state.config.OPENAI_API_BASE_URLS}
  74. @app.post("/urls/update")
  75. async def update_openai_urls(form_data: UrlsUpdateForm, user=Depends(get_admin_user)):
  76. await get_all_models()
  77. app.state.config.OPENAI_API_BASE_URLS = form_data.urls
  78. return {"OPENAI_API_BASE_URLS": app.state.config.OPENAI_API_BASE_URLS}
  79. @app.get("/keys")
  80. async def get_openai_keys(user=Depends(get_admin_user)):
  81. return {"OPENAI_API_KEYS": app.state.config.OPENAI_API_KEYS}
  82. @app.post("/keys/update")
  83. async def update_openai_key(form_data: KeysUpdateForm, user=Depends(get_admin_user)):
  84. app.state.config.OPENAI_API_KEYS = form_data.keys
  85. return {"OPENAI_API_KEYS": app.state.config.OPENAI_API_KEYS}
  86. @app.post("/audio/speech")
  87. async def speech(request: Request, user=Depends(get_verified_user)):
  88. idx = None
  89. try:
  90. idx = app.state.config.OPENAI_API_BASE_URLS.index("https://api.openai.com/v1")
  91. body = await request.body()
  92. name = hashlib.sha256(body).hexdigest()
  93. SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
  94. SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
  95. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  96. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  97. # Check if the file already exists in the cache
  98. if file_path.is_file():
  99. return FileResponse(file_path)
  100. headers = {}
  101. headers["Authorization"] = f"Bearer {app.state.config.OPENAI_API_KEYS[idx]}"
  102. headers["Content-Type"] = "application/json"
  103. if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
  104. headers["HTTP-Referer"] = "https://openwebui.com/"
  105. headers["X-Title"] = "Open WebUI"
  106. r = None
  107. try:
  108. r = requests.post(
  109. url=f"{app.state.config.OPENAI_API_BASE_URLS[idx]}/audio/speech",
  110. data=body,
  111. headers=headers,
  112. stream=True,
  113. )
  114. r.raise_for_status()
  115. # Save the streaming content to a file
  116. with open(file_path, "wb") as f:
  117. for chunk in r.iter_content(chunk_size=8192):
  118. f.write(chunk)
  119. with open(file_body_path, "w") as f:
  120. json.dump(json.loads(body.decode("utf-8")), f)
  121. # Return the saved file
  122. return FileResponse(file_path)
  123. except Exception as e:
  124. log.exception(e)
  125. error_detail = "Open WebUI: Server Connection Error"
  126. if r is not None:
  127. try:
  128. res = r.json()
  129. if "error" in res:
  130. error_detail = f"External: {res['error']}"
  131. except Exception:
  132. error_detail = f"External: {e}"
  133. raise HTTPException(
  134. status_code=r.status_code if r else 500, detail=error_detail
  135. )
  136. except ValueError:
  137. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.OPENAI_NOT_FOUND)
  138. async def fetch_url(url, key):
  139. timeout = aiohttp.ClientTimeout(total=5)
  140. try:
  141. headers = {"Authorization": f"Bearer {key}"}
  142. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  143. async with session.get(url, headers=headers) as response:
  144. return await response.json()
  145. except Exception as e:
  146. # Handle connection error here
  147. log.error(f"Connection error: {e}")
  148. return None
  149. async def cleanup_response(
  150. response: Optional[aiohttp.ClientResponse],
  151. session: Optional[aiohttp.ClientSession],
  152. ):
  153. if response:
  154. response.close()
  155. if session:
  156. await session.close()
  157. def merge_models_lists(model_lists):
  158. log.debug(f"merge_models_lists {model_lists}")
  159. merged_list = []
  160. for idx, models in enumerate(model_lists):
  161. if models is not None and "error" not in models:
  162. merged_list.extend(
  163. [
  164. {
  165. **model,
  166. "name": model.get("name", model["id"]),
  167. "owned_by": "openai",
  168. "openai": model,
  169. "urlIdx": idx,
  170. }
  171. for model in models
  172. if "api.openai.com"
  173. not in app.state.config.OPENAI_API_BASE_URLS[idx]
  174. or "gpt" in model["id"]
  175. ]
  176. )
  177. return merged_list
  178. def is_openai_api_disabled():
  179. api_keys = app.state.config.OPENAI_API_KEYS
  180. no_keys = len(api_keys) == 1 and api_keys[0] == ""
  181. return no_keys or not app.state.config.ENABLE_OPENAI_API
  182. async def get_all_models_raw() -> list:
  183. if is_openai_api_disabled():
  184. return []
  185. # Check if API KEYS length is same than API URLS length
  186. num_urls = len(app.state.config.OPENAI_API_BASE_URLS)
  187. num_keys = len(app.state.config.OPENAI_API_KEYS)
  188. if num_keys != num_urls:
  189. # if there are more keys than urls, remove the extra keys
  190. if num_keys > num_urls:
  191. new_keys = app.state.config.OPENAI_API_KEYS[:num_urls]
  192. app.state.config.OPENAI_API_KEYS = new_keys
  193. # if there are more urls than keys, add empty keys
  194. else:
  195. app.state.config.OPENAI_API_KEYS += [""] * (num_urls - num_keys)
  196. tasks = [
  197. fetch_url(f"{url}/models", app.state.config.OPENAI_API_KEYS[idx])
  198. for idx, url in enumerate(app.state.config.OPENAI_API_BASE_URLS)
  199. ]
  200. responses = await asyncio.gather(*tasks)
  201. log.debug(f"get_all_models:responses() {responses}")
  202. return responses
  203. @overload
  204. async def get_all_models(raw: Literal[True]) -> list: ...
  205. @overload
  206. async def get_all_models(raw: Literal[False] = False) -> dict[str, list]: ...
  207. async def get_all_models(raw=False) -> dict[str, list] | list:
  208. log.info("get_all_models()")
  209. if is_openai_api_disabled():
  210. return [] if raw else {"data": []}
  211. responses = await get_all_models_raw()
  212. if raw:
  213. return responses
  214. def extract_data(response):
  215. if response and "data" in response:
  216. return response["data"]
  217. if isinstance(response, list):
  218. return response
  219. return None
  220. models = {"data": merge_models_lists(map(extract_data, responses))}
  221. log.debug(f"models: {models}")
  222. app.state.MODELS = {model["id"]: model for model in models["data"]}
  223. return models
  224. @app.get("/models")
  225. @app.get("/models/{url_idx}")
  226. async def get_models(url_idx: Optional[int] = None, user=Depends(get_verified_user)):
  227. if url_idx is None:
  228. models = await get_all_models()
  229. if app.state.config.ENABLE_MODEL_FILTER:
  230. if user.role == "user":
  231. models["data"] = list(
  232. filter(
  233. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  234. models["data"],
  235. )
  236. )
  237. return models
  238. return models
  239. else:
  240. url = app.state.config.OPENAI_API_BASE_URLS[url_idx]
  241. key = app.state.config.OPENAI_API_KEYS[url_idx]
  242. headers = {}
  243. headers["Authorization"] = f"Bearer {key}"
  244. headers["Content-Type"] = "application/json"
  245. r = None
  246. try:
  247. r = requests.request(method="GET", url=f"{url}/models", headers=headers)
  248. r.raise_for_status()
  249. response_data = r.json()
  250. if "api.openai.com" in url:
  251. response_data["data"] = list(
  252. filter(lambda model: "gpt" in model["id"], response_data["data"])
  253. )
  254. return response_data
  255. except Exception as e:
  256. log.exception(e)
  257. error_detail = "Open WebUI: Server Connection Error"
  258. if r is not None:
  259. try:
  260. res = r.json()
  261. if "error" in res:
  262. error_detail = f"External: {res['error']}"
  263. except Exception:
  264. error_detail = f"External: {e}"
  265. raise HTTPException(
  266. status_code=r.status_code if r else 500,
  267. detail=error_detail,
  268. )
  269. @app.post("/chat/completions")
  270. @app.post("/chat/completions/{url_idx}")
  271. async def generate_chat_completion(
  272. form_data: dict,
  273. url_idx: Optional[int] = None,
  274. user=Depends(get_verified_user),
  275. ):
  276. idx = 0
  277. payload = {**form_data}
  278. if "metadata" in payload:
  279. del payload["metadata"]
  280. model_id = form_data.get("model")
  281. model_info = Models.get_model_by_id(model_id)
  282. if model_info:
  283. if model_info.base_model_id:
  284. payload["model"] = model_info.base_model_id
  285. params = model_info.params.model_dump()
  286. payload = apply_model_params_to_body_openai(params, payload)
  287. payload = apply_model_system_prompt_to_body(params, payload, user)
  288. model = app.state.MODELS[payload.get("model")]
  289. idx = model["urlIdx"]
  290. if "pipeline" in model and model.get("pipeline"):
  291. payload["user"] = {
  292. "name": user.name,
  293. "id": user.id,
  294. "email": user.email,
  295. "role": user.role,
  296. }
  297. # Convert the modified body back to JSON
  298. payload = json.dumps(payload)
  299. log.debug(payload)
  300. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  301. key = app.state.config.OPENAI_API_KEYS[idx]
  302. headers = {}
  303. headers["Authorization"] = f"Bearer {key}"
  304. headers["Content-Type"] = "application/json"
  305. if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
  306. headers["HTTP-Referer"] = "https://openwebui.com/"
  307. headers["X-Title"] = "Open WebUI"
  308. r = None
  309. session = None
  310. streaming = False
  311. try:
  312. session = aiohttp.ClientSession(
  313. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  314. )
  315. r = await session.request(
  316. method="POST",
  317. url=f"{url}/chat/completions",
  318. data=payload,
  319. headers=headers,
  320. )
  321. r.raise_for_status()
  322. # Check if response is SSE
  323. if "text/event-stream" in r.headers.get("Content-Type", ""):
  324. streaming = True
  325. return StreamingResponse(
  326. r.content,
  327. status_code=r.status,
  328. headers=dict(r.headers),
  329. background=BackgroundTask(
  330. cleanup_response, response=r, session=session
  331. ),
  332. )
  333. else:
  334. response_data = await r.json()
  335. return response_data
  336. except Exception as e:
  337. log.exception(e)
  338. error_detail = "Open WebUI: Server Connection Error"
  339. if r is not None:
  340. try:
  341. res = await r.json()
  342. print(res)
  343. if "error" in res:
  344. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  345. except Exception:
  346. error_detail = f"External: {e}"
  347. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  348. finally:
  349. if not streaming and session:
  350. if r:
  351. r.close()
  352. await session.close()
  353. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  354. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  355. idx = 0
  356. body = await request.body()
  357. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  358. key = app.state.config.OPENAI_API_KEYS[idx]
  359. target_url = f"{url}/{path}"
  360. headers = {}
  361. headers["Authorization"] = f"Bearer {key}"
  362. headers["Content-Type"] = "application/json"
  363. r = None
  364. session = None
  365. streaming = False
  366. try:
  367. session = aiohttp.ClientSession(trust_env=True)
  368. r = await session.request(
  369. method=request.method,
  370. url=target_url,
  371. data=body,
  372. headers=headers,
  373. )
  374. r.raise_for_status()
  375. # Check if response is SSE
  376. if "text/event-stream" in r.headers.get("Content-Type", ""):
  377. streaming = True
  378. return StreamingResponse(
  379. r.content,
  380. status_code=r.status,
  381. headers=dict(r.headers),
  382. background=BackgroundTask(
  383. cleanup_response, response=r, session=session
  384. ),
  385. )
  386. else:
  387. response_data = await r.json()
  388. return response_data
  389. except Exception as e:
  390. log.exception(e)
  391. error_detail = "Open WebUI: Server Connection Error"
  392. if r is not None:
  393. try:
  394. res = await r.json()
  395. print(res)
  396. if "error" in res:
  397. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  398. except Exception:
  399. error_detail = f"External: {e}"
  400. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  401. finally:
  402. if not streaming and session:
  403. if r:
  404. r.close()
  405. await session.close()