openai.py 28 KB

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