main.py 24 KB

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