main.py 24 KB

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