main.py 17 KB

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