main.py 24 KB

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