main.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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 (
  262. response if isinstance(response, list) else response.get("data", [])
  263. ):
  264. model["id"] = f"{prefix_id}.{model['id']}"
  265. log.debug(f"get_all_models:responses() {responses}")
  266. return responses
  267. async def get_all_models() -> dict[str, list]:
  268. log.info("get_all_models()")
  269. if not app.state.config.ENABLE_OPENAI_API:
  270. return {"data": []}
  271. responses = await get_all_models_responses()
  272. def extract_data(response):
  273. if response and "data" in response:
  274. return response["data"]
  275. if isinstance(response, list):
  276. return response
  277. return None
  278. models = {"data": merge_models_lists(map(extract_data, responses))}
  279. log.debug(f"models: {models}")
  280. return models
  281. @app.get("/models")
  282. @app.get("/models/{url_idx}")
  283. async def get_models(url_idx: Optional[int] = None, user=Depends(get_verified_user)):
  284. models = {
  285. "data": [],
  286. }
  287. if url_idx is None:
  288. models = await get_all_models()
  289. else:
  290. url = app.state.config.OPENAI_API_BASE_URLS[url_idx]
  291. key = app.state.config.OPENAI_API_KEYS[url_idx]
  292. headers = {}
  293. headers["Authorization"] = f"Bearer {key}"
  294. headers["Content-Type"] = "application/json"
  295. if ENABLE_FORWARD_USER_INFO_HEADERS:
  296. headers["X-OpenWebUI-User-Name"] = user.name
  297. headers["X-OpenWebUI-User-Id"] = user.id
  298. headers["X-OpenWebUI-User-Email"] = user.email
  299. headers["X-OpenWebUI-User-Role"] = user.role
  300. r = None
  301. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST)
  302. async with aiohttp.ClientSession(timeout=timeout) as session:
  303. try:
  304. async with session.get(f"{url}/models", headers=headers) as r:
  305. if r.status != 200:
  306. # Extract response error details if available
  307. error_detail = f"HTTP Error: {r.status}"
  308. res = await r.json()
  309. if "error" in res:
  310. error_detail = f"External Error: {res['error']}"
  311. raise Exception(error_detail)
  312. response_data = await r.json()
  313. # Check if we're calling OpenAI API based on the URL
  314. if "api.openai.com" in url:
  315. # Filter models according to the specified conditions
  316. response_data["data"] = [
  317. model
  318. for model in response_data.get("data", [])
  319. if not any(
  320. name in model["id"]
  321. for name in [
  322. "babbage",
  323. "dall-e",
  324. "davinci",
  325. "embedding",
  326. "tts",
  327. "whisper",
  328. ]
  329. )
  330. ]
  331. models = response_data
  332. except aiohttp.ClientError as e:
  333. # ClientError covers all aiohttp requests issues
  334. log.exception(f"Client error: {str(e)}")
  335. # Handle aiohttp-specific connection issues, timeout etc.
  336. raise HTTPException(
  337. status_code=500, detail="Open WebUI: Server Connection Error"
  338. )
  339. except Exception as e:
  340. log.exception(f"Unexpected error: {e}")
  341. # Generic error handler in case parsing JSON or other steps fail
  342. error_detail = f"Unexpected error: {str(e)}"
  343. raise HTTPException(status_code=500, detail=error_detail)
  344. if user.role == "user":
  345. # Filter models based on user access control
  346. filtered_models = []
  347. for model in models.get("data", []):
  348. model_info = Models.get_model_by_id(model["id"])
  349. if model_info:
  350. if user.id == model_info.user_id or has_access(
  351. user.id, type="read", access_control=model_info.access_control
  352. ):
  353. filtered_models.append(model)
  354. models["data"] = filtered_models
  355. return models
  356. class ConnectionVerificationForm(BaseModel):
  357. url: str
  358. key: str
  359. @app.post("/verify")
  360. async def verify_connection(
  361. form_data: ConnectionVerificationForm, user=Depends(get_admin_user)
  362. ):
  363. url = form_data.url
  364. key = form_data.key
  365. headers = {}
  366. headers["Authorization"] = f"Bearer {key}"
  367. headers["Content-Type"] = "application/json"
  368. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST)
  369. async with aiohttp.ClientSession(timeout=timeout) as session:
  370. try:
  371. async with session.get(f"{url}/models", headers=headers) as r:
  372. if r.status != 200:
  373. # Extract response error details if available
  374. error_detail = f"HTTP Error: {r.status}"
  375. res = await r.json()
  376. if "error" in res:
  377. error_detail = f"External Error: {res['error']}"
  378. raise Exception(error_detail)
  379. response_data = await r.json()
  380. return response_data
  381. except aiohttp.ClientError as e:
  382. # ClientError covers all aiohttp requests issues
  383. log.exception(f"Client error: {str(e)}")
  384. # Handle aiohttp-specific connection issues, timeout etc.
  385. raise HTTPException(
  386. status_code=500, detail="Open WebUI: Server Connection Error"
  387. )
  388. except Exception as e:
  389. log.exception(f"Unexpected error: {e}")
  390. # Generic error handler in case parsing JSON or other steps fail
  391. error_detail = f"Unexpected error: {str(e)}"
  392. raise HTTPException(status_code=500, detail=error_detail)
  393. @app.post("/chat/completions")
  394. async def generate_chat_completion(
  395. form_data: dict,
  396. user=Depends(get_verified_user),
  397. bypass_filter: Optional[bool] = False,
  398. ):
  399. idx = 0
  400. payload = {**form_data}
  401. if "metadata" in payload:
  402. del payload["metadata"]
  403. model_id = form_data.get("model")
  404. model_info = Models.get_model_by_id(model_id)
  405. # Check model info and override the payload
  406. if model_info:
  407. if model_info.base_model_id:
  408. payload["model"] = model_info.base_model_id
  409. params = model_info.params.model_dump()
  410. payload = apply_model_params_to_body_openai(params, payload)
  411. payload = apply_model_system_prompt_to_body(params, payload, user)
  412. # Check if user has access to the model
  413. if not bypass_filter and user.role == "user":
  414. if not (
  415. user.id == model_info.user_id
  416. or has_access(
  417. user.id, type="read", access_control=model_info.access_control
  418. )
  419. ):
  420. raise HTTPException(
  421. status_code=403,
  422. detail="Model not found",
  423. )
  424. elif not bypass_filter:
  425. if user.role != "admin":
  426. raise HTTPException(
  427. status_code=403,
  428. detail="Model not found",
  429. )
  430. # Attemp to get urlIdx from the model
  431. models = await get_all_models()
  432. # Find the model from the list
  433. model = next(
  434. (model for model in models["data"] if model["id"] == payload.get("model")),
  435. None,
  436. )
  437. if model:
  438. idx = model["urlIdx"]
  439. else:
  440. raise HTTPException(
  441. status_code=404,
  442. detail="Model not found",
  443. )
  444. # Get the API config for the model
  445. api_config = app.state.config.OPENAI_API_CONFIGS.get(
  446. app.state.config.OPENAI_API_BASE_URLS[idx], {}
  447. )
  448. prefix_id = api_config.get("prefix_id", None)
  449. if prefix_id:
  450. payload["model"] = payload["model"].replace(f"{prefix_id}.", "")
  451. # Add user info to the payload if the model is a pipeline
  452. if "pipeline" in model and model.get("pipeline"):
  453. payload["user"] = {
  454. "name": user.name,
  455. "id": user.id,
  456. "email": user.email,
  457. "role": user.role,
  458. }
  459. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  460. key = app.state.config.OPENAI_API_KEYS[idx]
  461. # Fix: O1 does not support the "max_tokens" parameter, Modify "max_tokens" to "max_completion_tokens"
  462. is_o1 = payload["model"].lower().startswith("o1-")
  463. # Change max_completion_tokens to max_tokens (Backward compatible)
  464. if "api.openai.com" not in url and not is_o1:
  465. if "max_completion_tokens" in payload:
  466. # Remove "max_completion_tokens" from the payload
  467. payload["max_tokens"] = payload["max_completion_tokens"]
  468. del payload["max_completion_tokens"]
  469. else:
  470. if is_o1 and "max_tokens" in payload:
  471. payload["max_completion_tokens"] = payload["max_tokens"]
  472. del payload["max_tokens"]
  473. if "max_tokens" in payload and "max_completion_tokens" in payload:
  474. del payload["max_tokens"]
  475. # Fix: O1 does not support the "system" parameter, Modify "system" to "user"
  476. if is_o1 and payload["messages"][0]["role"] == "system":
  477. payload["messages"][0]["role"] = "user"
  478. # Convert the modified body back to JSON
  479. payload = json.dumps(payload)
  480. log.debug(payload)
  481. headers = {}
  482. headers["Authorization"] = f"Bearer {key}"
  483. headers["Content-Type"] = "application/json"
  484. if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
  485. headers["HTTP-Referer"] = "https://openwebui.com/"
  486. headers["X-Title"] = "Open WebUI"
  487. if ENABLE_FORWARD_USER_INFO_HEADERS:
  488. headers["X-OpenWebUI-User-Name"] = user.name
  489. headers["X-OpenWebUI-User-Id"] = user.id
  490. headers["X-OpenWebUI-User-Email"] = user.email
  491. headers["X-OpenWebUI-User-Role"] = user.role
  492. r = None
  493. session = None
  494. streaming = False
  495. response = None
  496. try:
  497. session = aiohttp.ClientSession(
  498. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  499. )
  500. r = await session.request(
  501. method="POST",
  502. url=f"{url}/chat/completions",
  503. data=payload,
  504. headers=headers,
  505. )
  506. # Check if response is SSE
  507. if "text/event-stream" in r.headers.get("Content-Type", ""):
  508. streaming = True
  509. return StreamingResponse(
  510. r.content,
  511. status_code=r.status,
  512. headers=dict(r.headers),
  513. background=BackgroundTask(
  514. cleanup_response, response=r, session=session
  515. ),
  516. )
  517. else:
  518. try:
  519. response = await r.json()
  520. except Exception as e:
  521. log.error(e)
  522. response = await r.text()
  523. r.raise_for_status()
  524. return response
  525. except Exception as e:
  526. log.exception(e)
  527. error_detail = "Open WebUI: Server Connection Error"
  528. if isinstance(response, dict):
  529. if "error" in response:
  530. error_detail = f"{response['error']['message'] if 'message' in response['error'] else response['error']}"
  531. elif isinstance(response, str):
  532. error_detail = response
  533. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  534. finally:
  535. if not streaming and session:
  536. if r:
  537. r.close()
  538. await session.close()
  539. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  540. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  541. idx = 0
  542. body = await request.body()
  543. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  544. key = app.state.config.OPENAI_API_KEYS[idx]
  545. target_url = f"{url}/{path}"
  546. headers = {}
  547. headers["Authorization"] = f"Bearer {key}"
  548. headers["Content-Type"] = "application/json"
  549. if ENABLE_FORWARD_USER_INFO_HEADERS:
  550. headers["X-OpenWebUI-User-Name"] = user.name
  551. headers["X-OpenWebUI-User-Id"] = user.id
  552. headers["X-OpenWebUI-User-Email"] = user.email
  553. headers["X-OpenWebUI-User-Role"] = user.role
  554. r = None
  555. session = None
  556. streaming = False
  557. try:
  558. session = aiohttp.ClientSession(trust_env=True)
  559. r = await session.request(
  560. method=request.method,
  561. url=target_url,
  562. data=body,
  563. headers=headers,
  564. )
  565. r.raise_for_status()
  566. # Check if response is SSE
  567. if "text/event-stream" in r.headers.get("Content-Type", ""):
  568. streaming = True
  569. return StreamingResponse(
  570. r.content,
  571. status_code=r.status,
  572. headers=dict(r.headers),
  573. background=BackgroundTask(
  574. cleanup_response, response=r, session=session
  575. ),
  576. )
  577. else:
  578. response_data = await r.json()
  579. return response_data
  580. except Exception as e:
  581. log.exception(e)
  582. error_detail = "Open WebUI: Server Connection Error"
  583. if r is not None:
  584. try:
  585. res = await r.json()
  586. print(res)
  587. if "error" in res:
  588. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  589. except Exception:
  590. error_detail = f"External: {e}"
  591. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  592. finally:
  593. if not streaming and session:
  594. if r:
  595. r.close()
  596. await session.close()