main.py 15 KB

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