The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(support-allowed_openai_params-for-responses-api): Fixes https://github.com/BerriAI/litellm/issues/13559
Krrish Dholakiab83b1686c227
diff --git a/litellm/llms/azure/responses/transformation.py b/litellm/llms/azure/responses/transformation.pyindex e3d37c8a15a..a31ccacf345 100644--- a/litellm/llms/azure/responses/transformation.py+++ b/litellm/llms/azure/responses/transformation.py@@ -6,6 +6,7 @@ from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfifrom litellm.types.llms.openai import *from litellm.types.responses.main import *from litellm.types.router import GenericLiteLLMParams+from litellm.types.utils import LlmProvidersif TYPE_CHECKING:from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj@@ -16,6 +17,10 @@ else:class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig):+ @property+ def custom_llm_provider(self) -> LlmProviders:+ return LlmProviders.AZURE+def validate_environment(self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict:diff --git a/litellm/llms/base_llm/responses/transformation.py b/litellm/llms/base_llm/responses/transformation.pyindex e2f89da5e86..4da4f7652e0 100644--- a/litellm/llms/base_llm/responses/transformation.py+++ b/litellm/llms/base_llm/responses/transformation.py@@ -12,6 +12,7 @@ from litellm.types.llms.openai import ()from litellm.types.responses.main import *from litellm.types.router import GenericLiteLLMParams+from litellm.types.utils import LlmProvidersif TYPE_CHECKING:from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj@@ -29,6 +30,11 @@ class BaseResponsesAPIConfig(ABC):def __init__(self):pass+ @property+ @abstractmethod+ def custom_llm_provider(self) -> LlmProviders:+ pass+@classmethoddef get_config(cls):return {diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.pyindex 501941fdc59..40aae5a1cec 100644--- a/litellm/llms/openai/responses/transformation.py+++ b/litellm/llms/openai/responses/transformation.py@@ -13,6 +13,7 @@ from litellm.secret_managers.main import get_secret_strfrom litellm.types.llms.openai import *from litellm.types.responses.main import *from litellm.types.router import GenericLiteLLMParams+from litellm.types.utils import LlmProvidersfrom ..common_utils import OpenAIError@@ -25,6 +26,10 @@ else:class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):+ @property+ def custom_llm_provider(self) -> LlmProviders:+ return LlmProviders.OPENAI+def get_supported_openai_params(self, model: str) -> list:"""All OpenAI Responses API params are supported@@ -85,8 +90,10 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):)return final_request_params-- def _validate_input_param(self, input: Union[str, ResponseInputParam]) -> Union[str, ResponseInputParam]:++ def _validate_input_param(+ self, input: Union[str, ResponseInputParam]+ ) -> Union[str, ResponseInputParam]:"""Ensure all input fields if pydantic are converted to dict@@ -114,7 +121,9 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):"""No transform applied since outputs are in OpenAI spec already"""try:raw_response_json = raw_response.json()- raw_response_json["created_at"] = _safe_convert_created_field(raw_response_json["created_at"])+ raw_response_json["created_at"] = _safe_convert_created_field(+ raw_response_json["created_at"]+ )except Exception:raise OpenAIError(message=raw_response.text, status_code=raw_response.status_codediff --git a/litellm/responses/main.py b/litellm/responses/main.pyindex b5f18cf9e1a..ebd0ad4f42d 100644--- a/litellm/responses/main.py+++ b/litellm/responses/main.py@@ -1,7 +1,7 @@import asyncioimport contextvarsfrom functools import partial-from typing import Any, Coroutine, Dict, Iterable, List, Literal, Optional, Union+from typing import Any, Coroutine, Dict, Iterable, List, Literal, Optional, Union, castimport httpx@@ -89,6 +89,7 @@ def mock_responses_api_response(})+async def aresponses_api_with_mcp(input: Union[str, ResponseInputParam],model: str,@@ -122,7 +123,7 @@ async def aresponses_api_with_mcp() -> Union[ResponsesAPIResponse, BaseResponsesAPIStreamingIterator]:"""Async version of responses API with MCP integration.-+When MCP tools with server_url="litellm_proxy" are provided, this function will:1. Get available tools from the MCP server manager2. Insert the tools into the messages/input@@ -134,19 +135,25 @@ async def aresponses_api_with_mcp()# Parse MCP tools and separate from other tools- mcp_tools_with_litellm_proxy, other_tools = LiteLLM_Proxy_MCP_Handler._parse_mcp_tools(tools)-+ mcp_tools_with_litellm_proxy, other_tools = (+ LiteLLM_Proxy_MCP_Handler._parse_mcp_tools(tools)+ )+# Get available tools from MCP manager if we have MCP toolsopenai_tools = []mcp_tools_fetched = []if mcp_tools_with_litellm_proxy:user_api_key_auth = kwargs.get("user_api_key_auth")- mcp_tools_fetched = await LiteLLM_Proxy_MCP_Handler._get_mcp_tools_from_manager(user_api_key_auth)- openai_tools = LiteLLM_Proxy_MCP_Handler._transform_mcp_tools_to_openai(mcp_tools_fetched)-+ mcp_tools_fetched = await LiteLLM_Proxy_MCP_Handler._get_mcp_tools_from_manager(+ user_api_key_auth+ )+ openai_tools = LiteLLM_Proxy_MCP_Handler._transform_mcp_tools_to_openai(+ mcp_tools_fetched+ )+# Combine with other toolsall_tools = openai_tools + other_tools if (openai_tools or other_tools) else None-+# Prepare call parameters for reusecall_params = {"include": include,@@ -172,7 +179,7 @@ async def aresponses_api_with_mcp("custom_llm_provider": custom_llm_provider,**kwargs,}-+# Make initial response API call# TODO: if should auto-execute is True, then this first response should not be streamedresponse = await aresponses(@@ -180,45 +187,54 @@ async def aresponses_api_with_mcp(model=model,tools=all_tools,previous_response_id=previous_response_id,- **call_params+ **call_params,)-+# Check if we need to auto-execute tool calls (only for non-streaming responses)- if (mcp_tools_with_litellm_proxy and- isinstance(response, ResponsesAPIResponse) and- LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy)): # type: ignore- tool_calls = LiteLLM_Proxy_MCP_Handler._extract_tool_calls_from_response(response=response)-+ if (+ mcp_tools_with_litellm_proxy+ and isinstance(response, ResponsesAPIResponse)+ and LiteLLM_Proxy_MCP_Handler._should_auto_execute_tools(+ mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy+ )+ ): # type: ignore+ tool_calls = LiteLLM_Proxy_MCP_Handler._extract_tool_calls_from_response(+ response=response+ )+if tool_calls:- user_api_key_auth = kwargs.get("litellm_metadata", {}).get("user_api_key_auth")- tool_results = await LiteLLM_Proxy_MCP_Handler._execute_tool_calls(tool_calls=tool_calls, user_api_key_auth=user_api_key_auth)-+ user_api_key_auth = kwargs.get("litellm_metadata", {}).get(+ "user_api_key_auth"+ )+ tool_results = await LiteLLM_Proxy_MCP_Handler._execute_tool_calls(+ tool_calls=tool_calls, user_api_key_auth=user_api_key_auth+ )+if tool_results:follow_up_input = LiteLLM_Proxy_MCP_Handler._create_follow_up_input(- response=response,- tool_results=tool_results,- original_input=input+ response=response, tool_results=tool_results, original_input=input)-+final_response = await LiteLLM_Proxy_MCP_Handler._make_follow_up_call(follow_up_input=follow_up_input,model=model,all_tools=all_tools,response_id=response.id,- **call_params+ **call_params,)-+# Add custom output elements to the final responseif isinstance(final_response, ResponsesAPIResponse):- final_response = LiteLLM_Proxy_MCP_Handler._add_mcp_output_elements_to_response(- response=final_response,- mcp_tools_fetched=mcp_tools_fetched,- tool_results=tool_results+ final_response = (+ LiteLLM_Proxy_MCP_Handler._add_mcp_output_elements_to_response(+ response=final_response,+ mcp_tools_fetched=mcp_tools_fetched,+ tool_results=tool_results,+ ))return final_response-- return response+ return response@client@@ -319,7 +335,9 @@ async def aresponses()if response is None:- raise ValueError(f"Got an unexpected None response from the Responses API: {response}")+ raise ValueError(+ f"Got an unexpected None response from the Responses API: {response}"+ )return responseexcept Exception as e:@@ -363,6 +381,7 @@ def responses(extra_body: Optional[Dict[str, Any]] = None,timeout: Optional[Union[float, httpx.Timeout]] = None,# LiteLLM specific params,+ allowed_openai_params: Optional[List[str]] = None,custom_llm_provider: Optional[str] = None,**kwargs,):@@ -373,7 +392,7 @@ def responses(from litellm.responses.mcp.litellm_proxy_mcp_handler import (LiteLLM_Proxy_MCP_Handler,)-+local_vars = locals()try:litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore@@ -445,6 +464,7 @@ def responses(model=model,responses_api_provider_config=responses_api_provider_config,response_api_optional_params=response_api_optional_params,+ allowed_openai_params=allowed_openai_params,))diff --git a/litellm/responses/utils.py b/litellm/responses/utils.pyindex b50c84ad463..2b3d178c260 100644--- a/litellm/responses/utils.py+++ b/litellm/responses/utils.py@@ -1,5 +1,5 @@import base64-from typing import Any, Dict, Optional, Union, cast, get_type_hints, overload+from typing import Any, Dict, List, Optional, Union, cast, get_type_hints, overloadimport litellmfrom litellm._logging import verbose_logger@@ -16,11 +16,38 @@ from litellm.types.utils import SpecialEnums, Usageclass ResponsesAPIRequestUtils:"""Helper utils for constructing ResponseAPI requests"""+ @staticmethod+ def _check_valid_arg(+ supported_params: Optional[List[str]],+ non_default_params: Dict,+ drop_params: Optional[bool],+ custom_llm_provider: Optional[str],+ model: str,+ ):++ if supported_params is None:+ return+ unsupported_params = {}+ for k in non_default_params.keys():+ if k not in supported_params:+ unsupported_params[k] = non_default_params[k]+ if unsupported_params:+ if litellm.drop_params is True or (+ drop_params is not None and drop_params is True+ ):+ pass+ else:+ raise litellm.UnsupportedParamsError(+ status_code=500,+ message=f"{custom_llm_provider} does not support parameters: {unsupported_params}, for model={model}. To drop these, set `litellm.drop_params=True` or for proxy:\n\n`litellm_settings:\n drop_params: true`\n",+ )+@staticmethoddef get_optional_params_responses_api(model: str,responses_api_provider_config: BaseResponsesAPIConfig,response_api_optional_params: ResponsesAPIOptionalRequestParams,+ allowed_openai_params: Optional[List[str]] = None,) -> Dict:"""Get optional parameters for the responses API.@@ -33,25 +60,23 @@ class ResponsesAPIRequestUtils:Returns:A dictionary of supported parameters for the responses API"""- # Remove None values and internal parameters+ from litellm.utils import _apply_openai_param_overrides+ # Remove None values and internal parameters# Get supported parameters for the modelsupported_params = responses_api_provider_config.get_supported_openai_params(model)+ non_default_params = cast(Dict, response_api_optional_params)# Check for unsupported parameters- unsupported_params = [- param- for param in response_api_optional_params- if param not in supported_params- ]-- if unsupported_params:- raise litellm.UnsupportedParamsError(- model=model,- message=f"The following parameters are not supported for model {model}: {', '.join(unsupported_params)}",- )+ ResponsesAPIRequestUtils._check_valid_arg(+ supported_params=supported_params + (allowed_openai_params or []),+ non_default_params=non_default_params,+ drop_params=litellm.drop_params,+ custom_llm_provider=responses_api_provider_config.custom_llm_provider,+ model=model,+ )# Map parameters to provider-specific formatmapped_params = responses_api_provider_config.map_openai_params(@@ -60,6 +85,13 @@ class ResponsesAPIRequestUtils:drop_params=litellm.drop_params,)+ # add any allowed_openai_params to the mapped_params+ mapped_params = _apply_openai_param_overrides(+ optional_params=mapped_params,+ non_default_params=non_default_params,+ allowed_openai_params=allowed_openai_params or [],+ )+return mapped_params@staticmethod@@ -75,34 +107,48 @@ class ResponsesAPIRequestUtils:Returns:ResponsesAPIOptionalRequestParams instance with only the valid parameters"""+ from litellm.utils import PreProcessNonDefaultParams+valid_keys = get_type_hints(ResponsesAPIOptionalRequestParams).keys()- filtered_params = {- k: v for k, v in params.items() if k in valid_keys and v is not None- }+ custom_llm_provider = params.pop("custom_llm_provider", None)+ special_params = params.pop("kwargs")++ additional_drop_params = params.pop("additional_drop_params", None)+ non_default_params = (+ PreProcessNonDefaultParams.base_pre_process_non_default_params(+ passed_params=params,+ special_params=special_params,+ custom_llm_provider=custom_llm_provider,+ additional_drop_params=additional_drop_params,+ default_param_values={k: None for k in valid_keys},+ additional_endpoint_specific_params=["input"],+ )+ )# decode previous_response_id if it's a litellm encoded id- if "previous_response_id" in filtered_params:+ if "previous_response_id" in non_default_params:decoded_previous_response_id = ResponsesAPIRequestUtils.decode_previous_response_id_to_original_previous_response_id(- filtered_params["previous_response_id"]+ non_default_params["previous_response_id"])- filtered_params["previous_response_id"] = decoded_previous_response_id+ non_default_params["previous_response_id"] = decoded_previous_response_id- if "metadata" in filtered_params:+ if "metadata" in non_default_params:from litellm.utils import add_openai_metadata- filtered_params["metadata"] = add_openai_metadata(- filtered_params["metadata"]+ non_default_params["metadata"] = add_openai_metadata(+ non_default_params["metadata"])- return cast(ResponsesAPIOptionalRequestParams, filtered_params)-+ return cast(ResponsesAPIOptionalRequestParams, non_default_params)++ # fmt: off@overload@staticmethoddef _update_responses_api_response_id_with_model_id(responses_api_response: ResponsesAPIResponse,custom_llm_provider: Optional[str],litellm_metadata: Optional[Dict[str, Any]] = None,- ) -> ResponsesAPIResponse:+ ) -> ResponsesAPIResponse:...@overload@@ -111,9 +157,11 @@ class ResponsesAPIRequestUtils:responses_api_response: Dict[str, Any],custom_llm_provider: Optional[str],litellm_metadata: Optional[Dict[str, Any]] = None,- ) -> Dict[str, Any]:+ ) -> Dict[str, Any]:...+ # fmt: on+@staticmethoddef _update_responses_api_response_id_with_model_id(responses_api_response: Union[ResponsesAPIResponse, Dict[str, Any]],diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.pyindex f2f64fa3c5d..db35037801d 100644--- a/litellm/types/llms/openai.py+++ b/litellm/types/llms/openai.py@@ -968,6 +968,10 @@ class ResponsesAPIOptionalRequestParams(TypedDict, total=False):service_tier: Optional[str]safety_identifier: Optional[str]prompt: Optional[PromptObject]+ max_tool_calls: Optional[int]+ prompt_cache_key: Optional[str]+ stream_options: Optional[dict]+ top_logprobs: Optional[int]class ResponsesAPIRequestParams(ResponsesAPIOptionalRequestParams, total=False):diff --git a/tests/llm_translation/test_optional_params.py b/tests/llm_translation/test_optional_params.pyindex 52f6d99fdf5..0e1e34362b0 100644--- a/tests/llm_translation/test_optional_params.py+++ b/tests/llm_translation/test_optional_params.py@@ -1562,3 +1562,32 @@ def test_optional_params_image_gen_with_aspect_ratio():aspect_ratio="16:9",)assert optional_params["aspect_ratio"] == "16:9"+++def test_optional_params_responses_api_allowed_openai_params():+ from litellm import responses+ from unittest.mock import patch, MagicMock+ from litellm.llms.custom_httpx.http_handler import HTTPHandler++ client = HTTPHandler()++ with patch.object(client, "post") as mock_post:+ try:+ response = litellm.responses(+ model="openai/o1-pro",+ input="Tell me a three sentence bedtime story about a unicorn.",+ max_output_tokens=100,+ top_logprobs=10,+ allowed_openai_params=["top_logprobs"],+ client=client,+ )+ except Exception as e:+ import traceback++ traceback.print_exc()+ print("error: ", e)++ mock_post.assert_called_once()+ request_body = mock_post.call_args.kwargs+ print("request_body: ", request_body)+ assert "top_logprobs" in request_body["json"]