main.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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
  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. async def get_all_models() -> dict[str, list]:
  201. log.info("get_all_models()")
  202. if is_openai_api_disabled():
  203. return {"data": []}
  204. responses = await get_all_models_raw()
  205. def extract_data(response):
  206. if response and "data" in response:
  207. return response["data"]
  208. if isinstance(response, list):
  209. return response
  210. return None
  211. models = {"data": merge_models_lists(map(extract_data, responses))}
  212. log.debug(f"models: {models}")
  213. app.state.MODELS = {model["id"]: model for model in models["data"]}
  214. return models
  215. @app.get("/models")
  216. @app.get("/models/{url_idx}")
  217. async def get_models(url_idx: Optional[int] = None, user=Depends(get_verified_user)):
  218. if url_idx is None:
  219. models = await get_all_models()
  220. if app.state.config.ENABLE_MODEL_FILTER:
  221. if user.role == "user":
  222. models["data"] = list(
  223. filter(
  224. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  225. models["data"],
  226. )
  227. )
  228. return models
  229. return models
  230. else:
  231. url = app.state.config.OPENAI_API_BASE_URLS[url_idx]
  232. key = app.state.config.OPENAI_API_KEYS[url_idx]
  233. headers = {}
  234. headers["Authorization"] = f"Bearer {key}"
  235. headers["Content-Type"] = "application/json"
  236. r = None
  237. try:
  238. r = requests.request(method="GET", url=f"{url}/models", headers=headers)
  239. r.raise_for_status()
  240. response_data = r.json()
  241. if "api.openai.com" in url:
  242. response_data["data"] = list(
  243. filter(lambda model: "gpt" in model["id"], response_data["data"])
  244. )
  245. return response_data
  246. except Exception as e:
  247. log.exception(e)
  248. error_detail = "Open WebUI: Server Connection Error"
  249. if r is not None:
  250. try:
  251. res = r.json()
  252. if "error" in res:
  253. error_detail = f"External: {res['error']}"
  254. except Exception:
  255. error_detail = f"External: {e}"
  256. raise HTTPException(
  257. status_code=r.status_code if r else 500,
  258. detail=error_detail,
  259. )
  260. @app.post("/chat/completions")
  261. @app.post("/chat/completions/{url_idx}")
  262. async def generate_chat_completion(
  263. form_data: dict,
  264. url_idx: Optional[int] = None,
  265. user=Depends(get_verified_user),
  266. ):
  267. idx = 0
  268. payload = {**form_data}
  269. payload.pop("metadata")
  270. model_id = form_data.get("model")
  271. model_info = Models.get_model_by_id(model_id)
  272. if model_info:
  273. if model_info.base_model_id:
  274. payload["model"] = model_info.base_model_id
  275. params = model_info.params.model_dump()
  276. payload = apply_model_params_to_body(params, payload)
  277. payload = apply_model_system_prompt_to_body(params, payload, user)
  278. model = app.state.MODELS[payload.get("model")]
  279. idx = model["urlIdx"]
  280. if "pipeline" in model and model.get("pipeline"):
  281. payload["user"] = {
  282. "name": user.name,
  283. "id": user.id,
  284. "email": user.email,
  285. "role": user.role,
  286. }
  287. # Check if the model is "gpt-4-vision-preview" and set "max_tokens" to 4000
  288. # This is a workaround until OpenAI fixes the issue with this model
  289. if payload.get("model") == "gpt-4-vision-preview":
  290. if "max_tokens" not in payload:
  291. payload["max_tokens"] = 4000
  292. log.debug("Modified payload:", payload)
  293. # Convert the modified body back to JSON
  294. payload = json.dumps(payload)
  295. log.debug(payload)
  296. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  297. key = app.state.config.OPENAI_API_KEYS[idx]
  298. headers = {}
  299. headers["Authorization"] = f"Bearer {key}"
  300. headers["Content-Type"] = "application/json"
  301. if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
  302. headers["HTTP-Referer"] = "https://openwebui.com/"
  303. headers["X-Title"] = "Open WebUI"
  304. r = None
  305. session = None
  306. streaming = False
  307. try:
  308. session = aiohttp.ClientSession(
  309. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  310. )
  311. r = await session.request(
  312. method="POST",
  313. url=f"{url}/chat/completions",
  314. data=payload,
  315. headers=headers,
  316. )
  317. r.raise_for_status()
  318. # Check if response is SSE
  319. if "text/event-stream" in r.headers.get("Content-Type", ""):
  320. streaming = True
  321. return StreamingResponse(
  322. r.content,
  323. status_code=r.status,
  324. headers=dict(r.headers),
  325. background=BackgroundTask(
  326. cleanup_response, response=r, session=session
  327. ),
  328. )
  329. else:
  330. response_data = await r.json()
  331. return response_data
  332. except Exception as e:
  333. log.exception(e)
  334. error_detail = "Open WebUI: Server Connection Error"
  335. if r is not None:
  336. try:
  337. res = await r.json()
  338. print(res)
  339. if "error" in res:
  340. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  341. except Exception:
  342. error_detail = f"External: {e}"
  343. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  344. finally:
  345. if not streaming and session:
  346. if r:
  347. r.close()
  348. await session.close()
  349. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  350. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  351. idx = 0
  352. body = await request.body()
  353. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  354. key = app.state.config.OPENAI_API_KEYS[idx]
  355. target_url = f"{url}/{path}"
  356. headers = {}
  357. headers["Authorization"] = f"Bearer {key}"
  358. headers["Content-Type"] = "application/json"
  359. r = None
  360. session = None
  361. streaming = False
  362. try:
  363. session = aiohttp.ClientSession(trust_env=True)
  364. r = await session.request(
  365. method=request.method,
  366. url=target_url,
  367. data=body,
  368. headers=headers,
  369. )
  370. r.raise_for_status()
  371. # Check if response is SSE
  372. if "text/event-stream" in r.headers.get("Content-Type", ""):
  373. streaming = True
  374. return StreamingResponse(
  375. r.content,
  376. status_code=r.status,
  377. headers=dict(r.headers),
  378. background=BackgroundTask(
  379. cleanup_response, response=r, session=session
  380. ),
  381. )
  382. else:
  383. response_data = await r.json()
  384. return response_data
  385. except Exception as e:
  386. log.exception(e)
  387. error_detail = "Open WebUI: Server Connection Error"
  388. if r is not None:
  389. try:
  390. res = await r.json()
  391. print(res)
  392. if "error" in res:
  393. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  394. except Exception:
  395. error_detail = f"External: {e}"
  396. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  397. finally:
  398. if not streaming and session:
  399. if r:
  400. r.close()
  401. await session.close()