main.py 15 KB

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