main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. CACHE_DIR,
  12. CORS_ALLOW_ORIGIN,
  13. ENABLE_MODEL_FILTER,
  14. ENABLE_OPENAI_API,
  15. MODEL_FILTER_LIST,
  16. OPENAI_API_BASE_URLS,
  17. OPENAI_API_KEYS,
  18. AppConfig,
  19. )
  20. from open_webui.env import (
  21. AIOHTTP_CLIENT_TIMEOUT,
  22. AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST,
  23. )
  24. from open_webui.constants import ERROR_MESSAGES
  25. from open_webui.env import SRC_LOG_LEVELS
  26. from fastapi import Depends, FastAPI, HTTPException, Request
  27. from fastapi.middleware.cors import CORSMiddleware
  28. from fastapi.responses import FileResponse, StreamingResponse
  29. from pydantic import BaseModel
  30. from starlette.background import BackgroundTask
  31. from open_webui.utils.payload import (
  32. apply_model_params_to_body_openai,
  33. apply_model_system_prompt_to_body,
  34. )
  35. from open_webui.utils.utils import get_admin_user, get_verified_user
  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=AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST)
  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 not any(
  176. name in model["id"]
  177. for name in [
  178. "babbage",
  179. "dall-e",
  180. "davinci",
  181. "embedding",
  182. "tts",
  183. "whisper",
  184. ]
  185. )
  186. ]
  187. )
  188. return merged_list
  189. def is_openai_api_disabled():
  190. api_keys = app.state.config.OPENAI_API_KEYS
  191. no_keys = len(api_keys) == 1 and api_keys[0] == ""
  192. return no_keys or not app.state.config.ENABLE_OPENAI_API
  193. async def get_all_models_raw() -> list:
  194. if is_openai_api_disabled():
  195. return []
  196. # Check if API KEYS length is same than API URLS length
  197. num_urls = len(app.state.config.OPENAI_API_BASE_URLS)
  198. num_keys = len(app.state.config.OPENAI_API_KEYS)
  199. if num_keys != num_urls:
  200. # if there are more keys than urls, remove the extra keys
  201. if num_keys > num_urls:
  202. new_keys = app.state.config.OPENAI_API_KEYS[:num_urls]
  203. app.state.config.OPENAI_API_KEYS = new_keys
  204. # if there are more urls than keys, add empty keys
  205. else:
  206. app.state.config.OPENAI_API_KEYS += [""] * (num_urls - num_keys)
  207. tasks = [
  208. fetch_url(f"{url}/models", app.state.config.OPENAI_API_KEYS[idx])
  209. for idx, url in enumerate(app.state.config.OPENAI_API_BASE_URLS)
  210. ]
  211. responses = await asyncio.gather(*tasks)
  212. log.debug(f"get_all_models:responses() {responses}")
  213. return responses
  214. @overload
  215. async def get_all_models(raw: Literal[True]) -> list: ...
  216. @overload
  217. async def get_all_models(raw: Literal[False] = False) -> dict[str, list]: ...
  218. async def get_all_models(raw=False) -> dict[str, list] | list:
  219. log.info("get_all_models()")
  220. if is_openai_api_disabled():
  221. return [] if raw else {"data": []}
  222. responses = await get_all_models_raw()
  223. if raw:
  224. return responses
  225. def extract_data(response):
  226. if response and "data" in response:
  227. return response["data"]
  228. if isinstance(response, list):
  229. return response
  230. return None
  231. models = {"data": merge_models_lists(map(extract_data, responses))}
  232. log.debug(f"models: {models}")
  233. app.state.MODELS = {model["id"]: model for model in models["data"]}
  234. return models
  235. @app.get("/models")
  236. @app.get("/models/{url_idx}")
  237. async def get_models(url_idx: Optional[int] = None, user=Depends(get_verified_user)):
  238. if url_idx is None:
  239. models = await get_all_models()
  240. if app.state.config.ENABLE_MODEL_FILTER:
  241. if user.role == "user":
  242. models["data"] = list(
  243. filter(
  244. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  245. models["data"],
  246. )
  247. )
  248. return models
  249. return models
  250. else:
  251. url = app.state.config.OPENAI_API_BASE_URLS[url_idx]
  252. key = app.state.config.OPENAI_API_KEYS[url_idx]
  253. headers = {}
  254. headers["Authorization"] = f"Bearer {key}"
  255. headers["Content-Type"] = "application/json"
  256. r = None
  257. try:
  258. r = requests.request(method="GET", url=f"{url}/models", headers=headers)
  259. r.raise_for_status()
  260. response_data = r.json()
  261. if "api.openai.com" in url:
  262. # Filter the response data
  263. response_data["data"] = [
  264. model
  265. for model in response_data["data"]
  266. if not any(
  267. name in model["id"]
  268. for name in [
  269. "babbage",
  270. "dall-e",
  271. "davinci",
  272. "embedding",
  273. "tts",
  274. "whisper",
  275. ]
  276. )
  277. ]
  278. return response_data
  279. except Exception as e:
  280. log.exception(e)
  281. error_detail = "Open WebUI: Server Connection Error"
  282. if r is not None:
  283. try:
  284. res = r.json()
  285. if "error" in res:
  286. error_detail = f"External: {res['error']}"
  287. except Exception:
  288. error_detail = f"External: {e}"
  289. raise HTTPException(
  290. status_code=r.status_code if r else 500,
  291. detail=error_detail,
  292. )
  293. @app.post("/chat/completions")
  294. @app.post("/chat/completions/{url_idx}")
  295. async def generate_chat_completion(
  296. form_data: dict,
  297. url_idx: Optional[int] = None,
  298. user=Depends(get_verified_user),
  299. ):
  300. idx = 0
  301. payload = {**form_data}
  302. if "metadata" in payload:
  303. del payload["metadata"]
  304. model_id = form_data.get("model")
  305. model_info = Models.get_model_by_id(model_id)
  306. if model_info:
  307. if model_info.base_model_id:
  308. payload["model"] = model_info.base_model_id
  309. params = model_info.params.model_dump()
  310. payload = apply_model_params_to_body_openai(params, payload)
  311. payload = apply_model_system_prompt_to_body(params, payload, user)
  312. model = app.state.MODELS[payload.get("model")]
  313. idx = model["urlIdx"]
  314. if "pipeline" in model and model.get("pipeline"):
  315. payload["user"] = {
  316. "name": user.name,
  317. "id": user.id,
  318. "email": user.email,
  319. "role": user.role,
  320. }
  321. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  322. key = app.state.config.OPENAI_API_KEYS[idx]
  323. is_o1 = payload["model"].lower().startswith("o1-")
  324. # Change max_completion_tokens to max_tokens (Backward compatible)
  325. if "api.openai.com" not in url and not is_o1:
  326. if "max_completion_tokens" in payload:
  327. # Remove "max_completion_tokens" from the payload
  328. payload["max_tokens"] = payload["max_completion_tokens"]
  329. del payload["max_completion_tokens"]
  330. else:
  331. if is_o1 and "max_tokens" in payload:
  332. payload["max_completion_tokens"] = payload["max_tokens"]
  333. del payload["max_tokens"]
  334. if "max_tokens" in payload and "max_completion_tokens" in payload:
  335. del payload["max_tokens"]
  336. # Fix: O1 does not support the "system" parameter, Modify "system" to "user"
  337. if is_o1 and payload["messages"][0]["role"] == "system":
  338. payload["messages"][0]["role"] = "user"
  339. # Convert the modified body back to JSON
  340. payload = json.dumps(payload)
  341. log.debug(payload)
  342. headers = {}
  343. headers["Authorization"] = f"Bearer {key}"
  344. headers["Content-Type"] = "application/json"
  345. if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
  346. headers["HTTP-Referer"] = "https://openwebui.com/"
  347. headers["X-Title"] = "Open WebUI"
  348. r = None
  349. session = None
  350. streaming = False
  351. response = None
  352. try:
  353. session = aiohttp.ClientSession(
  354. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  355. )
  356. r = await session.request(
  357. method="POST",
  358. url=f"{url}/chat/completions",
  359. data=payload,
  360. headers=headers,
  361. )
  362. # Check if response is SSE
  363. if "text/event-stream" in r.headers.get("Content-Type", ""):
  364. streaming = True
  365. return StreamingResponse(
  366. r.content,
  367. status_code=r.status,
  368. headers=dict(r.headers),
  369. background=BackgroundTask(
  370. cleanup_response, response=r, session=session
  371. ),
  372. )
  373. else:
  374. try:
  375. response = await r.json()
  376. except Exception as e:
  377. log.error(e)
  378. response = await r.text()
  379. r.raise_for_status()
  380. return response
  381. except Exception as e:
  382. log.exception(e)
  383. error_detail = "Open WebUI: Server Connection Error"
  384. if isinstance(response, dict):
  385. if "error" in response:
  386. error_detail = f"{response['error']['message'] if 'message' in response['error'] else response['error']}"
  387. elif isinstance(response, str):
  388. error_detail = response
  389. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  390. finally:
  391. if not streaming and session:
  392. if r:
  393. r.close()
  394. await session.close()
  395. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  396. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  397. idx = 0
  398. body = await request.body()
  399. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  400. key = app.state.config.OPENAI_API_KEYS[idx]
  401. target_url = f"{url}/{path}"
  402. headers = {}
  403. headers["Authorization"] = f"Bearer {key}"
  404. headers["Content-Type"] = "application/json"
  405. r = None
  406. session = None
  407. streaming = False
  408. try:
  409. session = aiohttp.ClientSession(trust_env=True)
  410. r = await session.request(
  411. method=request.method,
  412. url=target_url,
  413. data=body,
  414. headers=headers,
  415. )
  416. r.raise_for_status()
  417. # Check if response is SSE
  418. if "text/event-stream" in r.headers.get("Content-Type", ""):
  419. streaming = True
  420. return StreamingResponse(
  421. r.content,
  422. status_code=r.status,
  423. headers=dict(r.headers),
  424. background=BackgroundTask(
  425. cleanup_response, response=r, session=session
  426. ),
  427. )
  428. else:
  429. response_data = await r.json()
  430. return response_data
  431. except Exception as e:
  432. log.exception(e)
  433. error_detail = "Open WebUI: Server Connection Error"
  434. if r is not None:
  435. try:
  436. res = await r.json()
  437. print(res)
  438. if "error" in res:
  439. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  440. except Exception:
  441. error_detail = f"External: {e}"
  442. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  443. finally:
  444. if not streaming and session:
  445. if r:
  446. r.close()
  447. await session.close()