main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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 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. # Change max_completion_tokens to max_tokens (Backward compatible)
  321. if "api.openai.com" not in url and not payload["model"].lower().startswith("o1-"):
  322. if "max_completion_tokens" in payload:
  323. # Remove "max_completion_tokens" from the payload
  324. payload["max_tokens"] = payload["max_completion_tokens"]
  325. del payload["max_completion_tokens"]
  326. else:
  327. if payload["model"].lower().startswith("o1-") and "max_tokens" in payload:
  328. payload["max_completion_tokens"] = payload["max_tokens"]
  329. del payload["max_tokens"]
  330. if "max_tokens" in payload and "max_completion_tokens" in payload:
  331. del payload["max_tokens"]
  332. # Convert the modified body back to JSON
  333. payload = json.dumps(payload)
  334. log.debug(payload)
  335. headers = {}
  336. headers["Authorization"] = f"Bearer {key}"
  337. headers["Content-Type"] = "application/json"
  338. if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
  339. headers["HTTP-Referer"] = "https://openwebui.com/"
  340. headers["X-Title"] = "Open WebUI"
  341. r = None
  342. session = None
  343. streaming = False
  344. response = None
  345. try:
  346. session = aiohttp.ClientSession(
  347. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  348. )
  349. r = await session.request(
  350. method="POST",
  351. url=f"{url}/chat/completions",
  352. data=payload,
  353. headers=headers,
  354. )
  355. # Check if response is SSE
  356. if "text/event-stream" in r.headers.get("Content-Type", ""):
  357. streaming = True
  358. return StreamingResponse(
  359. r.content,
  360. status_code=r.status,
  361. headers=dict(r.headers),
  362. background=BackgroundTask(
  363. cleanup_response, response=r, session=session
  364. ),
  365. )
  366. else:
  367. try:
  368. response = await r.json()
  369. except Exception as e:
  370. log.error(e)
  371. response = await r.text()
  372. r.raise_for_status()
  373. return response
  374. except Exception as e:
  375. log.exception(e)
  376. error_detail = "Open WebUI: Server Connection Error"
  377. if isinstance(response, dict):
  378. if "error" in response:
  379. error_detail = f"{response['error']['message'] if 'message' in response['error'] else response['error']}"
  380. elif isinstance(response, str):
  381. error_detail = response
  382. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  383. finally:
  384. if not streaming and session:
  385. if r:
  386. r.close()
  387. await session.close()
  388. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  389. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  390. idx = 0
  391. body = await request.body()
  392. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  393. key = app.state.config.OPENAI_API_KEYS[idx]
  394. target_url = f"{url}/{path}"
  395. headers = {}
  396. headers["Authorization"] = f"Bearer {key}"
  397. headers["Content-Type"] = "application/json"
  398. r = None
  399. session = None
  400. streaming = False
  401. try:
  402. session = aiohttp.ClientSession(trust_env=True)
  403. r = await session.request(
  404. method=request.method,
  405. url=target_url,
  406. data=body,
  407. headers=headers,
  408. )
  409. r.raise_for_status()
  410. # Check if response is SSE
  411. if "text/event-stream" in r.headers.get("Content-Type", ""):
  412. streaming = True
  413. return StreamingResponse(
  414. r.content,
  415. status_code=r.status,
  416. headers=dict(r.headers),
  417. background=BackgroundTask(
  418. cleanup_response, response=r, session=session
  419. ),
  420. )
  421. else:
  422. response_data = await r.json()
  423. return response_data
  424. except Exception as e:
  425. log.exception(e)
  426. error_detail = "Open WebUI: Server Connection Error"
  427. if r is not None:
  428. try:
  429. res = await r.json()
  430. print(res)
  431. if "error" in res:
  432. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  433. except Exception:
  434. error_detail = f"External: {e}"
  435. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  436. finally:
  437. if not streaming and session:
  438. if r:
  439. r.close()
  440. await session.close()