main.py 15 KB

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