openai.py 24 KB

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