main.py 15 KB

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