openai.py 26 KB

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