Skip to content

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]

fix ruff check

yuneng-jiang2c8225b46520
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index b2a5e2fa59d..0974830324f 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -227,45 +227,24 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
return input_items, instructions
- def transform_request(
+ def _map_optional_params_to_responses_api_request(
self,
- model: str,
- messages: List["AllMessageValues"],
optional_params: dict,
- litellm_params: dict,
- headers: dict,
- litellm_logging_obj: "LiteLLMLoggingObj",
- client: Optional[Any] = None,
- ) -> dict:
- (
- input_items,
- instructions,
- ) = self.convert_chat_completion_messages_to_responses_api(messages)
-
- optional_params = self._extract_extra_body_params(optional_params)
-
- # Build responses API request using the reverse transformation logic
- responses_api_request = ResponsesAPIOptionalRequestParams()
-
- # Set instructions if we found a system message
- if instructions:
- responses_api_request["instructions"] = instructions
-
- # Map optional parameters
+ responses_api_request: "ResponsesAPIOptionalRequestParams",
+ ) -> None:
+ """Map optional_params into responses_api_request (mutates in place)."""
for key, value in optional_params.items():
if value is None:
continue
if key in ("max_tokens", "max_completion_tokens"):
responses_api_request["max_output_tokens"] = value
elif key == "tools" and value is not None:
- # Convert chat completion tools to responses API tools format
responses_api_request["tools"] = (
self._convert_tools_to_responses_format(
cast(List[Dict[str, Any]], value)
)
)
elif key == "response_format":
- # Convert response_format to text.format
text_format = self._transform_response_format_to_text_format(value)
if text_format:
responses_api_request["text"] = text_format # type: ignore
@@ -278,7 +257,78 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
elif key == "web_search_options":
self._add_web_search_tool(responses_api_request, value)
- # Get stream parameter from litellm_params if not in optional_params
+ def _build_sanitized_litellm_params(
+ self, litellm_params: dict
+ ) -> Dict[str, Any]:
+ """Build sanitized litellm_params with merged metadata."""
+ responses_optional_param_keys = set(
+ ResponsesAPIOptionalRequestParams.__annotations__.keys()
+ )
+ sanitized: Dict[str, Any] = {
+ key: value
+ for key, value in litellm_params.items()
+ if key not in responses_optional_param_keys
+ }
+ legacy_metadata = litellm_params.get("metadata")
+ existing_litellm_metadata = litellm_params.get("litellm_metadata")
+ merged_litellm_metadata: Dict[str, Any] = {}
+ if isinstance(legacy_metadata, dict):
+ merged_litellm_metadata.update(legacy_metadata)
+ if isinstance(existing_litellm_metadata, dict):
+ merged_litellm_metadata.update(existing_litellm_metadata)
+ if merged_litellm_metadata:
+ sanitized["litellm_metadata"] = merged_litellm_metadata
+ else:
+ sanitized.pop("litellm_metadata", None)
+ return sanitized
+
+ def _merge_responses_api_request_into_request_data(
+ self,
+ request_data: Dict[str, Any],
+ responses_api_request: "ResponsesAPIOptionalRequestParams",
+ instructions: Optional[str],
+ ) -> None:
+ """Add non-None values from responses_api_request into request_data."""
+ for key, value in responses_api_request.items():
+ if value is None:
+ continue
+ if key == "instructions" and instructions:
+ request_data["instructions"] = instructions
+ elif key == "stream_options" and isinstance(value, dict):
+ request_data["stream_options"] = value.get("include_obfuscation")
+ elif key == "user" and isinstance(value, str) and len(value) <= 64:
+ request_data["user"] = value
+ else:
+ request_data[key] = value
+
+ def transform_request(
+ self,
+ model: str,
+ messages: List["AllMessageValues"],
+ optional_params: dict,
+ litellm_params: dict,
+ headers: dict,
+ litellm_logging_obj: "LiteLLMLoggingObj",
+ client: Optional[Any] = None,
+ ) -> dict:
+ (
+ input_items,
+ instructions,
+ ) = self.convert_chat_completion_messages_to_responses_api(messages)
+
+ optional_params = self._extract_extra_body_params(optional_params)
+
+ # Build responses API request using the reverse transformation logic
+ responses_api_request = ResponsesAPIOptionalRequestParams()
+
+ # Set instructions if we found a system message
+ if instructions:
+ responses_api_request["instructions"] = instructions
+
+ self._map_optional_params_to_responses_api_request(
+ optional_params, responses_api_request
+ )
+
stream = optional_params.get("stream") or litellm_params.get("stream", False)
verbose_logger.debug(f"Chat provider: Stream parameter: {stream}")
@@ -302,26 +352,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
setattr(litellm_logging_obj, "call_type", CallTypes.responses.value)
- responses_optional_param_keys = set(
- ResponsesAPIOptionalRequestParams.__annotations__.keys()
+ sanitized_litellm_params = self._build_sanitized_litellm_params(
+ litellm_params
)
- sanitized_litellm_params: Dict[str, Any] = {
- key: value
- for key, value in litellm_params.items()
- if key not in responses_optional_param_keys
- }
-
- legacy_metadata = litellm_params.get("metadata")
- existing_litellm_metadata = litellm_params.get("litellm_metadata")
- merged_litellm_metadata: Dict[str, Any] = {}
- if isinstance(legacy_metadata, dict):
- merged_litellm_metadata.update(legacy_metadata)
- if isinstance(existing_litellm_metadata, dict):
- merged_litellm_metadata.update(existing_litellm_metadata)
- if merged_litellm_metadata:
- sanitized_litellm_params["litellm_metadata"] = merged_litellm_metadata
- else:
- sanitized_litellm_params.pop("litellm_metadata", None)
request_data = {
"model": api_model,
@@ -335,18 +368,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
f"Chat provider: Final request model={api_model}, input_items={len(input_items)}"
)
- # Add non-None values from responses_api_request
- for key, value in responses_api_request.items():
- if value is not None:
- if key == "instructions" and instructions:
- request_data["instructions"] = instructions
- elif key == "stream_options" and isinstance(value, dict):
- request_data["stream_options"] = value.get("include_obfuscation")
- elif key == "user": # string can't be longer than 64 characters
- if isinstance(value, str) and len(value) <= 64:
- request_data["user"] = value
- else:
- request_data[key] = value
+ self._merge_responses_api_request_into_request_data(
+ request_data, responses_api_request, instructions
+ )
if headers:
request_data["extra_headers"] = headers