main.py 24 KB

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