main.py 23 KB

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