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(openai): flatten tool schema unions only for models whose validator rejects them

mateo-berri9448293903c3
diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py
index 63696983f7f..1c8f10d3307 100644
--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py
+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py
@@ -1167,6 +1167,10 @@ def _mergeable_branch(
return expanded
+def _is_object_schema(schema: Mapping[str, object]) -> bool:
+ return schema.get("type") == "object" or ("type" not in schema and "properties" in schema)
+
+
def _flatten_schema_against_root(
schema: Mapping[str, object],
root: Mapping[str, object],
@@ -1198,8 +1202,8 @@ def _flatten_schema_against_root(
(combinator, tuple(branch for branch in group if branch is not None)) for combinator, group in raw_branch_groups
)
branches: Final = tuple(branch for _, group in branch_groups for branch in group)
- is_object_schema: Final = schema.get("type") == "object" or (
- "type" not in schema and branches != () and all("properties" in branch for branch in branches)
+ is_object_schema: Final = _is_object_schema(schema) or (
+ "type" not in schema and branches != () and all(_is_object_schema(branch) for branch in branches)
)
if not is_object_schema:
return schema
diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.py
index 07a9a21bf7a..27e4b7dc4a6 100644
--- a/litellm/llms/openai/responses/transformation.py
+++ b/litellm/llms/openai/responses/transformation.py
@@ -32,6 +32,7 @@ else:
LiteLLMLoggingObj = Any
_NO_TOOL_UPDATE: Final[Mapping[str, object]] = MappingProxyType({})
+_MODEL_FAMILIES_REJECTING_TOP_LEVEL_SCHEMA_COMBINATORS: Final = ("gpt-4", "gpt-3.5", "chatgpt-4o", "o1", "o3", "o4")
class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):
@@ -171,7 +172,7 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):
input = self._validate_input_param(input)
tools = response_api_optional_request_params.get("tools")
input, tools = self.remove_cache_control_flag_from_input_and_tools(model=model, input=input, tools=tools)
- sanitized_tools: Final = self._flatten_tool_schema_combinators_for_openai(tools)
+ sanitized_tools: Final = self._flatten_tool_schema_combinators_for_openai(model=model, tools=tools)
if sanitized_tools is not None:
response_api_optional_request_params["tools"] = sanitized_tools
final_request_params: Final = dict(
@@ -214,21 +215,35 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):
def _flatten_tool_schema_combinators_for_openai(
self,
+ model: str,
tools: list[ALL_RESPONSES_API_TOOL_PARAMS] | None, # mutable-ok: request tools are a JSON list
) -> list[ALL_RESPONSES_API_TOOL_PARAMS] | None: # mutable-ok: request tools are a JSON list
- """Flatten top-level schema combinators for OpenAI itself only.
+ """Flatten top-level schema combinators only where OpenAI's validator rejects them.
OpenAI-compatible backends reusing this config (and the ChatGPT backend
- Codex talks to natively) accept them. Codex wraps MCP tools inside
- namespace entries, so nested ``tools`` arrays are walked too.
+ Codex talks to natively) accept them, and so do GPT-5 and later models,
+ which also call tools better with the union intact. Codex wraps MCP tools
+ inside namespace entries, so nested ``tools`` arrays are walked too.
"""
if tools is None or self.custom_llm_provider != LlmProviders.OPENAI:
return tools
+ if not self._rejects_top_level_schema_combinators(model):
+ return tools
flattened: Final = [ # mutable-ok: request tools are a JSON list
- self._flattened_tool_entry(tool) for tool in tools
+ self._flattened_tool_or_passthrough(tool) for tool in tools
]
return cast("list[ALL_RESPONSES_API_TOOL_PARAMS]", flattened) # cast-ok: dict spread keeps each tool's shape
+ @staticmethod
+ def _flattened_tool_or_passthrough(tool: object) -> object:
+ return OpenAIResponsesAPIConfig._flattened_tool_entry(tool) if isinstance(tool, dict) else tool
+
+ @staticmethod
+ def _rejects_top_level_schema_combinators(model: str) -> bool:
+ bare_model: Final = model.split("/")[-1]
+ base_model: Final = bare_model.split(":")[1] if bare_model.startswith("ft:") else bare_model
+ return base_model.startswith(_MODEL_FAMILIES_REJECTING_TOP_LEVEL_SCHEMA_COMBINATORS)
+
@staticmethod
def _flattened_tool_entry(
entry: Mapping[str, object],
@@ -699,7 +714,7 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):
input = self._validate_input_param(input)
tools = response_api_optional_request_params.get("tools")
input, tools = self.remove_cache_control_flag_from_input_and_tools(model=model, input=input, tools=tools)
- sanitized_tools: Final = self._flatten_tool_schema_combinators_for_openai(tools)
+ sanitized_tools: Final = self._flatten_tool_schema_combinators_for_openai(model=model, tools=tools)
if sanitized_tools is not None:
response_api_optional_request_params["tools"] = sanitized_tools
data: Final = dict(ResponsesAPIRequestParams(model=model, input=input, **response_api_optional_request_params))
diff --git a/tests/code_coverage_tests/recursive_detector.py b/tests/code_coverage_tests/recursive_detector.py
index b15a16ffc23..37e940460f6 100644
--- a/tests/code_coverage_tests/recursive_detector.py
+++ b/tests/code_coverage_tests/recursive_detector.py
@@ -57,6 +57,7 @@ IGNORE_FUNCTIONS = [
"_filter_argument_value", # max depth set (DEFAULT_MAX_RECURSE_DEPTH); fails closed by blocking the tool call at the cap.
"_redact_scanned_content", # max depth set (DEFAULT_MAX_RECURSE_DEPTH); fails closed by returning "[REDACTED]" at the cap.
"_iter_fallback_targets", # max depth set (2 * ROUTER_MAX_FALLBACKS); fails closed by raising ValueError at the cap.
+ "_mergeable_branch", # max depth set (_MAX_SCHEMA_FLATTEN_DEPTH=32) plus a seen_refs cycle guard; passes the schema through untouched at the cap.
"json_string_leaves", # max depth set (MAX_STRUCTURED_CONTENT_SCAN_DEPTH); fails closed by raising at the cap so nothing goes unscanned.
"with_json_string_leaves", # transitively bounded: only runs on a tree json_string_leaves already walked under the cap.
"json_unrewritable_labels", # max depth set (MAX_STRUCTURED_CONTENT_SCAN_DEPTH); returns the None sentinel at the cap so the caller blocks.
diff --git a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py
index b59a37516e9..772fbf98c57 100644
--- a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py
+++ b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py
@@ -1360,6 +1360,50 @@ class TestFlattenTopLevelSchemaCombinators:
assert "anyOf" not in flatten_top_level_schema_combinators(shallow)
assert flatten_top_level_schema_combinators(deep) is deep
+ @pytest.mark.parametrize(
+ "branches",
+ [
+ [{"required": ["enabled"]}, {"required": ["schedule"]}],
+ [{"type": "object", "required": ["enabled"]}, {"type": "object", "required": ["schedule"]}],
+ ],
+ )
+ def test_typeless_root_with_properties_flattens_branches_without_properties(self, branches):
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ flatten_top_level_schema_combinators,
+ )
+
+ schema = {
+ "properties": {"id": {"type": "string"}, "enabled": {"type": "boolean"}, "schedule": {"type": "string"}},
+ "required": ["id"],
+ "anyOf": branches,
+ }
+
+ result = flatten_top_level_schema_combinators(schema)
+
+ assert "anyOf" not in result
+ assert result["type"] == "object"
+ assert set(result["properties"]) == {"id", "enabled", "schedule"}
+ assert result["required"] == ["id"]
+
+ def test_typeless_root_flattens_typed_object_branches_without_properties(self):
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ flatten_top_level_schema_combinators,
+ )
+
+ schema = {
+ "anyOf": [
+ {"type": "object", "properties": {"id": {"type": "string"}}},
+ {"type": "object", "required": ["id"]},
+ ]
+ }
+
+ result = flatten_top_level_schema_combinators(schema)
+
+ assert "anyOf" not in result
+ assert result["type"] == "object"
+ assert result["properties"] == {"id": {"type": "string"}}
+ assert "required" not in result
+
def test_non_object_union_passes_through_unchanged(self):
from litellm.litellm_core_utils.prompt_templates.common_utils import (
flatten_top_level_schema_combinators,
diff --git a/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py b/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py
index 8135ec643e8..1a90db7c1fe 100644
--- a/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py
+++ b/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py
@@ -1,4 +1,5 @@
import json
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, Mock, patch
import httpx
@@ -1761,3 +1762,57 @@ class TestFlattenToolSchemaCombinatorsWiring:
)
assert "anyOf" in result["tools"][0]["parameters"]
+
+ @pytest.mark.parametrize(
+ "model",
+ [
+ "gpt-4o",
+ "gpt-4.1-mini",
+ "gpt-4-turbo",
+ "o1",
+ "o3-pro",
+ "o4-mini",
+ "openai/gpt-4o",
+ "ft:gpt-4o-2024-08-06:org::abc",
+ ],
+ )
+ def test_openai_flattens_for_models_whose_validator_rejects_combinators(self, model):
+ result = OpenAIResponsesAPIConfig().transform_responses_api_request(
+ model=model,
+ input="hi",
+ response_api_optional_request_params={"tools": [self._flat_function_tool()]},
+ litellm_params=GenericLiteLLMParams(),
+ headers={},
+ )
+
+ assert "anyOf" not in result["tools"][0]["parameters"]
+
+ @pytest.mark.parametrize(
+ "model", ["gpt-5", "gpt-5-nano", "gpt-5.4-mini", "gpt-5.4-codex", "gpt-5.5", "openai/gpt-5.2"]
+ )
+ def test_openai_keeps_combinators_for_models_that_accept_them(self, model):
+ tool = self._flat_function_tool()
+
+ result = OpenAIResponsesAPIConfig().transform_responses_api_request(
+ model=model,
+ input="hi",
+ response_api_optional_request_params={"tools": [tool]},
+ litellm_params=GenericLiteLLMParams(),
+ headers={},
+ )
+
+ assert result["tools"][0] is tool
+
+ def test_openai_leaves_non_dict_tool_entries_alone(self):
+ opaque_tool = SimpleNamespace(type="function", name="automation_update")
+
+ result = OpenAIResponsesAPIConfig().transform_responses_api_request(
+ model="gpt-4o",
+ input="hi",
+ response_api_optional_request_params={"tools": [opaque_tool, self._flat_function_tool()]},
+ litellm_params=GenericLiteLLMParams(),
+ headers={},
+ )
+
+ assert result["tools"][0] is opaque_tool
+ assert "anyOf" not in result["tools"][1]["parameters"]