openai.py 26 KB

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