openai.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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. from aiocache import cached
  9. import requests
  10. from fastapi import Depends, FastAPI, HTTPException, Request, APIRouter
  11. from fastapi.middleware.cors import CORSMiddleware
  12. from fastapi.responses import FileResponse, StreamingResponse
  13. from pydantic import BaseModel
  14. from starlette.background import BackgroundTask
  15. from open_webui.models.models import Models
  16. from open_webui.config import (
  17. CACHE_DIR,
  18. )
  19. from open_webui.env import (
  20. AIOHTTP_CLIENT_TIMEOUT,
  21. AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST,
  22. ENABLE_FORWARD_USER_INFO_HEADERS,
  23. BYPASS_MODEL_ACCESS_CONTROL,
  24. )
  25. from open_webui.constants import ERROR_MESSAGES
  26. from open_webui.env import ENV, SRC_LOG_LEVELS
  27. from open_webui.utils.payload import (
  28. apply_model_params_to_body_openai,
  29. apply_model_system_prompt_to_body,
  30. )
  31. from open_webui.utils.auth import get_admin_user, get_verified_user
  32. from open_webui.utils.access_control import has_access
  33. log = logging.getLogger(__name__)
  34. log.setLevel(SRC_LOG_LEVELS["OPENAI"])
  35. ##########################################
  36. #
  37. # Utility functions
  38. #
  39. ##########################################
  40. async def send_get_request(url, key=None):
  41. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST)
  42. try:
  43. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  44. async with session.get(
  45. url, headers={**({"Authorization": f"Bearer {key}"} if key else {})}
  46. ) as response:
  47. return await response.json()
  48. except Exception as e:
  49. # Handle connection error here
  50. log.error(f"Connection error: {e}")
  51. return None
  52. async def cleanup_response(
  53. response: Optional[aiohttp.ClientResponse],
  54. session: Optional[aiohttp.ClientSession],
  55. ):
  56. if response:
  57. response.close()
  58. if session:
  59. await session.close()
  60. def openai_o1_o3_handler(payload):
  61. """
  62. Handle o1, o3 specific parameters
  63. """
  64. if "max_tokens" in payload:
  65. # Remove "max_tokens" from the payload
  66. payload["max_completion_tokens"] = payload["max_tokens"]
  67. del payload["max_tokens"]
  68. # Fix: o1 and o3 do not support the "system" role directly.
  69. # For older models like "o1-mini" or "o1-preview", use role "user".
  70. # For newer o1/o3 models, replace "system" with "developer".
  71. if payload["messages"][0]["role"] == "system":
  72. model_lower = payload["model"].lower()
  73. if model_lower.startswith("o1-mini") or model_lower.startswith("o1-preview"):
  74. payload["messages"][0]["role"] = "user"
  75. else:
  76. payload["messages"][0]["role"] = "developer"
  77. return payload
  78. ##########################################
  79. #
  80. # API routes
  81. #
  82. ##########################################
  83. router = APIRouter()
  84. @router.get("/config")
  85. async def get_config(request: Request, user=Depends(get_admin_user)):
  86. return {
  87. "ENABLE_OPENAI_API": request.app.state.config.ENABLE_OPENAI_API,
  88. "OPENAI_API_BASE_URLS": request.app.state.config.OPENAI_API_BASE_URLS,
  89. "OPENAI_API_KEYS": request.app.state.config.OPENAI_API_KEYS,
  90. "OPENAI_API_CONFIGS": request.app.state.config.OPENAI_API_CONFIGS,
  91. }
  92. class OpenAIConfigForm(BaseModel):
  93. ENABLE_OPENAI_API: Optional[bool] = None
  94. OPENAI_API_BASE_URLS: list[str]
  95. OPENAI_API_KEYS: list[str]
  96. OPENAI_API_CONFIGS: dict
  97. @router.post("/config/update")
  98. async def update_config(
  99. request: Request, form_data: OpenAIConfigForm, user=Depends(get_admin_user)
  100. ):
  101. request.app.state.config.ENABLE_OPENAI_API = form_data.ENABLE_OPENAI_API
  102. request.app.state.config.OPENAI_API_BASE_URLS = form_data.OPENAI_API_BASE_URLS
  103. request.app.state.config.OPENAI_API_KEYS = form_data.OPENAI_API_KEYS
  104. # Check if API KEYS length is same than API URLS length
  105. if len(request.app.state.config.OPENAI_API_KEYS) != len(
  106. request.app.state.config.OPENAI_API_BASE_URLS
  107. ):
  108. if len(request.app.state.config.OPENAI_API_KEYS) > len(
  109. request.app.state.config.OPENAI_API_BASE_URLS
  110. ):
  111. request.app.state.config.OPENAI_API_KEYS = (
  112. request.app.state.config.OPENAI_API_KEYS[
  113. : len(request.app.state.config.OPENAI_API_BASE_URLS)
  114. ]
  115. )
  116. else:
  117. request.app.state.config.OPENAI_API_KEYS += [""] * (
  118. len(request.app.state.config.OPENAI_API_BASE_URLS)
  119. - len(request.app.state.config.OPENAI_API_KEYS)
  120. )
  121. request.app.state.config.OPENAI_API_CONFIGS = form_data.OPENAI_API_CONFIGS
  122. # Remove the API configs that are not in the API URLS
  123. keys = list(map(str, range(len(request.app.state.config.OPENAI_API_BASE_URLS))))
  124. request.app.state.config.OPENAI_API_CONFIGS = {
  125. key: value
  126. for key, value in request.app.state.config.OPENAI_API_CONFIGS.items()
  127. if key in keys
  128. }
  129. return {
  130. "ENABLE_OPENAI_API": request.app.state.config.ENABLE_OPENAI_API,
  131. "OPENAI_API_BASE_URLS": request.app.state.config.OPENAI_API_BASE_URLS,
  132. "OPENAI_API_KEYS": request.app.state.config.OPENAI_API_KEYS,
  133. "OPENAI_API_CONFIGS": request.app.state.config.OPENAI_API_CONFIGS,
  134. }
  135. @router.post("/audio/speech")
  136. async def speech(request: Request, user=Depends(get_verified_user)):
  137. idx = None
  138. try:
  139. idx = request.app.state.config.OPENAI_API_BASE_URLS.index(
  140. "https://api.openai.com/v1"
  141. )
  142. body = await request.body()
  143. name = hashlib.sha256(body).hexdigest()
  144. SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
  145. SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
  146. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  147. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  148. # Check if the file already exists in the cache
  149. if file_path.is_file():
  150. return FileResponse(file_path)
  151. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  152. r = None
  153. try:
  154. r = requests.post(
  155. url=f"{url}/audio/speech",
  156. data=body,
  157. headers={
  158. "Content-Type": "application/json",
  159. "Authorization": f"Bearer {request.app.state.config.OPENAI_API_KEYS[idx]}",
  160. **(
  161. {
  162. "HTTP-Referer": "https://openwebui.com/",
  163. "X-Title": "Open WebUI",
  164. }
  165. if "openrouter.ai" in url
  166. else {}
  167. ),
  168. **(
  169. {
  170. "X-OpenWebUI-User-Name": user.name,
  171. "X-OpenWebUI-User-Id": user.id,
  172. "X-OpenWebUI-User-Email": user.email,
  173. "X-OpenWebUI-User-Role": user.role,
  174. }
  175. if ENABLE_FORWARD_USER_INFO_HEADERS
  176. else {}
  177. ),
  178. },
  179. stream=True,
  180. )
  181. r.raise_for_status()
  182. # Save the streaming content to a file
  183. with open(file_path, "wb") as f:
  184. for chunk in r.iter_content(chunk_size=8192):
  185. f.write(chunk)
  186. with open(file_body_path, "w") as f:
  187. json.dump(json.loads(body.decode("utf-8")), f)
  188. # Return the saved file
  189. return FileResponse(file_path)
  190. except Exception as e:
  191. log.exception(e)
  192. detail = None
  193. if r is not None:
  194. try:
  195. res = r.json()
  196. if "error" in res:
  197. detail = f"External: {res['error']}"
  198. except Exception:
  199. detail = f"External: {e}"
  200. raise HTTPException(
  201. status_code=r.status_code if r else 500,
  202. detail=detail if detail else "Open WebUI: Server Connection Error",
  203. )
  204. except ValueError:
  205. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.OPENAI_NOT_FOUND)
  206. async def get_all_models_responses(request: Request) -> list:
  207. if not request.app.state.config.ENABLE_OPENAI_API:
  208. return []
  209. # Check if API KEYS length is same than API URLS length
  210. num_urls = len(request.app.state.config.OPENAI_API_BASE_URLS)
  211. num_keys = len(request.app.state.config.OPENAI_API_KEYS)
  212. if num_keys != num_urls:
  213. # if there are more keys than urls, remove the extra keys
  214. if num_keys > num_urls:
  215. new_keys = request.app.state.config.OPENAI_API_KEYS[:num_urls]
  216. request.app.state.config.OPENAI_API_KEYS = new_keys
  217. # if there are more urls than keys, add empty keys
  218. else:
  219. request.app.state.config.OPENAI_API_KEYS += [""] * (num_urls - num_keys)
  220. request_tasks = []
  221. for idx, url in enumerate(request.app.state.config.OPENAI_API_BASE_URLS):
  222. if (str(idx) not in request.app.state.config.OPENAI_API_CONFIGS) and (
  223. url not in request.app.state.config.OPENAI_API_CONFIGS # Legacy support
  224. ):
  225. request_tasks.append(
  226. send_get_request(
  227. f"{url}/models", request.app.state.config.OPENAI_API_KEYS[idx]
  228. )
  229. )
  230. else:
  231. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  232. str(idx),
  233. request.app.state.config.OPENAI_API_CONFIGS.get(
  234. url, {}
  235. ), # Legacy support
  236. )
  237. enable = api_config.get("enable", True)
  238. model_ids = api_config.get("model_ids", [])
  239. if enable:
  240. if len(model_ids) == 0:
  241. request_tasks.append(
  242. send_get_request(
  243. f"{url}/models",
  244. request.app.state.config.OPENAI_API_KEYS[idx],
  245. )
  246. )
  247. else:
  248. model_list = {
  249. "object": "list",
  250. "data": [
  251. {
  252. "id": model_id,
  253. "name": model_id,
  254. "owned_by": "openai",
  255. "openai": {"id": model_id},
  256. "urlIdx": idx,
  257. }
  258. for model_id in model_ids
  259. ],
  260. }
  261. request_tasks.append(
  262. asyncio.ensure_future(asyncio.sleep(0, model_list))
  263. )
  264. else:
  265. request_tasks.append(asyncio.ensure_future(asyncio.sleep(0, None)))
  266. responses = await asyncio.gather(*request_tasks)
  267. for idx, response in enumerate(responses):
  268. if response:
  269. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  270. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  271. str(idx),
  272. request.app.state.config.OPENAI_API_CONFIGS.get(
  273. url, {}
  274. ), # Legacy support
  275. )
  276. prefix_id = api_config.get("prefix_id", None)
  277. if prefix_id:
  278. for model in (
  279. response if isinstance(response, list) else response.get("data", [])
  280. ):
  281. model["id"] = f"{prefix_id}.{model['id']}"
  282. log.debug(f"get_all_models:responses() {responses}")
  283. return responses
  284. async def get_filtered_models(models, user):
  285. # Filter models based on user access control
  286. filtered_models = []
  287. for model in models.get("data", []):
  288. model_info = Models.get_model_by_id(model["id"])
  289. if model_info:
  290. if user.id == model_info.user_id or has_access(
  291. user.id, type="read", access_control=model_info.access_control
  292. ):
  293. filtered_models.append(model)
  294. return filtered_models
  295. @cached(ttl=3)
  296. async def get_all_models(request: Request) -> dict[str, list]:
  297. log.info("get_all_models()")
  298. if not request.app.state.config.ENABLE_OPENAI_API:
  299. return {"data": []}
  300. responses = await get_all_models_responses(request)
  301. def extract_data(response):
  302. if response and "data" in response:
  303. return response["data"]
  304. if isinstance(response, list):
  305. return response
  306. return None
  307. def merge_models_lists(model_lists):
  308. log.debug(f"merge_models_lists {model_lists}")
  309. merged_list = []
  310. for idx, models in enumerate(model_lists):
  311. if models is not None and "error" not in models:
  312. merged_list.extend(
  313. [
  314. {
  315. **model,
  316. "name": model.get("name", model["id"]),
  317. "owned_by": "openai",
  318. "openai": model,
  319. "urlIdx": idx,
  320. }
  321. for model in models
  322. if "api.openai.com"
  323. not in request.app.state.config.OPENAI_API_BASE_URLS[idx]
  324. or not any(
  325. name in model["id"]
  326. for name in [
  327. "babbage",
  328. "dall-e",
  329. "davinci",
  330. "embedding",
  331. "tts",
  332. "whisper",
  333. ]
  334. )
  335. ]
  336. )
  337. return merged_list
  338. models = {"data": merge_models_lists(map(extract_data, responses))}
  339. log.debug(f"models: {models}")
  340. request.app.state.OPENAI_MODELS = {model["id"]: model for model in models["data"]}
  341. return models
  342. @router.get("/models")
  343. @router.get("/models/{url_idx}")
  344. async def get_models(
  345. request: Request, url_idx: Optional[int] = None, user=Depends(get_verified_user)
  346. ):
  347. models = {
  348. "data": [],
  349. }
  350. if url_idx is None:
  351. models = await get_all_models(request)
  352. else:
  353. url = request.app.state.config.OPENAI_API_BASE_URLS[url_idx]
  354. key = request.app.state.config.OPENAI_API_KEYS[url_idx]
  355. r = None
  356. async with aiohttp.ClientSession(
  357. timeout=aiohttp.ClientTimeout(
  358. total=AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST
  359. )
  360. ) as session:
  361. try:
  362. async with session.get(
  363. f"{url}/models",
  364. headers={
  365. "Authorization": f"Bearer {key}",
  366. "Content-Type": "application/json",
  367. **(
  368. {
  369. "X-OpenWebUI-User-Name": user.name,
  370. "X-OpenWebUI-User-Id": user.id,
  371. "X-OpenWebUI-User-Email": user.email,
  372. "X-OpenWebUI-User-Role": user.role,
  373. }
  374. if ENABLE_FORWARD_USER_INFO_HEADERS
  375. else {}
  376. ),
  377. },
  378. ) as r:
  379. if r.status != 200:
  380. # Extract response error details if available
  381. error_detail = f"HTTP Error: {r.status}"
  382. res = await r.json()
  383. if "error" in res:
  384. error_detail = f"External Error: {res['error']}"
  385. raise Exception(error_detail)
  386. response_data = await r.json()
  387. # Check if we're calling OpenAI API based on the URL
  388. if "api.openai.com" in url:
  389. # Filter models according to the specified conditions
  390. response_data["data"] = [
  391. model
  392. for model in response_data.get("data", [])
  393. if not any(
  394. name in model["id"]
  395. for name in [
  396. "babbage",
  397. "dall-e",
  398. "davinci",
  399. "embedding",
  400. "tts",
  401. "whisper",
  402. ]
  403. )
  404. ]
  405. models = response_data
  406. except aiohttp.ClientError as e:
  407. # ClientError covers all aiohttp requests issues
  408. log.exception(f"Client error: {str(e)}")
  409. raise HTTPException(
  410. status_code=500, detail="Open WebUI: Server Connection Error"
  411. )
  412. except Exception as e:
  413. log.exception(f"Unexpected error: {e}")
  414. error_detail = f"Unexpected error: {str(e)}"
  415. raise HTTPException(status_code=500, detail=error_detail)
  416. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  417. models["data"] = await get_filtered_models(models, user)
  418. return models
  419. class ConnectionVerificationForm(BaseModel):
  420. url: str
  421. key: str
  422. @router.post("/verify")
  423. async def verify_connection(
  424. form_data: ConnectionVerificationForm, user=Depends(get_admin_user)
  425. ):
  426. url = form_data.url
  427. key = form_data.key
  428. async with aiohttp.ClientSession(
  429. timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST)
  430. ) as session:
  431. try:
  432. async with session.get(
  433. f"{url}/models",
  434. headers={
  435. "Authorization": f"Bearer {key}",
  436. "Content-Type": "application/json",
  437. },
  438. ) as r:
  439. if r.status != 200:
  440. # Extract response error details if available
  441. error_detail = f"HTTP Error: {r.status}"
  442. res = await r.json()
  443. if "error" in res:
  444. error_detail = f"External Error: {res['error']}"
  445. raise Exception(error_detail)
  446. response_data = await r.json()
  447. return response_data
  448. except aiohttp.ClientError as e:
  449. # ClientError covers all aiohttp requests issues
  450. log.exception(f"Client error: {str(e)}")
  451. raise HTTPException(
  452. status_code=500, detail="Open WebUI: Server Connection Error"
  453. )
  454. except Exception as e:
  455. log.exception(f"Unexpected error: {e}")
  456. error_detail = f"Unexpected error: {str(e)}"
  457. raise HTTPException(status_code=500, detail=error_detail)
  458. @router.post("/chat/completions")
  459. async def generate_chat_completion(
  460. request: Request,
  461. form_data: dict,
  462. user=Depends(get_verified_user),
  463. bypass_filter: Optional[bool] = False,
  464. ):
  465. if BYPASS_MODEL_ACCESS_CONTROL:
  466. bypass_filter = True
  467. idx = 0
  468. payload = {**form_data}
  469. metadata = payload.pop("metadata", None)
  470. model_id = form_data.get("model")
  471. model_info = Models.get_model_by_id(model_id)
  472. # Check model info and override the payload
  473. if model_info:
  474. if model_info.base_model_id:
  475. payload["model"] = model_info.base_model_id
  476. model_id = model_info.base_model_id
  477. params = model_info.params.model_dump()
  478. payload = apply_model_params_to_body_openai(params, payload)
  479. payload = apply_model_system_prompt_to_body(params, payload, metadata, user)
  480. # Check if user has access to the model
  481. if not bypass_filter and user.role == "user":
  482. if not (
  483. user.id == model_info.user_id
  484. or has_access(
  485. user.id, type="read", access_control=model_info.access_control
  486. )
  487. ):
  488. raise HTTPException(
  489. status_code=403,
  490. detail="Model not found",
  491. )
  492. elif not bypass_filter:
  493. if user.role != "admin":
  494. raise HTTPException(
  495. status_code=403,
  496. detail="Model not found",
  497. )
  498. await get_all_models(request)
  499. model = request.app.state.OPENAI_MODELS.get(model_id)
  500. if model:
  501. idx = model["urlIdx"]
  502. else:
  503. raise HTTPException(
  504. status_code=404,
  505. detail="Model not found",
  506. )
  507. # Get the API config for the model
  508. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  509. str(idx),
  510. request.app.state.config.OPENAI_API_CONFIGS.get(
  511. request.app.state.config.OPENAI_API_BASE_URLS[idx], {}
  512. ), # Legacy support
  513. )
  514. prefix_id = api_config.get("prefix_id", None)
  515. if prefix_id:
  516. payload["model"] = payload["model"].replace(f"{prefix_id}.", "")
  517. # Add user info to the payload if the model is a pipeline
  518. if "pipeline" in model and model.get("pipeline"):
  519. payload["user"] = {
  520. "name": user.name,
  521. "id": user.id,
  522. "email": user.email,
  523. "role": user.role,
  524. }
  525. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  526. key = request.app.state.config.OPENAI_API_KEYS[idx]
  527. # Fix: o1,o3 does not support the "max_tokens" parameter, Modify "max_tokens" to "max_completion_tokens"
  528. is_o1_o3 = payload["model"].lower().startswith(("o1", "o3-"))
  529. if is_o1_o3:
  530. payload = openai_o1_o3_handler(payload)
  531. elif "api.openai.com" not in url:
  532. # Remove "max_completion_tokens" from the payload for backward compatibility
  533. if "max_completion_tokens" in payload:
  534. payload["max_tokens"] = payload["max_completion_tokens"]
  535. del payload["max_completion_tokens"]
  536. if "max_tokens" in payload and "max_completion_tokens" in payload:
  537. del payload["max_tokens"]
  538. # Convert the modified body back to JSON
  539. payload = json.dumps(payload)
  540. r = None
  541. session = None
  542. streaming = False
  543. response = None
  544. try:
  545. session = aiohttp.ClientSession(
  546. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  547. )
  548. r = await session.request(
  549. method="POST",
  550. url=f"{url}/chat/completions",
  551. data=payload,
  552. headers={
  553. "Authorization": f"Bearer {key}",
  554. "Content-Type": "application/json",
  555. **(
  556. {
  557. "HTTP-Referer": "https://openwebui.com/",
  558. "X-Title": "Open WebUI",
  559. }
  560. if "openrouter.ai" in url
  561. else {}
  562. ),
  563. **(
  564. {
  565. "X-OpenWebUI-User-Name": user.name,
  566. "X-OpenWebUI-User-Id": user.id,
  567. "X-OpenWebUI-User-Email": user.email,
  568. "X-OpenWebUI-User-Role": user.role,
  569. }
  570. if ENABLE_FORWARD_USER_INFO_HEADERS
  571. else {}
  572. ),
  573. },
  574. )
  575. # Check if response is SSE
  576. if "text/event-stream" in r.headers.get("Content-Type", ""):
  577. streaming = True
  578. return StreamingResponse(
  579. r.content,
  580. status_code=r.status,
  581. headers=dict(r.headers),
  582. background=BackgroundTask(
  583. cleanup_response, response=r, session=session
  584. ),
  585. )
  586. else:
  587. try:
  588. response = await r.json()
  589. except Exception as e:
  590. log.error(e)
  591. response = await r.text()
  592. r.raise_for_status()
  593. return response
  594. except Exception as e:
  595. log.exception(e)
  596. detail = None
  597. if isinstance(response, dict):
  598. if "error" in response:
  599. detail = f"{response['error']['message'] if 'message' in response['error'] else response['error']}"
  600. elif isinstance(response, str):
  601. detail = response
  602. raise HTTPException(
  603. status_code=r.status if r else 500,
  604. detail=detail if detail else "Open WebUI: Server Connection Error",
  605. )
  606. finally:
  607. if not streaming and session:
  608. if r:
  609. r.close()
  610. await session.close()
  611. @router.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  612. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  613. """
  614. Deprecated: proxy all requests to OpenAI API
  615. """
  616. body = await request.body()
  617. idx = 0
  618. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  619. key = request.app.state.config.OPENAI_API_KEYS[idx]
  620. r = None
  621. session = None
  622. streaming = False
  623. try:
  624. session = aiohttp.ClientSession(trust_env=True)
  625. r = await session.request(
  626. method=request.method,
  627. url=f"{url}/{path}",
  628. data=body,
  629. headers={
  630. "Authorization": f"Bearer {key}",
  631. "Content-Type": "application/json",
  632. **(
  633. {
  634. "X-OpenWebUI-User-Name": user.name,
  635. "X-OpenWebUI-User-Id": user.id,
  636. "X-OpenWebUI-User-Email": user.email,
  637. "X-OpenWebUI-User-Role": user.role,
  638. }
  639. if ENABLE_FORWARD_USER_INFO_HEADERS
  640. else {}
  641. ),
  642. },
  643. )
  644. r.raise_for_status()
  645. # Check if response is SSE
  646. if "text/event-stream" in r.headers.get("Content-Type", ""):
  647. streaming = True
  648. return StreamingResponse(
  649. r.content,
  650. status_code=r.status,
  651. headers=dict(r.headers),
  652. background=BackgroundTask(
  653. cleanup_response, response=r, session=session
  654. ),
  655. )
  656. else:
  657. response_data = await r.json()
  658. return response_data
  659. except Exception as e:
  660. log.exception(e)
  661. detail = None
  662. if r is not None:
  663. try:
  664. res = await r.json()
  665. print(res)
  666. if "error" in res:
  667. detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  668. except Exception:
  669. detail = f"External: {e}"
  670. raise HTTPException(
  671. status_code=r.status if r else 500,
  672. detail=detail if detail else "Open WebUI: Server Connection Error",
  673. )
  674. finally:
  675. if not streaming and session:
  676. if r:
  677. r.close()
  678. await session.close()