main.py 17 KB

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