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]

Merge branch 'main' into feat/bedrock-native-structured-outputs

Nicholas Gigliotti8f647cad2be5
diff --cc tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py
index cbd990594e7,ddbb0454cac..6d8d2c67dcd
--- a/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py
+++ b/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py
@@@ -2939,441 -2936,45 +2936,485 @@@ def test_drop_thinking_param_when_think
litellm.modify_params = original_modify_params
+def test_supports_native_structured_outputs():
+ """Test model detection for native structured outputs support."""
+ config = AmazonConverseConfig()
+
+ # Supported models
+ assert config._supports_native_structured_outputs(
+ "anthropic.claude-sonnet-4-5-20250929-v1:0"
+ )
+ assert config._supports_native_structured_outputs(
+ "anthropic.claude-haiku-4-5-20251001-v1:0"
+ )
+ assert config._supports_native_structured_outputs(
+ "anthropic.claude-opus-4-6-v1:0"
+ )
+ assert config._supports_native_structured_outputs(
+ "eu.anthropic.claude-opus-4-5-20260101-v1:0"
+ )
+ assert config._supports_native_structured_outputs("qwen.qwen3-235b-instruct-v1:0")
+ assert config._supports_native_structured_outputs("mistral.mistral-large-3-v1:0")
+ assert config._supports_native_structured_outputs("deepseek.deepseek-v3.1-v1:0")
+
+ # Unsupported models — should fall back to tool-call approach
+ assert not config._supports_native_structured_outputs(
+ "anthropic.claude-3-5-sonnet-20241022-v2:0"
+ )
+ assert not config._supports_native_structured_outputs(
+ "anthropic.claude-sonnet-4-20250514-v1:0"
+ )
+ assert not config._supports_native_structured_outputs(
+ "meta.llama3-3-70b-instruct-v1:0"
+ )
+ assert not config._supports_native_structured_outputs(
+ "amazon.nova-pro-v1:0"
+ )
+ # Excluded despite AWS listing them: broken constrained decoding on Bedrock
+ assert not config._supports_native_structured_outputs(
+ "openai.gpt-oss-120b-1:0"
+ )
+ assert not config._supports_native_structured_outputs(
+ "mistral.magistral-small-2509"
+ )
+
+
+def test_create_output_config_for_response_format():
+ """Test outputConfig dict creation from JSON schema."""
+ config = AmazonConverseConfig()
+
+ schema = {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "age": {"type": "integer"},
+ },
+ "required": ["name", "age"],
+ }
+
+ output_config = config._create_output_config_for_response_format(
+ json_schema=schema,
+ name="PersonInfo",
+ description="A person's info",
+ )
+
+ assert "textFormat" in output_config
+ text_format = output_config["textFormat"]
+ assert text_format["type"] == "json_schema"
+ assert "structure" in text_format
+
+ json_schema_def = text_format["structure"]["jsonSchema"]
+ assert json_schema_def["name"] == "PersonInfo"
+ assert json_schema_def["description"] == "A person's info"
+ # schema field must be a JSON string, not a dict
+ assert isinstance(json_schema_def["schema"], str)
+ parsed_schema = json.loads(json_schema_def["schema"])
+ # additionalProperties: false is injected by normalization
+ expected = {**schema, "additionalProperties": False}
+ assert parsed_schema == expected
+
+
+def test_translate_response_format_native_output_config():
+ """For supported models, _translate_response_format_param should produce outputConfig."""
+ config = AmazonConverseConfig()
+
+ response_format = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "WeatherResult",
+ "description": "Weather info",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "temp": {"type": "number"},
+ },
+ "required": ["temp"],
+ },
+ },
+ }
+
+ optional_params: dict = {}
+ result = config._translate_response_format_param(
+ value=response_format,
+ model="anthropic.claude-sonnet-4-5-20250929-v1:0",
+ optional_params=optional_params,
+ non_default_params={"response_format": response_format},
+ is_thinking_enabled=False,
+ )
+
+ # Should have outputConfig, NOT tools
+ assert "outputConfig" in result
+ assert "tools" not in result
+ assert "tool_choice" not in result
+ assert result["json_mode"] is True
+ # No fake_stream for native approach
+ assert "fake_stream" not in result
+
+ # Verify the schema content (additionalProperties: false is added by normalization)
+ schema_str = result["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["schema"]
+ parsed_schema = json.loads(schema_str)
+ expected_schema = {**response_format["json_schema"]["schema"], "additionalProperties": False}
+ assert parsed_schema == expected_schema
+ assert (
+ result["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["name"]
+ == "WeatherResult"
+ )
+
+
+def test_translate_response_format_fallback_tool_call():
+ """For unsupported models, should fall back to tool-call approach."""
+ config = AmazonConverseConfig()
+
+ response_format = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "WeatherResult",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "temp": {"type": "number"},
+ },
+ },
+ },
+ }
+
+ optional_params: dict = {}
+ result = config._translate_response_format_param(
+ value=response_format,
+ model="anthropic.claude-3-5-sonnet-20241022-v2:0",
+ optional_params=optional_params,
+ non_default_params={"response_format": response_format},
+ is_thinking_enabled=False,
+ )
+
+ # Should use tool-call approach, NOT outputConfig
+ assert "outputConfig" not in result
+ assert "tools" in result
+ assert result["json_mode"] is True
+
+
+def test_native_structured_output_no_fake_stream():
+ """When using native structured outputs with streaming, fake_stream should NOT be set."""
+ config = AmazonConverseConfig()
+
+ response_format = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "Result",
+ "schema": {
+ "type": "object",
+ "properties": {
+ "answer": {"type": "string"},
+ },
+ },
+ },
+ }
+
+ optional_params: dict = {}
+ result = config._translate_response_format_param(
+ value=response_format,
+ model="anthropic.claude-sonnet-4-5-20250929-v1:0",
+ optional_params=optional_params,
+ non_default_params={"response_format": response_format, "stream": True},
+ is_thinking_enabled=False,
+ )
+
+ assert "outputConfig" in result
+ assert result["json_mode"] is True
+ # No fake_stream for native approach
+ assert "fake_stream" not in result
+
+ # Verify the schema content
+ schema_str = result["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["schema"]
+ assert json.loads(schema_str) == {
+ "type": "object",
+ "properties": {"answer": {"type": "string"}},
+ "additionalProperties": False,
+ }
+
+
+def test_transform_request_with_output_config():
+ """Test that outputConfig flows through _transform_request_helper into the final request."""
+ from litellm.types.llms.bedrock import OutputConfigBlock, OutputFormat, OutputFormatStructure, JsonSchemaDefinition
+
+ config = AmazonConverseConfig()
+
+ output_config = OutputConfigBlock(
+ textFormat=OutputFormat(
+ type="json_schema",
+ structure=OutputFormatStructure(
+ jsonSchema=JsonSchemaDefinition(
+ schema='{"type": "object", "properties": {"x": {"type": "string"}}, "additionalProperties": false}',
+ name="TestSchema",
+ )
+ ),
+ )
+ )
+
+ messages = [{"role": "user", "content": "test"}]
+ optional_params = {
+ "outputConfig": output_config,
+ "json_mode": True,
+ }
+
+ result = config._transform_request(
+ model="anthropic.claude-sonnet-4-5-20250929-v1:0",
+ messages=messages,
+ optional_params=optional_params,
+ litellm_params={},
+ headers={},
+ )
+
+ assert "outputConfig" in result
+ assert result["outputConfig"]["textFormat"]["type"] == "json_schema"
+ assert result["outputConfig"]["textFormat"]["structure"]["jsonSchema"]["name"] == "TestSchema"
+
+
+def test_transform_response_native_structured_output():
+ """Test response handling when model returns JSON as text content (native structured output)."""
+ response_json = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [
+ {
+ "text": '{"temp": 62, "description": "Mild and foggy"}'
+ }
+ ],
+ }
+ },
+ "stopReason": "end_turn",
+ "usage": {
+ "inputTokens": 10,
+ "outputTokens": 20,
+ "totalTokens": 30,
+ },
+ }
+
+ class MockResponse:
+ def json(self):
+ return response_json
+
+ @property
+ def text(self):
+ return json.dumps(response_json)
+
+ config = AmazonConverseConfig()
+ model_response = ModelResponse()
+ # json_mode=True but no tool_call in response — native structured output path
+ optional_params = {"json_mode": True}
+
+ result = config._transform_response(
+ model="anthropic.claude-sonnet-4-5-20250929-v1:0",
+ response=MockResponse(),
+ model_response=model_response,
+ stream=False,
+ logging_obj=None,
+ optional_params=optional_params,
+ api_key=None,
+ data={},
+ messages=[],
+ encoding=None,
+ )
+
+ # Content should be the JSON text directly
+ assert result.choices[0].message.content == '{"temp": 62, "description": "Mild and foggy"}'
+ # Should NOT have tool_calls
+ assert result.choices[0].message.tool_calls is None
+ assert result.choices[0].finish_reason == "stop"
+
+
+def test_add_additional_properties_simple_object():
+ """Object schemas without additionalProperties get it set to false."""
+ schema = {
+ "type": "object",
+ "properties": {
+ "city": {"type": "string"},
+ "country": {"type": "string"},
+ },
+ "required": ["city", "country"],
+ }
+ result = AmazonConverseConfig._add_additional_properties_to_schema(schema)
+ assert result["additionalProperties"] is False
+ # Original should not be mutated
+ assert "additionalProperties" not in schema
+
+
+def test_add_additional_properties_already_set():
+ """If additionalProperties is already set, don't overwrite it."""
+ schema = {
+ "type": "object",
+ "properties": {"x": {"type": "string"}},
+ "additionalProperties": True,
+ }
+ result = AmazonConverseConfig._add_additional_properties_to_schema(schema)
+ assert result["additionalProperties"] is True
+
+
+def test_add_additional_properties_nested():
+ """Recursively processes nested object types in properties, items, $defs, anyOf."""
+ schema = {
+ "type": "object",
+ "properties": {
+ "address": {
+ "type": "object",
+ "properties": {
+ "street": {"type": "string"},
+ "zip": {"type": "string"},
+ },
+ },
+ "tags": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {"name": {"type": "string"}},
+ },
+ },
+ },
+ "$defs": {
+ "Metadata": {
+ "type": "object",
+ "properties": {"key": {"type": "string"}},
+ }
+ },
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {"variant": {"type": "string"}},
+ }
+ ],
+ }
+ result = AmazonConverseConfig._add_additional_properties_to_schema(schema)
+ # Top-level
+ assert result["additionalProperties"] is False
+ # Nested property object
+ assert result["properties"]["address"]["additionalProperties"] is False
+ # Array items object
+ assert result["properties"]["tags"]["items"]["additionalProperties"] is False
+ # $defs object
+ assert result["$defs"]["Metadata"]["additionalProperties"] is False
+ # anyOf object
+ assert result["anyOf"][0]["additionalProperties"] is False
+
+
+def test_add_additional_properties_non_object():
+ """Non-object schemas are returned unchanged."""
+ schema = {"type": "string"}
+ result = AmazonConverseConfig._add_additional_properties_to_schema(schema)
+ assert "additionalProperties" not in result
+ assert result == {"type": "string"}
+
+
+def test_add_additional_properties_definitions():
+ """Recursively processes object types inside 'definitions' (not just '$defs')."""
+ schema = {
+ "type": "object",
+ "properties": {
+ "item": {"$ref": "#/definitions/Item"},
+ },
+ "definitions": {
+ "Item": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "details": {
+ "type": "object",
+ "properties": {"weight": {"type": "number"}},
+ },
+ },
+ }
+ },
+ }
+ result = AmazonConverseConfig._add_additional_properties_to_schema(schema)
+ # Top-level
+ assert result["additionalProperties"] is False
+ # definitions object
+ assert result["definitions"]["Item"]["additionalProperties"] is False
+ # Nested object inside definitions
+ assert result["definitions"]["Item"]["properties"]["details"]["additionalProperties"] is False
+
+
+def test_json_object_no_schema_falls_back_to_tool_call():
+ """response_format: {type: json_object} with no schema should use tool-call fallback,
+ even for models that support native structured outputs."""
+ config = AmazonConverseConfig()
+ optional_params: dict = {}
+ non_default_params = {"response_format": {"type": "json_object"}}
+
+ result = config._translate_response_format_param(
+ value=non_default_params["response_format"],
+ model="anthropic.claude-sonnet-4-5-20250929-v1:0",
+ optional_params=optional_params,
+ non_default_params=non_default_params,
+ is_thinking_enabled=False,
+ )
+
+ # Should NOT use native outputConfig (no schema provided)
+ assert "outputConfig" not in result
+ # Should use tool-call fallback
+ assert "tools" in result
+ assert result["json_mode"] is True
+
+
+def test_output_config_applies_additional_properties():
+ """_create_output_config_for_response_format normalizes the schema."""
+ schema = {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "nested": {
+ "type": "object",
+ "properties": {"val": {"type": "integer"}},
+ },
+ },
+ }
+ output_config = AmazonConverseConfig._create_output_config_for_response_format(
+ json_schema=schema, name="test_schema"
+ )
+ parsed = json.loads(output_config["textFormat"]["structure"]["jsonSchema"]["schema"])
+ assert parsed["additionalProperties"] is False
+ assert parsed["properties"]["nested"]["additionalProperties"] is False
++
++
+ class TestBedrockMinThinkingBudgetTokens:
+ """Test that thinking.budget_tokens is clamped to the Bedrock minimum (1024)."""
+
+ def _map_params(
+ self, thinking_value, model="anthropic.claude-3-7-sonnet-20250219-v1:0"
+ ):
+ """Helper to call map_openai_params with the given thinking value."""
+ config = AmazonConverseConfig()
+ non_default_params = {"thinking": thinking_value}
+ optional_params = {"thinking": thinking_value}
+ return config.map_openai_params(
+ non_default_params=non_default_params,
+ optional_params=optional_params,
+ model=model,
+ drop_params=False,
+ )
+
+ def test_budget_tokens_below_minimum_is_clamped(self):
+ """budget_tokens < 1024 should be clamped to 1024."""
+ result = self._map_params({"type": "enabled", "budget_tokens": 499})
+ assert result["thinking"]["budget_tokens"] == 1024
+
+ def test_budget_tokens_at_minimum_is_unchanged(self):
+ """budget_tokens == 1024 should remain 1024."""
+ result = self._map_params({"type": "enabled", "budget_tokens": 1024})
+ assert result["thinking"]["budget_tokens"] == 1024
+
+ def test_budget_tokens_above_minimum_is_unchanged(self):
+ """budget_tokens > 1024 should remain unchanged."""
+ result = self._map_params({"type": "enabled", "budget_tokens": 2048})
+ assert result["thinking"]["budget_tokens"] == 2048
+
+ def test_no_thinking_param_does_not_error(self):
+ """When thinking is not provided, map_openai_params should not raise."""
+ config = AmazonConverseConfig()
+ result = config.map_openai_params(
+ non_default_params={},
+ optional_params={},
+ model="anthropic.claude-3-7-sonnet-20250219-v1:0",
+ drop_params=False,
+ )
+ assert "thinking" not in result or result.get("thinking") is None