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
fix(anthropic): json_schema envelope edge cases on the Anthropic json tool path (#47478)
Mateo Wang270d108aceb9
diff --git a/litellm/llms/anthropic/chat/handler.py b/litellm/llms/anthropic/chat/handler.pyindex 718536120b6..f0143f64be8 100644--- a/litellm/llms/anthropic/chat/handler.py+++ b/litellm/llms/anthropic/chat/handler.py@@ -28,6 +28,7 @@ from litellm.llms.base_llm.base_utils import (ResponseFormatSchema,names_a_response_format_property,partial_response_format_answer,+ response_format_answer_json,response_format_envelope_contents,split_response_format_answer,)@@ -104,17 +105,17 @@ def _key_after_a_string_verdict(string_value_start: str, schema: ResponseFormatSnext_key: Final = _STRING_VALUE_THEN_KEY.match(string_value_start)if next_key is None:return "undecided"- return "pass_through" if next_key.group(1) in schema.property_names else "hold"+ return "pass_through" if next_key.group(1) in schema.declared_names else "hold"def _is_a_label(text: str, schema: ResponseFormatSchema, tool_name: str) -> bool:- return text in schema.property_names or text == tool_name+ return text in schema.declared_names or text == tool_namedef _label_verdict(label: str, next_key: str, schema: ResponseFormatSchema, tool_name: str) -> _EnvelopeVerdict:if _is_a_label(label, schema, tool_name):return "hold"- return "pass_through" if next_key in schema.property_names else "undecided"+ return "pass_through" if next_key in schema.declared_names else "undecided"def _leading_labels_verdict(string_value_start: str, schema: ResponseFormatSchema, tool_name: str) -> _EnvelopeVerdict:@@ -159,9 +160,9 @@ def _prefix_verdict(buffered_json: str, schema: ResponseFormatSchema, tool_name:return "hold"if first_value is None and _NAME_VALUE_PREFIX.match(buffered_json):return "undecided"- if first_key.group(1) == "values" and "values" not in schema.property_names:+ if first_key.group(1) == "values" and "values" not in schema.declared_names:return "hold"- if first_key.group(1) in schema.property_names or not schema.property_names:+ if first_key.group(1) in schema.declared_names or not schema.declared_names:return "pass_through"return _first_value_verdict(buffered_json[first_key.end() :], schema, tool_name)@@ -172,13 +173,13 @@ def _held_answer(held: str, schema: ResponseFormatSchema) -> str:except (json.JSONDecodeError, RecursionError):return heldcontents: Final = response_format_envelope_contents(payload, schema, RESPONSE_FORMAT_TOOL_NAME)- return held if contents is None else json.dumps(contents)+ return held if contents is None else response_format_answer_json(contents)def _split_answer_text(blocks: tuple[str, ...], schema: ResponseFormatSchema) -> str:answer: Final = split_response_format_answer(blocks, schema)if answer is not None:- return json.dumps(answer)+ return response_format_answer_json(answer)return "".join(_held_answer(block, schema) for block in blocks)@@ -1283,7 +1284,7 @@ class ModelResponseIterator:return Noneself._streamed_answer_keys = streamed | frozenset(fields)separator: Final = ", " if streamed else ""- return f"{separator}{json.dumps(fields)[1:-1]}" if fields else ""+ return f"{separator}{response_format_answer_json(fields)[1:-1]}" if fields else ""def _flush_response_format_buffer(self) -> str:schema: Final = self.response_format_schema@@ -1314,6 +1315,17 @@ class ModelResponseIterator:return ""return _split_answer_text(blocks, self.response_format_schema)+ def cut_stream_chunk(self) -> ModelResponseStream | None:+ unsent: Final = self._flush_response_format_buffer() if self._response_format_buffer.getvalue() else ""+ text: Final = unsent + self._release_answer_close() + self._drain_split_answer_blocks()+ if not text:+ return None+ return ModelResponseStream(+ choices=[StreamingChoices(index=0, delta=Delta(content=text))],+ id=self.response_id,+ model=self.served_model,+ )+def _handle_message_delta(self, chunk: dict) -> tuple[str, Usage | None, dict[str, Any] | None, Mapping[str, object]]:@@ -1428,6 +1440,9 @@ class ModelResponseIterator:result = self._handle_accumulated_json_chunk(data_str="", is_final=True)if result is not None:return result+ cut_stream_chunk = self.cut_stream_chunk()+ if cut_stream_chunk is not None:+ return cut_stream_chunkraise StopIterationexcept ValueError as e:raise RuntimeError(f"Error receiving chunk from stream: {e}")@@ -1474,6 +1489,9 @@ class ModelResponseIterator:result = self._handle_accumulated_json_chunk(data_str="", is_final=True)if result is not None:return result+ cut_stream_chunk = self.cut_stream_chunk()+ if cut_stream_chunk is not None:+ return cut_stream_chunkraise StopAsyncIterationexcept ValueError as e:raise RuntimeError(f"Error receiving chunk from stream: {e}")diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.pyindex 9624dbb582b..867dd935a03 100644--- a/litellm/llms/anthropic/chat/transformation.py+++ b/litellm/llms/anthropic/chat/transformation.py@@ -23,7 +23,7 @@ from litellm.constants import (DEFAULT_REASONING_EFFORT_XHIGH_THINKING_BUDGET,RESPONSE_FORMAT_TOOL_NAME,)-from litellm.litellm_core_utils.core_helpers import map_finish_reason+from litellm.litellm_core_utils.core_helpers import drops_unsupported_params, map_finish_reasonfrom litellm.litellm_core_utils.prompt_templates.common_utils import (DEFS_MAX_INLINED_BYTES,is_object_schema,@@ -50,6 +50,7 @@ from litellm.litellm_core_utils.prompt_templates.mid_conversation_system importfrom litellm.llms.base_llm.base_utils import (ResponseFormatSchema,as_json_object,+ response_format_answer_json,response_format_schema,split_response_format_answer,type_to_response_format_param,@@ -163,6 +164,7 @@ _ANTHROPIC_TOOL_NAME_MAX_LEN: Final = 128_DEFER_LOADING_ADAPTER: Final = TypeAdapter(bool)_TOOL_FIELDS_ADAPTER: Final = TypeAdapter(Mapping[str, object])_TOOLS_ADAPTER: Final = TypeAdapter(list[object])+_LITELLM_PARAMS_ADAPTER: Final = TypeAdapter(Mapping[str, object])_NATIVE_OUTPUT_STRING_FORMATS: Final = frozenset(("date-time", "time", "date", "duration", "email", "hostname", "uri", "ipv4", "ipv6", "uuid"))@@ -2436,6 +2438,13 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):drop_params=litellm_params.get("drop_params") is True,output_key="top_k",)+ output_format: Final = request_params.get("output_format")+ if (+ output_format is not None+ and not isinstance(output_format, Mapping)+ and drops_unsupported_params(_LITELLM_PARAMS_ADAPTER.validate_python(litellm_params).get("drop_params"))+ ):+ request_params.pop("output_format")data: Final = {"model": model,@@ -3166,7 +3175,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):))if split_answer is not None:- return litellm.Message(content=json.dumps(split_answer))+ return litellm.Message(content=response_format_answer_json(split_answer))try:payload: Final = _DECODED_JSON.validate_python(json.loads(json_mode_content_str))except (json.JSONDecodeError, RecursionError):@@ -3174,7 +3183,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):return litellm.Message(content=json_mode_content_str)if response_format_schema is not None:return litellm.Message(- content=json.dumps(+ content=response_format_answer_json(unwrap_response_format_envelope(payload, response_format_schema, RESPONSE_FORMAT_TOOL_NAME)))diff --git a/litellm/llms/anthropic/pass_through/messages/transformation.py b/litellm/llms/anthropic/pass_through/messages/transformation.pyindex 0e8c1b49e8e..a71cd72b768 100644--- a/litellm/llms/anthropic/pass_through/messages/transformation.py+++ b/litellm/llms/anthropic/pass_through/messages/transformation.py@@ -7,6 +7,7 @@ import litellmfrom litellm._logging import verbose_loggerfrom litellm.anthropic_beta_headers_manager import get_unsupported_headers, is_beta_header_supported_by_bundled_configfrom litellm.exceptions import AuthenticationError+from litellm.litellm_core_utils.core_helpers import drops_unsupported_paramsfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.llms.anthropic.pass_through.convertible_blocks import drop_non_string_tool_result_textsfrom litellm.llms.anthropic.pass_through.safeguards import proxy_serves_safeguards@@ -627,6 +628,14 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):):anthropic_messages_optional_request_params.pop("safeguards") # pyright: ignore[reportUnknownMemberType] # the request params arrive as a bare dict+ output_format: Final[object] = anthropic_messages_optional_request_params.get("output_format") # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] # the request params arrive as a bare dict+ if (+ output_format is not None+ and not isinstance(output_format, Mapping)+ and drops_unsupported_params(litellm_params.drop_params)+ ):+ anthropic_messages_optional_request_params.pop("output_format") # pyright: ignore[reportUnknownMemberType] # the request params arrive as a bare dict+self._translate_reasoning_effort_to_anthropic(model=model,optional_params=anthropic_messages_optional_request_params,diff --git a/litellm/llms/base_llm/base_utils.py b/litellm/llms/base_llm/base_utils.pyindex 5ed73e13188..640930a780d 100644--- a/litellm/llms/base_llm/base_utils.py+++ b/litellm/llms/base_llm/base_utils.py@@ -5,6 +5,7 @@ Utility functions for base LLM classes.import copyimport itertoolsimport json+import refrom abc import ABC, abstractmethodfrom collections.abc import Iterator, Mapping, Sequencefrom dataclasses import dataclass@@ -172,7 +173,7 @@ _convert_tool_response_to_message = convert_tool_response_to_message@dataclass(frozen=True, slots=True)class ResponseFormatSchema:- property_names: frozenset[str]+ declared_names: frozenset[str]required_names: frozenset[str] = frozenset()allows_undeclared_keys: bool = False@@ -216,9 +217,10 @@ def response_format_schema(value: object) -> ResponseFormatSchema | None:properties: Final = as_json_object(document.get("properties", {}))if properties is None:return None+ required_names: Final = _names(document.get("required", ()))return ResponseFormatSchema(- property_names=frozenset(properties),- required_names=_names(document.get("required", ())),+ declared_names=frozenset(properties) | required_names,+ required_names=required_names,allows_undeclared_keys=_allows_undeclared_keys(document),)@@ -244,8 +246,9 @@ def _json_object_or_encoded_object(value: JsonValue) -> Mapping[str, JsonValue]def _label_keys(payload_object: Mapping[str, JsonValue], schema: ResponseFormatSchema) -> frozenset[str]:if not schema.required_names:return frozenset()- declared: Final = schema.property_names | schema.required_names- return frozenset(key for key, value in payload_object.items() if isinstance(value, str) and key not in declared)+ return frozenset(+ key for key, value in payload_object.items() if isinstance(value, str) and key not in schema.declared_names+ )def _envelope_layer(@@ -256,7 +259,7 @@ def _envelope_layer()label_keys: Final = name_keys or _label_keys(payload_object, schema)wrapper_keys: Final = tuple(key for key in payload_object if key not in label_keys)- if len(wrapper_keys) != 1 or wrapper_keys[0] in schema.property_names:+ if len(wrapper_keys) != 1 or wrapper_keys[0] in schema.declared_names:return Nonewrapped: Final = payload_object[wrapper_keys[0]]inner: Final = _json_object_or_encoded_object(wrapped) if name_keys else as_json_object(wrapped)@@ -275,15 +278,16 @@ def _envelope_layers(def _schema_object_inside_envelope(payload_object: Mapping[str, JsonValue], schema: ResponseFormatSchema, tool_name: str) -> Mapping[str, JsonValue] | None:- layers: Final = _envelope_layers(payload_object, schema, tool_name)- candidates: Final = layers if schema.property_names else itertools.islice(layers, 1)- return next((layer.inner for layer in candidates if _holds_the_schema_object(layer, schema)), None)+ walk: Final = _envelope_layers(payload_object, schema, tool_name)+ layers: Final = tuple(walk if schema.declared_names else itertools.islice(walk, 1))+ schema_object: Final = next((layer.inner for layer in layers if _shares_a_schema_key(layer.inner, schema)), None)+ if schema_object is not None:+ return schema_object+ return next((layer.inner for layer in layers if layer.names_the_tool), None)-def _holds_the_schema_object(layer: _EnvelopeLayer, schema: ResponseFormatSchema) -> bool:- if layer.names_the_tool:- return True- return not schema.accepts_a_lone_undeclared_key and not schema.property_names.isdisjoint(layer.inner)+def _shares_a_schema_key(candidate: Mapping[str, JsonValue], schema: ResponseFormatSchema) -> bool:+ return not schema.accepts_a_lone_undeclared_key and not schema.declared_names.isdisjoint(candidate)def response_format_envelope_contents(payload: object, schema: ResponseFormatSchema, tool_name: str) -> object | None:@@ -293,7 +297,15 @@ def response_format_envelope_contents(payload: object, schema: ResponseFormatSchschema_object: Final = _schema_object_inside_envelope(payload_object, schema, tool_name)if schema_object is not None:return schema_object- return None if "values" in schema.property_names else payload_object.get("values")+ return None if "values" in schema.declared_names else payload_object.get("values")+++_LONE_SURROGATE: Final = re.compile("[\ud800-\udfff]")+++def response_format_answer_json(value: object) -> str:+ text: Final = json.dumps(value, ensure_ascii=False)+ return json.dumps(value) if _LONE_SURROGATE.search(text) else textdef unwrap_response_format_envelope(payload: object, schema: ResponseFormatSchema, tool_name: str) -> object:@@ -305,7 +317,7 @@ def _field_names(blocks: tuple[Mapping[str, JsonValue], ...], key: str, schema: ResponseFormatSchema) -> tuple[str, ...] | None:values: Final = (block[key] for block in blocks)- names: Final = tuple(value for value in values if isinstance(value, str) and value in schema.property_names)+ names: Final = tuple(value for value in values if isinstance(value, str) and value in schema.declared_names)return names if len(frozenset(names)) == len(blocks) else None@@ -324,7 +336,7 @@ def _split_answer_fields(blocks: tuple[Mapping[str, JsonValue], ...], schema: ResponseFormatSchema) -> Mapping[str, JsonValue] | None:keys: Final = frozenset(blocks[0])- if not keys.isdisjoint(schema.property_names) or any(frozenset(block) != keys for block in blocks):+ if not keys.isdisjoint(schema.declared_names) or any(frozenset(block) != keys for block in blocks):return Nonenamed: Final = tuple((key, names) for key in keys if (names := _field_names(blocks, key, schema)) is not None)if len(named) != 1:@@ -340,7 +352,7 @@ def _merged_partial_answers(blocks: tuple[Mapping[str, JsonValue], ...], schema: ResponseFormatSchema) -> Mapping[str, JsonValue] | None:keys: Final = frozenset(itertools.chain.from_iterable(blocks))- if not keys <= schema.property_names or len(keys) != sum(len(block) for block in blocks):+ if not keys <= schema.declared_names or len(keys) != sum(len(block) for block in blocks):return Nonereturn dict(itertools.chain.from_iterable(block.items() for block in blocks))@@ -358,14 +370,14 @@ def split_response_format_answer(def partial_response_format_answer(encoded_block: str, schema: ResponseFormatSchema) -> Mapping[str, JsonValue] | None:block: Final = _json_object_or_encoded_object(encoded_block)- return block if block is not None and frozenset(block) <= schema.property_names else None+ return block if block is not None and frozenset(block) <= schema.declared_names else Nonedef names_a_response_format_property(encoded_block: str, schema: ResponseFormatSchema) -> bool:block: Final = _json_object_or_encoded_object(encoded_block)if block is None:return False- return any(isinstance(value, str) and value in schema.property_names for value in block.values())+ return any(isinstance(value, str) and value in schema.declared_names for value in block.values())def _dict_to_response_format_helper(response_format: dict, ref_template: str | None = None) -> dict:diff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.pyindex 7553dacd35d..3d4821fcaa2 100644--- a/litellm/llms/bedrock/chat/invoke_handler.py+++ b/litellm/llms/bedrock/chat/invoke_handler.py@@ -857,6 +857,9 @@ class AWSEventStreamDecoder:undecoded_stream_error: Final = tally.undecoded_stream_error(response_headers)if undecoded_stream_error is not None:raise undecoded_stream_error+ stream_end_chunk: Final = self._stream_end_chunk()+ if stream_end_chunk is not None:+ yield stream_end_chunkasync def aiter_bytes(self, iterator: AsyncIterator[bytes], *, response_headers: Mapping[str, str] | None = None@@ -878,6 +881,12 @@ class AWSEventStreamDecoder:undecoded_stream_error: Final = tally.undecoded_stream_error(response_headers)if undecoded_stream_error is not None:raise undecoded_stream_error+ stream_end_chunk: Final = self._stream_end_chunk()+ if stream_end_chunk is not None:+ yield stream_end_chunk++ def _stream_end_chunk(self) -> ModelResponseStream | None:+ return Nonedef _response_stream_shape(self) -> "Shape":response_stream_shape: Final = get_bedrock_response_stream_shape()@@ -956,6 +965,9 @@ class AmazonAnthropicClaudeStreamDecoder(AWSEventStreamDecoder):def _chunk_parser(self, chunk_data: dict) -> ModelResponseStream:return self.anthropic_model_response_iterator.chunk_parser(chunk=chunk_data)+ def _stream_end_chunk(self) -> ModelResponseStream | None:+ return self.anthropic_model_response_iterator.cut_stream_chunk()+class AmazonDeepSeekR1StreamDecoder(AWSEventStreamDecoder):def __init__(diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/output_params_utils.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/output_params_utils.pyindex d5950d49d2b..db27427a5be 100644--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/output_params_utils.py+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/output_params_utils.py@@ -45,11 +45,22 @@ def _as_output_config(value: object) -> Mapping[str, object] | None:def _fold_output_format_into_output_config(- output_config: Mapping[str, object] | None, output_format: object+ output_config: Mapping[str, object] | None, output_format: object, model: str) -> Mapping[str, object] | None:if output_format is None:return output_config- return {**(output_config or {}), "format": output_format}+ output_format_object: Final = _as_output_config(output_format)+ if output_format_object is not None:+ return {**(output_config or {}), "format": output_format_object}+ from litellm.exceptions import UnsupportedParamsError++ raise UnsupportedParamsError(+ message=(+ f"{model} on vertex_ai needs `output_format` to be a JSON object, got {type(output_format).__name__}. "+ "To drop it, set `litellm.drop_params=True` or for proxy:\n\n`litellm_settings:\n drop_params: true`\n"+ ),+ status_code=400,+ )def sanitize_vertex_anthropic_output_params(data: dict, model: str) -> None:@@ -67,13 +78,16 @@ def sanitize_vertex_anthropic_output_params(data: dict, model: str) -> None:body has no empty dict.* ``output_format`` is moved into ``output_config.format``, becauseVertex AI Claude rejects the top-level field as deprecated. When both- are set, ``output_format`` wins, as it does in the Anthropic adapter.+ are set, a dict ``output_format`` wins, as it does in the Anthropic+ adapter. A non-dict ``output_format`` raises a 400+ ``UnsupportedParamsError``, since the parent config already dropped it+ under ``drop_params``.* Non-dict values for ``output_config`` are dropped to avoid sendingmalformed payloads downstream."""request: Final[dict[str, object]] = data # mutable-ok: the caller's request body is sanitized in placeoutput_config: Final = _fold_output_format_into_output_config(- _as_output_config(request.get("output_config")), request.pop("output_format", None)+ _as_output_config(request.get("output_config")), request.pop("output_format", None), model)if output_config is None:request.pop("output_config", None)diff --git a/tests/integration/providers/test_vertex_anthropic_structured_output_wire.py b/tests/integration/providers/test_vertex_anthropic_structured_output_wire.pyindex cb295815ae2..2918f364c56 100644--- a/tests/integration/providers/test_vertex_anthropic_structured_output_wire.py+++ b/tests/integration/providers/test_vertex_anthropic_structured_output_wire.py@@ -1819,25 +1819,32 @@ def test_vertex_chat_without_response_format_sends_no_tool_and_no_output_config(assert not {"tools", "output_config", "output_format"} & sent.body.keys(), sent.body- "output_format",- [5, [], {}, "x" * 5000],- ids=["int", "list", "empty", "5kb"],-)-def test_vertex_messages_malformed_output_format_reaches_the_caller_as_the_peer_400(+def test_vertex_messages_empty_output_format_reaches_the_caller_as_the_peer_400(gateway: Gateway) -> None:+ marker, marker_hex = _marker("native")+ with wire_server(_peer) as wire, gateway.scenario() as scenario:+ model: Final = _vertex_deployment(gateway, scenario, wire.url, _NATIVE_MODEL)+ response: Final = gateway.request("POST", "/v1/messages", _messages_body(model, marker, output_format={}))+ assert response.status_code == 400, response.text+ assert _BAD_FORMAT in response.text, response.text+ sent: Final = _one_delivery(wire, marker_hex)+ assert "output_format" not in sent.body, sent.body+ assert object_value(sent.body["output_config"])["format"] == {}, sent.body+ assert gateway.request("GET", "/health/liveliness").status_code == 200++[email protected]("output_format", [5, [], "x" * 5000], ids=["int", "list", "5kb"])+def test_vertex_messages_non_object_output_format_is_refused_without_reaching_the_peer(gateway: Gateway, output_format: JsonValue) -> None:- marker, marker_hex = _marker("native")+ marker, _ = _marker("native")with wire_server(_peer) as wire, gateway.scenario() as scenario:model: Final = _vertex_deployment(gateway, scenario, wire.url, _NATIVE_MODEL)response: Final = gateway.request("POST", "/v1/messages", _messages_body(model, marker, output_format=output_format))assert response.status_code == 400, response.text- assert _BAD_FORMAT in response.text, response.text- sent: Final = _one_delivery(wire, marker_hex)- assert "output_format" not in sent.body, sent.body- assert object_value(sent.body["output_config"])["format"] == output_format, sent.body+ assert "needs `output_format` to be a JSON object" in response.text, response.text+ assert _delivered(wire) == ()assert gateway.request("GET", "/health/liveliness").status_code == 200diff --git a/tests/integration/translation/chat_completions/response_format/__init__.py b/tests/integration/translation/chat_completions/response_format/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/integration/translation/chat_completions/response_format/test_chat_completions_response_format_anthropic.py b/tests/integration/translation/chat_completions/response_format/test_chat_completions_response_format_anthropic.pynew file mode 100644index 00000000000..07e4358ff97--- /dev/null+++ b/tests/integration/translation/chat_completions/response_format/test_chat_completions_response_format_anthropic.py@@ -0,0 +1,123 @@+from dataclasses import replace+from typing import Final+from unittest.mock import ANY++import pytest+from integration._support.client import Gateway+from integration._support.provider import SharedProvider+from integration.translation.case import TranslationTestCase+from integration.translation.chat_completions.bases.anthropic import CLAUDE_HAIKU_5_5_TEST_CASE+from integration.translation.runner import assert_translation++PLACE_SCHEMA: Final = {+ "type": "object",+ "properties": {"city": {"type": "string"}, "country": {"type": "string"}},+ "required": ["city", "country"],+ "additionalProperties": True,+}+PLACE_PROMPT: Final = "Which city is the capital of France? Answer as JSON with city and country."+PLACE_TOOL_USE: Final = {+ "type": "tool_use",+ "id": "toolu_01Sr1iptyZnsy1eNxabMZejF",+ "name": "json_tool_call",+ "input": {"city": "Paris", "country": "France"},+ "caller": {"type": "direct"},+}++CLAUDE_HAIKU_5_5_JSON_SCHEMA_TEST_CASE: Final = replace(+ CLAUDE_HAIKU_5_5_TEST_CASE,+ scenario="json_schema",+ litellm_request={+ "model": "anthropic/claude-haiku-5-5",+ "max_tokens": 128,+ "messages": [{"role": "user", "content": PLACE_PROMPT}],+ "response_format": {"type": "json_schema", "json_schema": {"name": "place", "schema": PLACE_SCHEMA}},+ "cache": {"no-cache": True},+ },+ expected_provider_request={+ "model": "claude-haiku-5-5",+ "messages": [{"role": "user", "content": [{"type": "text", "text": PLACE_PROMPT}]}],+ "max_tokens": 128,+ "tool_choice": {"name": "json_tool_call", "type": "tool"},+ "tools": [{"name": "json_tool_call", "input_schema": PLACE_SCHEMA}],+ },+ mock_provider_response={+ "model": "claude-haiku-5-5",+ "id": "msg_011CgCoP2UR3vcM5ZWmEBd8D",+ "type": "message",+ "role": "assistant",+ "content": [PLACE_TOOL_USE],+ "container": None,+ "stop_reason": "tool_use",+ "stop_sequence": None,+ "stop_details": None,+ "usage": {+ "input_tokens": 528,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0},+ "output_tokens": 55,+ "output_tokens_details": {"thinking_tokens": 0},+ "service_tier": "standard",+ "inference_geo": "global",+ "speed": "standard",+ },+ "diagnostics": None,+ },+ expected_litellm_response={+ "id": ANY,+ "created": ANY,+ "object": "chat.completion",+ "model": "anthropic/claude-haiku-5-5",+ "choices": [+ {+ "finish_reason": "stop",+ "index": 0,+ "message": {"content": '{"city": "Paris", "country": "France"}', "role": "assistant"},+ }+ ],+ "usage": {+ "completion_tokens": 55,+ "prompt_tokens": 528,+ "total_tokens": 583,+ "completion_tokens_details": {"reasoning_tokens": 0, "text_tokens": 55},+ "prompt_tokens_details": {+ "cached_tokens": 0,+ "text_tokens": 528,+ "cache_write_tokens": 0,+ "cache_creation_tokens": 0,+ "cache_creation_token_details": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0},+ },+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "inference_geo": "global",+ "service_tier": "standard",+ "speed": "standard",+ },+ },+)++CLAUDE_HAIKU_5_5_JSON_SCHEMA_TOOL_NAMED_ENVELOPE_TEST_CASE: Final = replace(+ CLAUDE_HAIKU_5_5_JSON_SCHEMA_TEST_CASE,+ scenario="json_schema_tool_named_envelope",+ mock_provider_response={+ **CLAUDE_HAIKU_5_5_JSON_SCHEMA_TEST_CASE.mock_provider_response,+ "content": [+ {+ **PLACE_TOOL_USE,+ "input": {"name": "json_tool_call", "arguments": {"input": {"city": "Paris", "country": "France"}}},+ }+ ],+ },+)+++ "case",+ [CLAUDE_HAIKU_5_5_JSON_SCHEMA_TEST_CASE, CLAUDE_HAIKU_5_5_JSON_SCHEMA_TOOL_NAMED_ENVELOPE_TEST_CASE],+ ids=lambda case: case.id,+)+def test_chat_completions_response_format_anthropic(+ case: TranslationTestCase, gateway: Gateway, provider: SharedProvider+) -> None:+ assert_translation(case, gateway, provider)diff --git a/tests/integration/translation/chat_completions/streaming/test_chat_completions_streaming_anthropic.py b/tests/integration/translation/chat_completions/streaming/test_chat_completions_streaming_anthropic.pyindex ccba51cff23..b2c0d39f9aa 100644--- a/tests/integration/translation/chat_completions/streaming/test_chat_completions_streaming_anthropic.py+++ b/tests/integration/translation/chat_completions/streaming/test_chat_completions_streaming_anthropic.py@@ -5,8 +5,12 @@ import pytestfrom integration._support.client import Gatewayfrom integration._support.provider import SharedProviderfrom integration.translation.case import SSEFrame, StreamingTranslationTestCase-from integration.translation.chat_completions.bases.anthropic import CLAUDE_SONNET_5_5_TEST_CASE+from integration.translation.chat_completions.bases.anthropic import (+ CLAUDE_HAIKU_5_5_TEST_CASE,+ CLAUDE_SONNET_5_5_TEST_CASE,+)from integration.translation.runner import assert_streaming_translation+from pydantic import JsonValueCLAUDE_SONNET_5_5_STREAMING_TEST_CASE: Final = StreamingTranslationTestCase(scenario="streaming",@@ -128,7 +132,143 @@ CLAUDE_SONNET_5_5_STREAMING_TEST_CASE: Final = StreamingTranslationTestCase()[email protected]("case", [CLAUDE_SONNET_5_5_STREAMING_TEST_CASE], ids=lambda case: case.id)+PLACE_SCHEMA: Final = {+ "type": "object",+ "properties": {"city": {"type": "string"}, "country": {"type": "string"}},+ "required": ["city", "country"],+ "additionalProperties": True,+}+PLACE_PROMPT: Final = "Which city is the capital of France? Answer as JSON with city and country."+++def _place_delta(partial_json: str) -> SSEFrame:+ return SSEFrame(+ event="content_block_delta",+ data={+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "input_json_delta", "partial_json": partial_json},+ },+ )+++def _place_chunk(delta: dict[str, JsonValue], *, finish_reason: str | None = None) -> SSEFrame:+ finish: Final = {} if finish_reason is None else {"finish_reason": finish_reason}+ return SSEFrame(+ data={+ "id": ANY,+ "object": "chat.completion.chunk",+ "created": ANY,+ "model": "anthropic/claude-haiku-5-5",+ "choices": [{"index": 0, "delta": delta, **finish}],+ }+ )+++CLAUDE_HAIKU_5_5_JSON_SCHEMA_CUT_STREAM_TEST_CASE: Final = StreamingTranslationTestCase(+ scenario="json_schema_cut_stream",+ litellm_endpoint=CLAUDE_HAIKU_5_5_TEST_CASE.litellm_endpoint,+ litellm_request={+ "model": "anthropic/claude-haiku-5-5",+ "max_tokens": 128,+ "messages": [{"role": "user", "content": PLACE_PROMPT}],+ "response_format": {"type": "json_schema", "json_schema": {"name": "place", "schema": PLACE_SCHEMA}},+ "cache": {"no-cache": True},+ "stream": True,+ },+ expected_provider_endpoint=CLAUDE_HAIKU_5_5_TEST_CASE.expected_provider_endpoint,+ expected_provider_headers=CLAUDE_HAIKU_5_5_TEST_CASE.expected_provider_headers,+ expected_provider_request={+ "model": "claude-haiku-5-5",+ "messages": [{"role": "user", "content": [{"type": "text", "text": PLACE_PROMPT}]}],+ "max_tokens": 128,+ "tool_choice": {"name": "json_tool_call", "type": "tool"},+ "tools": [{"name": "json_tool_call", "input_schema": PLACE_SCHEMA}],+ "stream": True,+ },+ mock_provider_frames=(+ SSEFrame(+ event="message_start",+ data={+ "type": "message_start",+ "message": {+ "model": "claude-haiku-5-5",+ "id": "msg_011CgCoP5RkexwE6N7PRZEca",+ "type": "message",+ "role": "assistant",+ "content": [],+ "container": None,+ "stop_reason": None,+ "stop_sequence": None,+ "stop_details": None,+ "usage": {+ "input_tokens": 528,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0},+ "output_tokens": 16,+ "service_tier": "standard",+ "inference_geo": "global",+ "speed": "standard",+ },+ "diagnostics": None,+ },+ },+ ),+ SSEFrame(+ event="content_block_start",+ data={+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "tool_use",+ "id": "toolu_01B4QSMQtft8TA3Rn6XFziWe",+ "name": "json_tool_call",+ "input": {},+ "caller": {"type": "direct"},+ },+ },+ ),+ SSEFrame(event="ping", data={"type": "ping"}),+ _place_delta(""),+ _place_delta('{"city"'),+ _place_delta(': "Pari'),+ _place_delta('s"'),+ _place_delta(', "coun'),+ _place_delta('try": "'),+ _place_delta('France"}'),+ ),+ expected_litellm_frames=(+ _place_chunk({"role": "assistant", "content": '{"city": "Pari'}),+ _place_chunk({"content": 's"'}),+ _place_chunk({"content": ', "coun'}),+ _place_chunk({"content": 'try": "'}),+ _place_chunk({"content": 'France"'}),+ _place_chunk({"content": "}"}),+ _place_chunk({}, finish_reason="stop"),+ SSEFrame(data="[DONE]"),+ ),+ expected_litellm_response={+ "id": ANY,+ "object": "chat.completion",+ "created": ANY,+ "model": "anthropic/claude-haiku-5-5",+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": '{"city": "Paris", "country": "France"}'},+ "finish_reason": "stop",+ }+ ],+ },+)+++ "case",+ [CLAUDE_SONNET_5_5_STREAMING_TEST_CASE, CLAUDE_HAIKU_5_5_JSON_SCHEMA_CUT_STREAM_TEST_CASE],+ ids=lambda case: case.id,+)def test_chat_completions_streaming_anthropic(case: StreamingTranslationTestCase, gateway: Gateway, provider: SharedProvider) -> None:diff --git a/tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py b/tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.pyindex a2d9f321122..1f4a5aaa256 100644--- a/tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py+++ b/tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py@@ -3108,6 +3108,92 @@ def test_streamed_json_mode_answer_with_a_foreign_name_matches_the_non_streamed_assert unwrap_response_format_envelope(answer, schema, RESPONSE_FORMAT_TOOL_NAME) == answer+def test_streamed_json_mode_tool_name_envelope_around_an_input_wrapper_is_unwrapped_to_the_answer():+ envelope = json.dumps({"name": RESPONSE_FORMAT_TOOL_NAME, "arguments": {"input": _STREAMED_RISK_OBJECT}})++ contents = _streamed_json_mode_contents((envelope[:9], envelope[9:40], envelope[40:]))++ assert json.loads("".join(contents)) == _STREAMED_RISK_OBJECT+++def test_streamed_json_mode_unwrapped_answer_keeps_non_ascii_text():+ answer = {"tier": 3, "summary": "Hôtel Lutetia, 東京"}+ envelope = json.dumps({"input": answer}, ensure_ascii=False)++ contents = _streamed_json_mode_contents((envelope[:9], envelope[9:30], envelope[30:]))++ assert "Hôtel Lutetia, 東京" in "".join(contents)+ assert json.loads("".join(contents)) == answer+++def test_streamed_json_mode_unwrapped_answer_with_a_lone_surrogate_stays_utf8_encodable():+ answer = {"tier": 3, "summary": "smile \ud83d end"}+ envelope = json.dumps({"input": answer})++ contents = _streamed_json_mode_contents((envelope[:9], envelope[9:30], envelope[30:]))++ assert json.loads("".join(contents).encode("utf-8")) == answer+++_CUT_STREAM_FRAGMENTS: Final = (+ pytest.param(+ json.dumps({"name": RESPONSE_FORMAT_TOOL_NAME, "parameters": _STREAMED_RISK_OBJECT})[:-1],+ id="held_envelope",+ ),+ pytest.param(json.dumps(_STREAMED_RISK_OBJECT), id="streamed_answer"),+)+++def _cut_stream_lines(sent: str) -> tuple[bytes, ...]:+ events: Final = _json_tool_events((sent[:9], sent[9:30], sent[30:]))+ return tuple(f"data: {json.dumps(event)}\n".encode() for event in events[:-2])+++def _cut_stream_iterator(sync_stream: bool, streaming_response: object) -> ModelResponseIterator:+ return ModelResponseIterator(+ streaming_response=streaming_response,+ sync_stream=sync_stream,+ json_mode=True,+ response_format_schema=response_format_schema(_STREAMED_RISK_SCHEMA),+ )++[email protected]("sent", _CUT_STREAM_FRAGMENTS)+def test_streamed_json_mode_text_is_delivered_when_the_stream_ends_before_the_block_stops(sent: str):+ iterator = _cut_stream_iterator(True, iter(_cut_stream_lines(sent)))++ assert "".join(chunk.choices[0].delta.content or "" for chunk in iterator) == sent++[email protected]("sent", _CUT_STREAM_FRAGMENTS)+async def test_async_streamed_json_mode_text_is_delivered_when_the_stream_ends_before_the_block_stops(sent: str):+ async def lines():+ for line in _cut_stream_lines(sent):+ yield line++ iterator = _cut_stream_iterator(False, lines())++ assert "".join([chunk.choices[0].delta.content or "" async for chunk in iterator]) == sent+++def test_streamed_json_mode_complete_envelope_is_unwrapped_when_the_stream_ends_before_the_block_stops():+ envelope = json.dumps({"name": RESPONSE_FORMAT_TOOL_NAME, "parameters": _STREAMED_RISK_OBJECT})++ iterator = _cut_stream_iterator(True, iter(_cut_stream_lines(envelope)))++ assert json.loads("".join(chunk.choices[0].delta.content or "" for chunk in iterator)) == _STREAMED_RISK_OBJECT+++def test_streamed_json_mode_answer_keyed_by_a_required_only_name_is_kept_whole():+ required_only_schema = {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["payload"]}+ encoded = json.dumps({"payload": {"id": "abc", "rows": 3}})++ contents = _streamed_json_mode_contents((encoded[:12], encoded[12:24], encoded[24:]), required_only_schema)++ assert "".join(contents) == encoded++def _json_tool_block_events(index: int, encoded: str) -> tuple[dict[str, object], ...]:return ({@@ -3202,6 +3288,30 @@ def test_streamed_json_mode_answer_split_into_one_partial_object_per_field_arrivassert contents[3] == blocks[0][:-1]+ "blocks",+ [+ pytest.param((_STREAMED_TIER_FIELD, _STREAMED_SUMMARY_FIELD), id="one_block_per_field"),+ pytest.param(+ tuple(json.dumps({name: value}) for name, value in _STREAMED_RISK_OBJECT.items()),+ id="one_partial_object_per_field",+ ),+ ],+)+def test_streamed_json_mode_split_answer_arrives_as_one_object_when_the_stream_ends_in_its_last_block(+ blocks: tuple[str, ...],+):+ message_start, *_ = _json_tool_events(())+ events = (+ message_start,+ *chain.from_iterable(_json_tool_block_events(index, encoded) for index, encoded in enumerate(blocks)),+ )[:-1]++ iterator = _cut_stream_iterator(True, iter(tuple(f"data: {json.dumps(event)}\n".encode() for event in events)))++ assert json.loads("".join(chunk.choices[0].delta.content or "" for chunk in iterator)) == _STREAMED_RISK_OBJECT++def test_streamed_json_mode_empty_object_then_field_blocks_arrives_as_one_object():blocks = ("{}", *(json.dumps({name: value}) for name, value in _STREAMED_RISK_OBJECT.items()))diff --git a/tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.py b/tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.pyindex ef8447712d6..32f18b952ac 100644--- a/tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.py+++ b/tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.py@@ -2251,6 +2251,38 @@ def test_effort_with_other_features():assert "thinking" in result+_OBJECT_OUTPUT_FORMAT: Final = {"type": "json_schema", "schema": {"type": "object", "properties": {}}}+++ ("output_format", "request_drop_params", "global_drop_params", "forwarded"),+ [+ pytest.param("json", True, False, False, id="string_dropped_under_request_drop_params"),+ pytest.param("json", None, True, False, id="string_dropped_under_global_drop_params"),+ pytest.param("json", None, False, True, id="string_forwarded_without_drop_params"),+ pytest.param(_OBJECT_OUTPUT_FORMAT, True, False, True, id="object_kept_under_drop_params"),+ ],+)+def test_anthropic_chat_drops_only_a_non_object_output_format_and_only_under_drop_params(+ output_format: object,+ request_drop_params: bool | None,+ global_drop_params: bool,+ forwarded: bool,+ monkeypatch: pytest.MonkeyPatch,+):+ monkeypatch.setattr(litellm, "drop_params", global_drop_params)++ result = AnthropicConfig().transform_request(+ model="claude-haiku-4-5",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params={"output_format": output_format},+ litellm_params={"drop_params": request_drop_params},+ headers={},+ )++ assert result.get("output_format") == (output_format if forwarded else None)++def test_anthropic_drop_params_strips_output_config_for_pre_4_5_models():"""``drop_params=True`` strips unsupported ``output_config`` for pre-4.5 models."""config = AnthropicConfig()@@ -7882,6 +7914,24 @@ def _json_tool_call(arguments: object) -> list[ChatCompletionToolCallChunk]:{"summary": "likes tea"},id="tool_name_envelope_on_a_schema_allowing_extra_keys",),+ pytest.param(+ {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["payload"]},+ {"payload": {"id": "abc", "rows": 3}},+ {"payload": {"id": "abc", "rows": 3}},+ id="key_listed_only_in_required",+ ),+ pytest.param(+ _RISK_SCHEMA,+ {"name": RESPONSE_FORMAT_TOOL_NAME, "arguments": {"input": _RISK_OBJECT}},+ _RISK_OBJECT,+ id="tool_name_envelope_around_an_input_wrapper",+ ),+ pytest.param(+ _PER_USER_SCHEMA,+ {"name": RESPONSE_FORMAT_TOOL_NAME, "parameters": _PER_USER_ANSWER},+ _PER_USER_ANSWER,+ id="tool_name_envelope_around_an_answer_with_one_allowed_key",+ ),],)def test_convert_tool_response_to_message_unwraps_only_an_unambiguous_schema_envelope(@@ -7896,6 +7946,31 @@ def test_convert_tool_response_to_message_unwraps_only_an_unambiguous_schema_envassert json.loads(message.content) == expected_content+def test_convert_tool_response_to_message_keeps_non_ascii_text_in_an_unwrapped_answer():+ answer = {"tier": 3, "summary": "Hôtel Lutetia, 東京"}++ message = AnthropicConfig.convert_tool_response_to_message(+ tool_calls=_json_tool_call({"input": answer}),+ response_format_schema=_schema(_RISK_SCHEMA),+ )++ assert message is not None+ assert "Hôtel Lutetia, 東京" in message.content+ assert json.loads(message.content) == answer+++def test_convert_tool_response_to_message_answer_with_a_lone_surrogate_stays_utf8_encodable():+ answer = {"tier": 3, "summary": "smile \ud83d end"}++ message = AnthropicConfig.convert_tool_response_to_message(+ tool_calls=_json_tool_call({"input": answer}),+ response_format_schema=_schema(_RISK_SCHEMA),+ )++ assert message is not None+ assert json.loads(message.content.encode("utf-8")) == answer++_TOO_DEEP_TO_DECODE: Final = "[" * 100_000 + "]" * 100_000diff --git a/tests/unit/llms/anthropic/pass_through/messages/test_anthropic_messages_structured_outputs.py b/tests/unit/llms/anthropic/pass_through/messages/test_anthropic_messages_structured_outputs.pyindex 670e3de5110..db3ff58d80a 100644--- a/tests/unit/llms/anthropic/pass_through/messages/test_anthropic_messages_structured_outputs.py+++ b/tests/unit/llms/anthropic/pass_through/messages/test_anthropic_messages_structured_outputs.py@@ -2,10 +2,16 @@Tests for structured outputs support in Anthropic /v1/messages endpoint."""+from collections.abc import Mapping+from typing import Final+import pytest++import litellmfrom litellm.llms.anthropic.pass_through.messages.transformation import (AnthropicMessagesConfig,)+from litellm.types.router import GenericLiteLLMParamsdef test_output_format_supported_and_transforms_correctly():@@ -109,3 +115,47 @@ def test_output_format_works_with_bedrock_and_azure():headers={},)assert "output_format" in azure_result+++_OBJECT_OUTPUT_FORMAT: Final = {"type": "json_schema", "schema": {"type": "object", "properties": {}}}+++def _request_with_output_format(+ output_format: object, litellm_params: GenericLiteLLMParams+) -> Mapping[str, object]:+ return AnthropicMessagesConfig().transform_anthropic_messages_request(+ model="claude-haiku-5-5",+ messages=[{"role": "user", "content": "What is 6 times 7?"}],+ anthropic_messages_optional_request_params={"max_tokens": 1024, "output_format": output_format},+ litellm_params=litellm_params,+ headers={},+ )++[email protected]("output_format", ["json", ["json_schema"], 42])+def test_malformed_output_format_is_dropped_under_drop_params(output_format: object) -> None:+ result: Final = _request_with_output_format(output_format, GenericLiteLLMParams(drop_params=True))++ assert "output_format" not in result+++def test_malformed_output_format_is_dropped_under_the_global_drop_params_flag(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(litellm, "drop_params", True)++ result: Final = _request_with_output_format("json", GenericLiteLLMParams())++ assert "output_format" not in result+++def test_object_output_format_is_kept_under_drop_params() -> None:+ result: Final = _request_with_output_format(_OBJECT_OUTPUT_FORMAT, GenericLiteLLMParams(drop_params=True))++ assert result["output_format"] == _OBJECT_OUTPUT_FORMAT+++def test_malformed_output_format_is_forwarded_for_the_provider_to_reject_without_drop_params() -> None:+ result: Final = _request_with_output_format("json", GenericLiteLLMParams())++ assert result["output_format"] == "json"diff --git a/tests/unit/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py b/tests/unit/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.pyindex 176dcfc86c9..38483b8a1fa 100644--- a/tests/unit/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py+++ b/tests/unit/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py@@ -7,6 +7,7 @@ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../..")))+from collections.abc import Mappingfrom typing import Finalfrom unittest.mock import patch@@ -551,3 +552,47 @@ async def test_outgoing_azure_request_sends_safeguards_with_the_dangerous_tool_usent: Final = received[0]assert "dangerous-tool-use-2026-09-03" in sent.headers["anthropic-beta"].split(","), dict(sent.headers)assert json.loads(sent.content)["safeguards"] == list(AUTO_MODE_SAFEGUARDS)+++async def _azure_request_body_for_output_format(output_format: object, drop_params: bool) -> Mapping[str, object]:+ received: Final[list[httpx.Request]] = []++ def foundry_answers(request: httpx.Request) -> httpx.Response:+ received.append(request)+ return _foundry_answer(request)++ upstream: Final = AsyncHTTPHandler(transport=httpx.MockTransport(foundry_answers))+ try:+ await litellm.anthropic.messages.acreate(+ max_tokens=256,+ messages=[{"role": "user", "content": "What is 6 times 7?"}],+ model="azure_ai/claude-sonnet-4-6",+ api_key="test-api-key",+ api_base="https://test-resource.services.ai.azure.com",+ output_format=output_format,+ drop_params=drop_params,+ client=upstream,+ )+ finally:+ await upstream.close()++ assert len(received) == 1, received+ return json.loads(received[0].content)++[email protected]("local_beta_headers_config")+async def test_outgoing_azure_request_drops_a_malformed_output_format_under_drop_params() -> None:+ body: Final = await _azure_request_body_for_output_format("json", drop_params=True)++ assert "output_format" not in body++[email protected]("local_beta_headers_config")+async def test_outgoing_azure_request_keeps_an_object_output_format_under_drop_params() -> None:+ output_format: Final = {"type": "json_schema", "schema": {"type": "object", "properties": {}}}++ body: Final = await _azure_request_body_for_output_format(output_format, drop_params=True)++ assert body["output_format"] == output_formatdiff --git a/tests/unit/llms/bedrock/chat/test_invoke_handler.py b/tests/unit/llms/bedrock/chat/test_invoke_handler.pyindex 069438e25c0..f3ceac1d93c 100644--- a/tests/unit/llms/bedrock/chat/test_invoke_handler.py+++ b/tests/unit/llms/bedrock/chat/test_invoke_handler.py@@ -1880,3 +1880,84 @@ async def test_converse_stream_thinking_merges_into_content_with_think_tags() ->"Hi I am Anthropic, I am a helpful assistant")assert [getattr(chunk.choices[0].delta, "reasoning_content", None) for chunk in chunks] == [None] * len(chunks)+++_PLACE_JSON_MODE_REQUEST: Final = json.dumps(+ {+ "tools": [+ {+ "name": "json_tool_call",+ "input_schema": {+ "type": "object",+ "properties": {"city": {"type": "string"}, "country": {"type": "string"}},+ "required": ["city", "country"],+ "additionalProperties": True,+ },+ }+ ]+ }+)++_CUT_JSON_TOOL_STREAM: Final = b"".join(+ _bedrock_event_stream_frame(event)+ for event in (+ {+ "type": "message_start",+ "message": {+ "id": "msg_cut_1",+ "type": "message",+ "role": "assistant",+ "model": "claude-haiku-5-5",+ "content": [],+ "stop_reason": None,+ "usage": {"input_tokens": 528, "output_tokens": 1},+ },+ },+ {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "tool_use", "id": "toolu_cut_1", "name": "json_tool_call", "input": {}},+ },+ {"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": '{"city"'}},+ {"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": ': "Paris", '}},+ {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "input_json_delta", "partial_json": '"country": "France"}'},+ },+ )+)+++def _cut_json_tool_stream_decoder() -> AWSEventStreamDecoder:+ return _stream_decoder(+ "anthropic",+ model="anthropic.claude-haiku-5-5",+ json_mode=True,+ sync_stream=True,+ response_format_schema=response_format_schema_from_request(_PLACE_JSON_MODE_REQUEST, json_mode=True),+ )+++def _streamed_content(chunks: Sequence[object]) -> str:+ return "".join(+ chunk.choices[0].delta.content or ""+ for chunk in chunks+ if isinstance(chunk, ModelResponseStream) and chunk.choices+ )+++def test_anthropic_invoke_stream_cut_before_the_json_tool_block_ends_sends_the_held_close() -> None:+ chunks: Final = list(_cut_json_tool_stream_decoder().iter_bytes(iter([_CUT_JSON_TOOL_STREAM])))++ assert json.loads(_streamed_content(chunks)) == {"city": "Paris", "country": "France"}+++async def test_async_anthropic_invoke_stream_cut_before_the_json_tool_block_ends_sends_the_held_close() -> None:+ async def _chunks() -> AsyncIterator[bytes]:+ yield _CUT_JSON_TOOL_STREAM++ chunks: Final = [chunk async for chunk in _cut_json_tool_stream_decoder().aiter_bytes(_chunks())]++ assert json.loads(_streamed_content(chunks)) == {"city": "Paris", "country": "France"}diff --git a/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py b/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.pyindex 113ddcfe2a9..ae9b9684f2d 100644--- a/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py+++ b/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py@@ -1,6 +1,7 @@import copyimport jsonimport os+from collections.abc import Mappingfrom typing import Finalfrom unittest.mock import MagicMock, patch@@ -537,6 +538,44 @@ def test_messages_request_moves_output_format_into_output_config():assert result["output_config"] == {"effort": "high", "format": output_format}+_CALLER_OUTPUT_CONFIG: Final = {+ "effort": "high",+ "format": {"type": "json_schema", "schema": {"type": "object", "properties": {"answer": {"type": "integer"}}}},+}+++def _messages_request_with_output_format(output_format: object, drop_params: bool) -> Mapping[str, object]:+ return VertexAIPartnerModelsAnthropicMessagesConfig().transform_anthropic_messages_request(+ model="claude-opus-4-6",+ messages=[{"role": "user", "content": "What is 6 times 7?"}],+ anthropic_messages_optional_request_params={+ "max_tokens": 1024,+ "output_format": output_format,+ "output_config": copy.deepcopy(_CALLER_OUTPUT_CONFIG),+ },+ litellm_params=GenericLiteLLMParams(drop_params=drop_params),+ headers={},+ )++[email protected]("output_format", ["json", ["json_schema"], 42])+def test_messages_request_drops_a_malformed_output_format_under_drop_params(output_format: object):+ result = _messages_request_with_output_format(output_format, drop_params=True)++ assert "output_format" not in result+ assert result["output_config"] == _CALLER_OUTPUT_CONFIG++[email protected]("output_format", ["json", ["json_schema"], 42])+def test_messages_request_rejects_a_malformed_output_format_without_drop_params(output_format: object):+ import litellm++ with pytest.raises(litellm.UnsupportedParamsError) as error:+ _messages_request_with_output_format(output_format, drop_params=False)++ assert error.value.status_code == 400++def test_provider_config_manager_reuses_vertex_anthropic_messages_config_instance():"""Regression test: repeated provider config lookups for the same Vertex Claude modeldiff --git a/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.py b/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.pyindex ace24c8a3f4..21bda6f0345 100644--- a/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.py+++ b/tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_transformation.py@@ -918,6 +918,44 @@ def test_sanitize_folds_output_format_into_output_config(model: str, data: dict,assert request["output_config"] == expected_output_config+def _vertex_chat_request_with_output_format(+ output_format: object, litellm_params: Mapping[str, object]+) -> Mapping[str, object]:+ return VertexAIAnthropicConfig().transform_request(+ model="claude-opus-4-6",+ messages=[{"role": "user", "content": "What is 6 times 7?"}],+ optional_params={"max_tokens": 64, "output_format": output_format},+ litellm_params=dict(litellm_params),+ headers={},+ )+++def test_vertex_chat_request_drops_a_malformed_output_format_under_per_request_drop_params():+ request: Final = _vertex_chat_request_with_output_format("json", {"drop_params": True})++ assert "output_format" not in request+ assert "output_config" not in request+++def test_vertex_chat_request_drops_a_malformed_output_format_under_the_global_drop_params_flag(+ monkeypatch: pytest.MonkeyPatch,+):+ monkeypatch.setattr(litellm, "drop_params", True)++ request: Final = _vertex_chat_request_with_output_format("json", {})++ assert "output_format" not in request+ assert "output_config" not in request+++def test_vertex_chat_request_rejects_a_malformed_output_format_without_drop_params_naming_the_proxy_setting():+ with pytest.raises(litellm.UnsupportedParamsError) as error:+ _vertex_chat_request_with_output_format("json", {})++ assert error.value.status_code == 400+ assert "litellm_settings:\n drop_params: true" in str(error.value)++def test_vertex_ai_native_response_format_reaches_vertex_as_output_config_format(local_model_cost_map):config = VertexAIAnthropicConfig()schema: Final = {"type": "object", "properties": {"result": {"type": "string"}}, "required": ["result"]}