main.py 18 KB

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