main.py 24 KB

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