main.py 24 KB

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