Repository navigation
fix(vertex_ai): unwrap tool-emulated json_schema envelopes and send output_config.format for Claude - #45871
Conversation
…utput_config.format for Claude Vertex AI Claude deployments that emulate response_format through a forced tool sometimes nest the schema object under an extra key such as `parameters` or `input`, and that envelope reached message.content with a 200. The converter now unwraps exactly one nested object that matches the schema, leaving a payload that is itself schema-shaped alone. Native structured-output rows sent the deprecated top-level `output_format`, which Vertex rejects with a 400. The Vertex request now carries it as `output_config.format`, with an explicit caller value winning.
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
| if payload_object is None or _is_schema_object(payload_object, schema, property_names): | ||
| return payload | ||
| nested_objects: Final = tuple(as_json_object(value) for value in payload_object.values()) | ||
| candidates: Final = tuple( | ||
| nested for nested in nested_objects if nested is not None and _is_schema_object(nested, schema, property_names) | ||
| ) | ||
| return candidates[0] if len(candidates) == 1 else payload |
There was a problem hiding this comment.
Valid response fields disappear
For schema {"type":"object","properties":{"score":{"type":"integer"}},"additionalProperties":true}, the valid response {"meta":{"score":7},"label":"keep"} becomes {"score":7}. The outer object has no declared property names, so the helper mistakes it for a wrapper and discards meta and label. Check whether the whole object satisfies the schema before removing a wrapper.
There was a problem hiding this comment.
53377d8 leaves any schema-accepted payload untouched and unwraps only when exactly one nested object matches the schema
There was a problem hiding this comment.
Still holds at 71e8341, now by structure: an answer with two or more undeclared keys comes back as sent, so meta and label stay
| content: Final = ( | ||
| payload | ||
| if response_format_schema is None | ||
| else unwrap_response_format_envelope(payload, response_format_schema) | ||
| ) |
There was a problem hiding this comment.
The wrapper fix does not cover stream=True. The streaming caller still invokes convert_tool_response_to_message without response_format_schema, so the new helper is skipped. A response such as {"input":{"tier":3,"summary":"ok"}} still reaches callers with its wrapper, while the same non-streaming response returns the inner object. Pass the schema into the streaming path and account for JSON split across chunks.
There was a problem hiding this comment.
53377d8 holds a streamed wrapper until the block ends and emits the unwrapped object, same as the non-stream path
Merging this PR will not alter performance
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
… and tool-name wrappers
…_structured_output # Conflicts: # tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py # tests/unit/llms/bedrock/chat/test_invoke_handler.py
| tool_call_payload: Final = _tool_call_envelope_payload(payload_object, tool_name) | ||
| if tool_call_payload is not None: | ||
| return tool_call_payload |
There was a problem hiding this comment.
🔴 Valid structured answers lose required fields
When a valid answer has name: "json_tool_call" beside one object field, unwrap_response_format_envelope strips its outer fields. The returned answer no longer matches the requested schema.
Learn more
The tool-emulated JSON response can itself use name and an object-valued property. _tool_call_envelope_payload treats any matching tool name plus one object as an envelope before ResponseFormatSchema.accepts checks the complete answer. This changes a valid answer into its nested property, including on the non-streaming path and when the streaming buffer flushes.
Example: For a schema requiring name and parameters, the valid answer {"name":"json_tool_call","parameters":{"age":36}} becomes {"age":36} rather than remaining unchanged.
Recommended fix: Check whether the outer object satisfies ResponseFormatSchema before applying the named-envelope shortcut in unwrap_response_format_envelope. Keep the named-envelope fallback for objects the schema does not accept, including schemas without required properties.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
A name equal to our tool's name is never legitimate data, and accepts-first would keep that wrapper on any permissive schema with a name property
There was a problem hiding this comment.
Withdrawn. 86450fe now checks schema acceptance first, so a schema-accepted payload keeps its tool-named wrapper as you suggested
There was a problem hiding this comment.
71e8341 never treats a key the schema declares as a wrapper, so a declared field beside our tool's name keeps the whole answer
| first_value: Final = _FIRST_NAME_VALUE.match(buffered_json) | ||
| if first_value is None: | ||
| return "undecided" if _NAME_VALUE_PREFIX.match(buffered_json) else "pass_through" | ||
| return "hold" if first_value.group(1) == tool_name else "pass_through" |
There was a problem hiding this comment.
🔴 Streamed answers retain some JSON envelopes
When an envelope starts with a schema property like name, _envelope_verdict passes it through unless its value names the tool. A nested schema-shaped answer then remains wrapped in the stream, unlike the non-streaming response.
Learn more
Streaming decides whether to release content from the first key and, for name, from its first value. A schema can include name even when the model puts the actual schema object inside another field and names the schema rather than the tool. unwrap_response_format_envelope sees the complete object and selects its single schema-shaped child, while _envelope_verdict has already released the outer object and cannot correct it.
Example: With a schema requiring name and age, {"name":"Person","parameters":{"name":"Ada","age":36}} streams unchanged because Person differs from json_tool_call. The non-streaming result is {"name":"Ada","age":36}.
Recommended fix: Hold ambiguous prefixes until the complete object can be classified using the same schema-aware decision as unwrap_response_format_envelope, or use a streaming parser that can distinguish a top-level schema object from its envelope before emitting bytes.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Fixed in 86450fe: the held stream now decides at the second top-level key, so a schema-named wrapper is held and unwrapped like non-stream
There was a problem hiding this comment.
Superseded by 71e8341. Neither path unwraps a wrapper with a foreign name now, so stream and non-stream return the same object
| self._response_format_buffer = self._response_format_buffer + fragment | ||
| if self._response_format_verdict == "hold": | ||
| return "" |
There was a problem hiding this comment.
🔴 Large JSON streams incur quadratic copying
When _response_format_verdict holds an envelope, each fragment copies the entire accumulated buffer. Long fine-grained JSON streams spend quadratic time copying content before clients receive the final answer.
Learn more
Fine-grained Anthropic tool streaming supplies JSON arguments in successive partial_json fragments through _content_block_delta_helper. Once the first key is not a schema property, _envelope_verdict selects hold. Every new fragment then allocates a string containing the entire answer so far. An answer of N characters delivered in many small fragments copies a quadratic number of characters, and held content is not returned until the block closes.
Example: A 100 KB wrapped answer delivered in 10,000 small fragments requires roughly 500 MB of cumulative string copying, before parsing or emitting its final chunk.
Recommended fix: Store held fragments in a list and join them once in _flush_response_format_buffer. Keep only a bounded prefix for the early verdict instead of rebuilding the full held string on each delta.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Fixed in 86450fe: held fragments go into one StringIO buffer, and a stream undecided after 4096 bytes is held without re-scanning
…reams at the second key An answer the json_schema accepts is returned as is before any envelope rule runs, the tool-name wrapper is unwrapped only when the schema rejects it, a malformed schema turns the unwrap off, a streamed answer whose first key is a schema property named name or tool_name waits for its second key before streaming, the held fragments go through a StringIO, and a prefix that stays undecided past 4 KB is held to the end
|
@litereview code-review |
✅ code-reviewScope: full · Full PR review. READY · Test evidence VERIFIED · 4/5 No correctness findings. The earlier open finding about Claude Platform and Bedrock Mantle streams no longer applies to this PR. The description now limits the stream unwrap to direct Anthropic, Azure AI Anthropic, Bedrock invoke and Vertex AI. Checks and execution details
Evidence: the PR description contains inspectable manual E2E evidence:
Tested commit matches head: the GitHub compare from Gaps: the linked Google Sheet and Drive raw jsonl returned 401 or a sign-in page. I relied on the inline outputs in the description. I did not run the integration suite, which needs Postgres, Redis and the owned proxy.
Result: 726 passed.
The remaining mismatches fall into 2 groups:
I found no mismatch on schemas with required keys, the case the PR targets.
View review · Reviewed |
…am iterator gets the schema
|
Mantle and Claude Platform streams already emit tool_calls deltas on the merge base, a separate bug listed in Caveats. CircleCI does not run on PRs |
|
@litereview code-review |
✅ code-reviewScope: full · Full PR review. READY · Test evidence: VERIFIED · 4/5 No correctness findings. Prior finding withdrawn: "Claude Platform and Bedrock Mantle streams still return the json_tool_call wrapper". The PR doesn't change those streams. On the merge base they already stream the wrapper or send it as
That leaves a separate, known bug. This PR didn't cause it. Checks and execution details
Integration tests run on the head commit: I set up local Postgres 15 and Redis, ran INTEGRATION_WORKERS=2 python tests/integration/run.py providers tests/integration/providers/test_vertex_anthropic_structured_output_wire.pyResult: 108 passed in 142.7s, with no skips ( Where the fixtures come from: The scripted wrapper shapes ( The manual runs used commits earlier than the head (f32acde). For the head itself, the evidence comes from the integration run above.
The non-stream cases for both providers pass.
View review · Reviewed |
|
bugbot run |
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 1 · PR risk: 0/10 |
…hema validation The unwrap now reads only the schema's top-level property names. A lone undeclared key holding an object, alone or beside a name equal to the json tool's own name, is the envelope, and the unwrap repeats while the inner object shares no key with the schema. jsonschema and referencing are no longer imported on the request path. The stream holds only an answer that opens with the tool's name or with an undeclared key holding an object, and a schema without top-level properties streams as it arrives.
|
@litereview code-review |
|
…eys and stream held text as sent A schema that allows undeclared keys and requires none now keeps an undeclared wrapper key on both the stream and non-stream paths. When no envelope is found, the held stream text is now sent exactly as the model wrote it. On Vertex /v1/messages, output_format now wins over output_config.format when both are set, which matches the Anthropic adapter.
|
@litereview code-review |
|
bugbot run |
| return "undecided" | ||
| if first_key.group(1) in schema.property_names or not schema.property_names or schema.accepts_a_lone_undeclared_key: | ||
| return "pass_through" | ||
| return _first_value_verdict(buffered_json[first_key.end() :], schema) |
There was a problem hiding this comment.
Stream skips values unwrap on open schemas
Medium Severity
_prefix_verdict pass-throughs any answer that does not open with the json tool's name when the schema has no properties or accepts_a_lone_undeclared_key. Non-stream still applies the legacy values fallback and will unwrap {"values": {...}} on json_object mode, so stream and non-stream return different objects.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 3d3761a. Configure here.
There was a problem hiding this comment.
Pre-existing. Base also streams the values wrapper as sent when arguments arrive in several deltas, and non-stream is unchanged. Listed as a Low caveat
| ) -> Mapping[str, object] | None: | ||
| if output_format is None: | ||
| return output_config | ||
| return {**(output_config or {}), "format": output_format} |
There was a problem hiding this comment.
Medium · Vertex /v1/messages overwrites the caller's explicit output_config.format with output_format
Suppose you call /v1/messages on a Vertex AI Claude deployment and send both output_format and output_config.format. sanitize_vertex_anthropic_output_params replaces your output_config.format with output_format, so Vertex enforces a different schema from the one you set explicitly.
The PR description says: "An explicit output_config.format from the caller wins over a mapped output_format." The PR's integration test test_vertex_messages_keeps_the_callers_output_config_format_over_output_format asserts the same thing. The code does the opposite:
return {**(output_config or {}), "format": output_format}The docstring and the unit case output_format_wins_over_output_config_format encode this reversed rule too. On head, the integration test fails: the body that reached the scripted Vertex peer lacked the caller schema's "title": "callers".
Smallest fix: only fill format from output_format when the existing output_config.format is absent or None. Then update the unit case and docstring to match.
Integration run on head: FAILED test_vertex_messages_keeps_the_callers_output_config_format_over_output_format. The delivered output_config.format.schema was missing 'title': 'callers'.
PR description, Decisions: "An explicit output_config.format from the caller wins over a mapped output_format, and a null one counts as absent"
Unit test test_sanitize_folds_output_format_into_output_config[output_format_wins_over_output_config_format] asserts the reverse rule and passes.
Latest summary by code-review · View this review · Reviewed 3d3761aaa615
There was a problem hiding this comment.
This is intended. output_format wins when both are set, like the Anthropic adapter, the Responses adapter and bedrock/common_utils.py. The wire test matches since ef1c19f
There was a problem hiding this comment.
Finding withdrawn
I flagged a mismatch between the PR's stated rule and the code. At ef1c19fbd6, the stated rule matches the code: when a /v1/messages caller sends both output_format and output_config.format, output_format wins. The PR description, the docstring, the unit test and the integration test now agree on this. Bedrock's legacy fold uses the same precedence. Neither the code nor the tests show a defect.
output_params_utils.py _fold_output_format_into_output_config returns {**(output_config or {}), "format": output_format}. The docstring says: "When both are set, output_format wins, as it does in the Anthropic adapter."
PR description, Decisions section: "When a /v1/messages caller sets both output_format and output_config.format, output_format wins, as it already does in the Anthropic adapter, the Responses adapter and Bedrock's own fold of the legacy field"
The integration test tests/integration/providers/test_vertex_anthropic_structured_output_wire.py:1418 is now test_vertex_messages_output_format_wins_over_the_callers_output_config_format. It expects {"format": _OUTPUT_FORMAT} on the wire, with and without effort.
Unit case output_format_wins_over_output_config_format expects {"format": _STRUCTURED_FORMAT}. I did not run it locally because pytest is not installed in this sandbox. This conclusion comes from reading the code and tests.
litellm/llms/bedrock/common_utils.py:273-275 sets schema_format = legacy_output_format if isinstance(legacy_output_format, dict) else output_config_format, so the legacy field takes precedence there too.
A leftover nit, not a defect: row N9 of the PR description's test table still says "caller's wins" and uses the old test name.
GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.
Reviewed ef1c19fbd60f · View follow-up
| return [payload] | ||
| case "deep": | ||
| return _nest(payload, 60) | ||
| case "other_tool": |
There was a problem hiding this comment.
Low · Integration tests still expect a foreign tool_name wrapper to come back unchanged
The PR's own integration suite fails on head. Two other_tool cases expect {"tool_name": "other_tool", "parameters": {...}} to come back as sent. The code now unwraps it to {"tier": 2, "summary": ...} on both the stream and non-stream paths.
The unwrap matches the documented rule: "On a schema with required keys that does not declare it, a foreign name or tool_name is a label like any other string." _label_keys in base_utils.py treats tool_name as a label because _SCHEMA has required keys. The test expectation is stale, not the product.
This still blocks merge. The suite that is supposed to prove the change is red. Update the other_tool expectations in both tests, or move other_tool out of the pass-through set.
FAILED test_vertex_chat_stream_json_schema_content_is_the_schema_object[other_tool]: got {'tier': 2, 'summary': ...}, expected the tool_name/parameters wrapper
FAILED test_vertex_chat_json_schema_unwraps_a_tool_named_envelope_only_around_one_object[other_tool]: same mismatch on the non-stream path
Latest summary by code-review · View this review · Reviewed 3d3761aaa615
There was a problem hiding this comment.
Agreed, those expectations were stale. Since ef1c19f both other_tool cases expect the unwrapped schema object, matching the documented label rule
There was a problem hiding this comment.
Finding withdrawn
The reply is correct, and I verified it against the current code. In tests/integration/providers/test_vertex_anthropic_structured_output_wire.py, _expected() now lists "other_tool" among the shapes that return _payload(marker_hex), which is {"tier": 2, "summary": marker}. Both tests use that expectation: test_vertex_chat_stream_json_schema_content_is_the_schema_object and test_vertex_chat_json_schema_unwraps_a_tool_named_envelope_only_around_one_object.
The code produces the same result on both paths:
- Non-stream:
unwrap_response_format_envelopeinlitellm/llms/base_llm/base_utils.pyreturns the inner object. - Stream:
_envelope_verdictinlitellm/llms/anthropic/chat/handler.pyholds the answer._held_answerthen emits the unwrapped object.other_toolsits in_HELD_STREAM_SHAPES, so the test expects one frame, and the held path sends one.
I checked this by running the helpers directly. I did not run the gateway integration tests themselves.
_expected() (line ~327) now includes | "other_tool" in the branch that returns _payload(marker_hex). _payload (line 209) returns {"tier": 2, "summary": marker_hex}.
Ran unwrap_response_format_envelope({'tool_name':'other_tool','parameters':{'tier':2,'summary':'x'}}, schema(_SCHEMA), 'json_tool_call'). Output: {'tier': 2, 'summary': 'x'}.
Ran _envelope_verdict on growing prefixes of the same JSON. Results: undecided at 10, 25 and 40 chars, then hold on the full text. _held_answer returned {"tier": 2, "summary": "x"}. This matches other_tool in _HELD_STREAM_SHAPES, which expects 1 frame.
test_vertex_chat_malformed_response_format_schema_keeps_the_tool_input[other_tool] still expects the raw tool input. That is consistent with the code: when properties is malformed, response_format_schema returns None and no unwrap runs.
I did not run the full integration suite. It requires PostgreSQL, Redis and the owned proxy described in tests/integration/README.md. The verdict rests on the test-file changes and the direct helper runs above.
GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.
Reviewed ef1c19fbd60f · View follow-up
…en held streams and output_format precedence
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
1 issue from previous review remains unresolved.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit ef1c19f. Configure here.
|
Follow-up #46331 fixes what this left open, streamed answers on Bedrock Mantle and Claude Platform, split answers on Vertex AI, and Bugbot's streamed wrapper finding |
* chore(litellm): bump proxy v1.92.0 -> v1.108.13 (LTS) v1.108.13 carries BerriAI/litellm#45871 and #46337: on vertex_ai Claude the response_format json_tool_call answer is unwrapped from invented envelopes ({"object": ...}, {"value": ...}, {"json_value": ...}). v1.92.0 only unwrapped "values", which hit 5 of 88 ingestbuddy tax extractions on claude-sonnet-5 (ingestbuddy#155). Pinned to the multi-arch index digest of the v1.108.13 tag (same as the current lts tag). The proxy applies 90 additive Prisma migrations at startup; a rehearsal on a copy of the prod schema showed v1.92.0 still boots on the migrated schema, so a pin revert is the rollback. Also notes on the pin that Renovate does not track digest-only refs, which is why the image sat on v1.92.0 since the digest pin of 2026-07-24. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(litellm): pin as -lts tag plus digest so Renovate tracks it `tag: v1.108.13-lts@sha256:65a9...` resolves to the same index digest as before (v1.108.13, v1.108.13-lts and lts all point to it), so the content stays digest-pinned as a4730b4 intended. The tag lets the app-template regex manager see the image again; with docker versioning the -lts suffix restricts updates to the LTS line. The LiteLLM packageRule in .github/renovate/base.json5 turns automerge off for it. Rendered with app-template 5.3.0: ghcr.io/berriai/litellm:v1.108.13-lts@sha256:65a9631f... Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>


TLDR
Problem this solves:
json_schemaanswers sometimes come back wrapped underparameters,input, or a similar keyoutput_format, so Vertex answers 400How it solves it:
nameortool_nameequal to the json tool's own name, or beside undeclared string labels such asparameter_namewhen the schema has required keysoutput_formatto Vertex AI Claude asoutput_config.formatDecisions made on purpose:
jsonschemaimport, metaschema check or$refresolution runs on the request path. That works on everyjsonschemathe pin allows and cannot be stalled by a large schemainputorparameterskeeps it{"parameter_name": "RiskAssessment", "parameter_value": {...}}and{"$FUNCTION_NAME": "json_tool_call", "PARAMETER_VALUE": {...}}unwrap. Every key in such a payload is undeclared, so it holds none of the required keys and can never be a valid answer as sent{"meta": {...}, "label": "keep"}on an open schema with no required keys keeps every fieldadditionalPropertiesset totrueor a schema, orpatternProperties) and requires none keeps a lone undeclared key whole, so{"user_1": {...}}on a per-user map comes back as sent on both paths. Only anameortool_nameequal to our tool's name is still set aside thereadditionalPropertieskey counts as closed for this, although JSON Schema reads it as open, because generated schemas such as Pydantic's usually leave it out and a model-added wrapper around schema keys is far more likely there than a real undeclared keynameortool_nameequal to the json tool's name is set aside even on a schema with no properties or one that declaresname, since no answer names our tool by accident. The value beside it may also be a JSON-encoded object stringnamewith any other value is ordinary data when the schema declaresnameor has no required keys, so{"name": "Person", "parameters": {...}}on a Person schema comes back as sent on both paths, as on the merge base. On a schema with required keys that does not declare it, a foreignnameortool_nameis a label like any other string. The stream waits for the key after that string before it decides, so both paths still agreejson.loadscome back as sent instead of raising, both for the whole payload and for a JSON-encoded string beside our tool's name. The merge base raised on the first and never parsed the second{"parameter": {"value": {...}}}reaches the caller as the inner object. A layer that names our tool stops the walk there (see Caveats)enable_json_schema_validationthen reports the missing key on the object the schema describesproperties(a map,anyOfor$refroot) streams as it arrives unless the answer opens with our tool's namevaluesunwrap stays as the fallback when no envelope is found, except when the schema itself declaresvalues, where{"values": [...]}now comes back as sent instead of as the bare arrayaffected_systemskey out of 9 of 20 interleaved live calls, against 2 of 20 incomplete answers without it and 3 of 20 at the merge base (all 60 rows), so the tool keeps the merge base's name-and-schema shape/v1/messagescaller sets bothoutput_formatandoutput_config.format,output_formatwins, as it already does in the Anthropic adapter, the Responses adapter and Bedrock's own fold of the legacy fieldoutput_formatfirst while Vertex sends onlyoutput_config.format, since Bedrock still accepts the old fieldtool_callsdeltas instead of content, which is a separate bug. The Bedrock converse and Databricks converters keep their own per-key unwrap (see Caveats)enable_json_schema_validationnow validates the unwrapped object, which is the object the schema describesUser Flow
Before: a developer asking a Vertex AI Claude deployment for a
json_schemaanswer gets the object wrapped under an extra key, whether they read the whole answer or stream it, or a 400 on the native deployment, so their parser fails"model": "claude-opus-5"(avertex_ai/claude-opus-5deployment) and"response_format": {"type": "json_schema", "json_schema": {"name": "RiskAssessment", "schema": {...}}}finish_reason: stop, butmessage.contentis{"name": "json_tool_call", "parameters": {"tier": 3, ...}}on most calls, so parsing it as aRiskAssessmentfails on the missing top-level keys"stream": trueand join thedelta.contentchunks: the joined text is the same{"name": "json_tool_call", "parameters": {...}}wrapper"model": "claude-opus-5-5"(avertex_ai/claude-opus-5-5deployment, native structured outputs) and get HTTP 400output_format: This field is deprecated. Use 'output_config.format' instead.on every callAfter: the same requests come back as the schema object itself, streamed or not, and the native deployment reaches Vertex with the current field
"model": "claude-opus-5"and the sameresponse_formatmessage.contentas{"tier": 3, "risk_level": "high", ...}, the schema's own keys at the top level, so the parse succeeds"stream": true: thedelta.contentchunks join to{"tier": 3, "risk_level": "high", ...}and the last chunk carriesfinish_reason: stop"model": "claude-opus-5-5"and it reaches Vertex asoutput_config.format: a project whose org policy allows structured outputs gets HTTP 200 with a schema-conformant object, and one that does not gets Vertex's own 400 namingconstraints/vertexai.allowedPartnerModelFeaturesinstead of the deprecation errorLinear ticket
Resolves LIT-9409
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more@greptileaito re-request a review after pushing changes)Delays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Last updated: ef1c19f. QA and /live-pr-risk ran on 3d3761a, the last commit with a product diff
Both legs ran at the same time against two live LiteLLM proxies in front of real Vertex AI Claude on project
vertex-check-481318, locationglobal. Each proxy ran 2 uvicorn workers with no DB from its own worktree and.venv, Before from 464a4db on port 32069 and After from 3d3761a on port 48959. The tool-emulation cases (claude-sonnet-5 and claude-opus-5) use the OpenAI Python SDK 2.33.0 on/v1/chat/completionsand/v1/responses, streamed and not. Oneqa_cases.pyrun per case sends call i to both proxies at the same moment, 3 calls in flight per leg. TheRiskAssessmentcases send the exact messages and 8-field schema ofchat.jsonbelow, with nomax_tokens. Each answer is classed by the shallowest object in it that holds all 8 required keys.plainmeans that object is the top level,wrapped_depth1means it sits one level down under the keys inwrapper, andincompletemeans no object holds all 8. A stream is classed on its joined content deltas, with its chunk count and first-chunk timeThree more cases cover what 3d3761a changes, all on
/v1/chat/completionswith system messageYou are a hotel data assistant. Answer only with the requested JSON.lone_key_opus5sends theHotelRecordschema below, which allows extra keys and requires none, andkept_wholemeans the asked-forZRH-01is still the only top-level key.held_textsendsHotelNotesand asks for an undeclared, accentedhotel_notesobject beforesummary. claude-opus-5 writeshotel_notesfirst, so the proxy holds the stream until it can rule out an envelope. claude-sonnet-5 putssummaryfirst, so it is a control with no hold.literal_textmeanshotel_notescomes first with literal accents and no\uescape. Every call is one row in this sheet tab, and the raw jsonl per case and leg is in this folderThe config has this entry for each of claude-opus-5, claude-sonnet-5, and claude-opus-5-5, and a small launcher drops
DATABASE_URLand starts the proxy with the arguments below:Client calls, per case:
{"hotel_record": {"type": "object", "properties": {"name": {"type": "string"}, "city": {"type": "string"}, "rooms": {"type": "integer"}}, "additionalProperties": true}, "hotel_notes": {"type": "object", "properties": {"summary": {"type": "string"}}, "required": ["summary"], "additionalProperties": true}}The
lone_keyuser message isGive me the record for one hotel: Hotel Limmat in Zurich, 120 rooms, property code ZRH-01. The JSON object must have exactly one top-level key, the property code "ZRH-01", and its value must be an object with the fields name, city, and rooms. Do not put name, city, or rooms at the top level.Theheld_textuser message isWrite notes for three hotels: Hôtel Lutèce in Paris, Gasthof Zürichsee in Zürich, and Ryōkan Kyō-no-yado in Kyōto. The JSON object's FIRST key must be "hotel_notes": an object that maps each hotel's exact name, accents included, to a one-line note written in that hotel's local language with its accented characters. After hotel_notes, put "summary", one English sentence.The native claude-opus-5-5 loops ran with curl right after, 5 calls in a row per loop with both legs at the same time. The project's org policy allows
claude-opus-5-5:structured_outputs.chat_stream.jsonischat.jsonwith"stream": true, andmessages.jsonsends the schema under a top-leveloutput_format.messages_both.jsonadds anoutput_config.formatthat asks forverdictandreasoninstead, so the answer's keys show which format the proxy sent. Themessagesloop is the last loop below with-d @messages.jsonchat.json
{ "model": "claude-opus-5-5", "max_tokens": 1024, "messages": [ { "role": "system", "content": "You are a change-risk reviewer for a hotel group's IT team. Keep every string under 25 words." }, { "role": "user", "content": "Change request: move the loyalty-points ledger database from a self-managed PostgreSQL 13 cluster to a managed cloud database over a weekend window, with a planned 2-hour read-only period. Assess the risk." } ], "response_format": { "type": "json_schema", "json_schema": { "name": "RiskAssessment", "schema": { "$defs": { "Finding": { "properties": { "title": { "title": "Title", "type": "string" }, "severity": { "enum": [ "low", "medium", "high" ], "title": "Severity", "type": "string" }, "detail": { "title": "Detail", "type": "string" } }, "required": [ "title", "severity", "detail" ], "title": "Finding", "type": "object" } }, "properties": { "tier": { "title": "Tier", "type": "integer" }, "risk_level": { "enum": [ "low", "medium", "high" ], "title": "Risk Level", "type": "string" }, "score": { "title": "Score", "type": "integer" }, "summary": { "title": "Summary", "type": "string" }, "affected_systems": { "items": { "type": "string" }, "title": "Affected Systems", "type": "array" }, "findings": { "items": { "$ref": "#/$defs/Finding" }, "title": "Findings", "type": "array" }, "rollback_plan": { "title": "Rollback Plan", "type": "string" }, "requires_downtime": { "title": "Requires Downtime", "type": "boolean" } }, "required": [ "tier", "risk_level", "score", "summary", "affected_systems", "findings", "rollback_plan", "requires_downtime" ], "title": "RiskAssessment", "type": "object" } } } }messages.json
{ "model": "claude-opus-5-5", "max_tokens": 1024, "system": "You are a change-risk reviewer for a hotel group's IT team. Keep every string under 25 words.", "messages": [ { "role": "user", "content": "Change request: move the loyalty-points ledger database from a self-managed PostgreSQL 13 cluster to a managed cloud database over a weekend window, with a planned 2-hour read-only period. Assess the risk." } ], "output_format": { "type": "json_schema", "schema": { "$defs": { "Finding": { "properties": { "title": { "title": "Title", "type": "string" }, "severity": { "enum": [ "low", "medium", "high" ], "title": "Severity", "type": "string" }, "detail": { "title": "Detail", "type": "string" } }, "required": [ "title", "severity", "detail" ], "title": "Finding", "type": "object", "additionalProperties": false } }, "properties": { "tier": { "title": "Tier", "type": "integer" }, "risk_level": { "enum": [ "low", "medium", "high" ], "title": "Risk Level", "type": "string" }, "score": { "title": "Score", "type": "integer" }, "summary": { "title": "Summary", "type": "string" }, "affected_systems": { "items": { "type": "string" }, "title": "Affected Systems", "type": "array" }, "findings": { "items": { "$ref": "#/$defs/Finding" }, "title": "Findings", "type": "array" }, "rollback_plan": { "title": "Rollback Plan", "type": "string" }, "requires_downtime": { "title": "Requires Downtime", "type": "boolean" } }, "required": [ "tier", "risk_level", "score", "summary", "affected_systems", "findings", "rollback_plan", "requires_downtime" ], "title": "RiskAssessment", "type": "object", "additionalProperties": false } } }Before (464a4db)
Raw output covers the customer's flow and what 3d3761a changes, and the table and the sheet tab have every case
chat completions, claude-opus-5 (tool emulation), the customer's flow
CONC=3 python qa_cases.py chat_opus5 24 . base=http://127.0.0.1:32069 head=http://127.0.0.1:48959, one run for both legsCall 16's
message.content, as the client got it:Native structured outputs, claude-opus-5-5 (curl)
PORT=32069Permissive schema with one undeclared key, claude-opus-5, streaming
lone_key_opus5_stream 6, andlone_key_opus5 6without streamingZRH-01stays the only top-level key on all 6 streams, 9 chunks each. The joined stream is the last line:Stream that starts with an undeclared key and accented text, claude-opus-5
held_text_opus5_stream 6, andheld_text_sonnet5_stream 4as the controlhotel_notesand stream in 66 to 77 chunks, the first 4.0 to 5.2 s after the request, with literal accents:Call 0's joined
delta.content, opening:After (3d3761a)
chat completions, claude-opus-5 (tool emulation), the customer's flow
message.content:Call 16's
message.content, as the client got it:Native structured outputs, claude-opus-5-5 (curl)
PORT=48959output_formatschema's 8 keys on all 5 calls, notverdictandreason, sooutput_formatwon. The first line of the chat and both-formats loops:Permissive schema with one undeclared key, claude-opus-5, streaming
ZRH-01stays the only top-level key on all 6 streams, so the proxy did not unwrap it. Each stream arrives in 8 chunks, the first 1.5 to 2.0 s after the request, so it was not held. The joined text is the same as Before:Stream that starts with an undeclared key and accented text, claude-opus-5
hotel_notes, keeps the accents as literal characters with no\uescape, and keeps the model's own mixed spacing, which a re-serialization would have changed:Call 0's one chunk, whole:
Required-key completeness and raw wrappers, Before vs After
Each row links to its case and leg in the sheet, whose
class,top_keys, andcontent_chunkscolumns give the counts. "Expected shape" is the schema object at the top for the RiskAssessment and native cases (theoutput_formatschema fornative_messages_both_opus55),kept_wholefor lone_key,literal_textfor held_text_opus5, andsummary_firstfor the sonnet control. No call returned a 429 or any error other than the 20 native Before 400sBefore wrapped 45 of 70 tool-mode answers, 4 of them in a two-key envelope, and After wrapped none of 70. The 1 Before answer that misses a key holds only
tierunder$PARAMETER_NAMEand$PARAMETER_VALUE, and no After answer did thatObservations from the run:
ZRH-01whole, 6 plus 6 callshotel_notestext as written, 6 of 6output_formatwin overoutput_config.format, 5 of 5hotel_notesalone, both legs/live-pr-risk at 3d3761a
Base 464a4db and head 3d3761a ran side by side on real Anthropic, Vertex AI, Azure AI, and Bedrock calls through two proxies with their own Postgres, with a recorder in front of every provider. Every base and head difference is listed below or is a different model answer, checked against the recorded provider stream. A third proxy on current main merged with 3d3761a matched head wherever the provider gave the same answer, and the only misses were runs where the model called
get_weatheron one leg and not the otherBreaking
At c739e13 a schema that allows extra keys and requires none lost the outer key of a valid answer. With
{"properties": {"summary": ...}, "additionalProperties": {"type": "object"}}the provider sent{"user_1": {"summary": "likes tea", "visits": 3}}and head returned{"summary": "likes tea", "visits": 3}. At 3d3761a base and head both return it as sent, in stream and non-stream on Azure AI Sonnet 4.6, and a long held answer streams in 90 chunks where base used 89 to 91.additionalProperties: trueandpatternPropertieskeep the wrapper too, on Azure AI Sonnet 4.6 and Vertex AI Haiku 4.5. Fixed in 3d3761aBackward incompatible
A schema with a declared
valueskey now gets{"values": [2, 3, 5, 7, 11]}on non-stream calls instead of the bare list[2, 3, 5, 7, 11]that base returned, on Anthropic, Bedrock, and Vertex AI. The stream already returned the object on base, so the two now agree. Approved by @mateo-berri under his standing rule that the answer must match the schema the requester describedA stream answer the handler holds now arrives in one chunk. On the risk schema,
{"city": "Paris"}from Vertex AI Haiku 4.5 went from 3 chunks to 1 with the same text. Approved by @mateo-berri under his standing rule that the answer must match the schema the requester describedAt c739e13 held text was re-serialized with
json.dumps, which escaped non-ASCII text and changed whitespace. At 3d3761a held text with no envelope is sent exactly as the provider wrote it, so{"meta": {"city":"café 東京"}, "summary": "crème brûlée"}from Azure AI Sonnet 4.6 comes back byte for byte as on base. A held answer that does carry an envelope is unwrapped and serialized withjson.dumps, the same way non-stream already returns it. Fixed in 3d3761aThe label rule unwraps
{"parameter_name": "RiskAssessment", "parameter_value": {...}}in stream and non-stream when the schema has required keys, but the stream holds the whole answer until it ends. On Bedrock Sonnet 5.5 the first chunk moved from about 1.6 s on base to about 7.4 s on head, and about 300 chunks became 1. Approved by @mateo-berri under his standing rule that the answer must match the schema the requester describedOn
/v1/messages,output_formatis now sent to Vertex AI asoutput_config.format. At c739e13 a request that set both fields lostoutput_formatwithout an error. At 3d3761aoutput_formatwins, the same as the Anthropic adapter, and otheroutput_configkeys such aseffortare kept. On Vertex AI Opus 5.5 a request with both fields went from a 400 on base to a 200 with theoutput_formatschema inoutput_config.format. Fixed in 3d3761aRegression risk
A schema that sets no
additionalPropertiesis treated as closed, even though JSON Schema allows extra keys by default. So a lone undeclared wrapper whose inner object shares a declared key is still unwrapped there. This is what makes the unwrap work for Pydantic-generated schemas, which leave the key out, and it was read from the code rather than driven live. A schema with no properties, such as{"additionalProperties": {"type": "integer"}}, passes aparameter_nameandparameter_valuelabel through as sent, the same as base, as seen live on Vertex AI Haiku 4.5. If a stream ends beforecontent_block_stop, a held answer may never be flushed, and a unit test that cuts the stream after a held prefix would cover it. Held answers push the first chunk out to the full answer time, so a long held answer behind a client or load balancer idle timeout could time out where base streamed. Malformedoutput_formatvalues such as5,[1],"", and{}still reach the provider, now insideoutput_config.formatinstead of asoutput_format, so they still answer 400 but with different provider error text. Bedrock Converse, Bedrock Mantle, and Claude Platform streams do not run the stream unwrap on base or head, so their streams still return the envelope that non-stream now strips. Tool arguments nested deeper than pydantic's JSON depth limit skip the unwrap and pass through as sent, which only unit tests coverDependency graph
response_format_envelope_contentsinlitellm/llms/base_llm/base_utils.pyhas two callers,unwrap_response_format_envelopefor non-stream inlitellm/llms/anthropic/chat/transformation.pyand_held_answerfor the held stream inlitellm/llms/anthropic/chat/handler.py._holds_the_schema_object,_allows_undeclared_keys, andResponseFormatSchema.accepts_a_lone_undeclared_keyare used only by the envelope walk and by_prefix_verdictin the handler, andResponseFormatSchemais built only byresponse_format_schema. Anthropic, Vertex AI, Azure AI, Bedrock Invoke, Bedrock Mantle, and Claude Platform all inherit that transformation and handler._fold_output_format_into_output_confighas one caller,sanitize_vertex_anthropic_output_params, which runs for Vertex AI/chat/completionsand/v1/messages. Non-stream and stream are verified live on Anthropic, Vertex AI, Azure AI, and Bedrock Invoke, and the fold is verified live on Vertex AI Opus 5.5 with and withouteffortand on/chat/completionsJSON mode. Spend rows were written on both sides. Mapped unit tests pass except 3 retry tests intests/unit/test_utils.pythat fail the same way on baseNot verified
tests/integration/run.py providerscould not run locally because every test fails setup withKeyError: 'INTEGRATION_PROXY_URL'on base and head, so it ran on the /audit rig instead (audit round 3 below). Vertex AI Haiku 4.5, Sonnet 4.5, and Sonnet 5.5 on/v1/messageswith a schema are blocked by the test project's org policy (constraints/vertexai.allowedPartnerModelFeatures) on both sides, so the provider's own answer to a malformedoutput_config.formatwas not seen. Vertex AI Sonnet 5.5 and Claude Platform Sonnet 5.5 rejected forced tool choice on both sides in the c739e13 run. The truncated held stream and the Bedrock Mantle and Claude Platform streams were not driven. The{"name": "json_tool_call", "arguments": {...}}envelope on an open schema, an open schema with required keys, and the$FUNCTION_NAMEandtool_namelabel shapes were prompted, but the models answered with other shapes on both sides, so unit tests are the only cover for thoseAudit round 3 of 3
The rig is lit9409r3c on the GCE box, with base at the merge base 464a4db and head and ctl at 3d3761a plus the tests commit ef1c19f. Every cell boots its own gateway against a recording fake upstream. Base cells come from round 3's base run at the same merge base plus a base run of the new cells. The whole head file ran twice, T1 to T4 ran interleaved in 1-worker lanes, and live Vertex calls ran on both legs. The full per-cell matrix has 182 cells, 181 PASS, and 1 Low outside the diff
DK covers
additionalPropertiesset to an object or true andpatternProperties, on chat and /v1/messages, stream and non-stream. A wrapper those schemas allow stays whole, and ajson_tool_callenvelope still unwraps. NA1s checks that a held stream with non-ASCII labels and no envelope comes back byte for byte as the model wrote it. N9 checks thatoutput_formatwins over the caller'soutput_config.formaton /v1/messages and that effort is kept. Base 400s on L2 are Vertex rejecting the deprecatedoutput_formatThe Low row is the P4 gemini pass-through control, which was red on all 3 runs. Its owned proxy took about 130 s to boot at box load 23 to 27, which hit the 90 s pytest timeout. It was green in round 2, and the diff does not touch Gemini pass-through or proxy boot. As already known, the Bedrock Mantle and Claude Platform stream iterators build ModelResponseIterator without the schema, so they keep the envelope on both legs (merge-base code). Timing reds seen while other lanes booted proxies cleared on the interleaved reruns, with the 512 KB wall at 0.33 to 0.63 s on base and 0.32 to 0.72 s on head
Type
🐛 Bug Fix
Caveats (if any)
High
properties{"properties": {"id": ...}, "required": ["payload"]}, the valid answer{"payload": {"id": "abc", "rows": 3}}comes back as{"id": "abc", "rows": 3}on stream and non-stream, which fails the caller's own schema. Withenable_json_schema_validationon, that 200 becomes aJSONSchemaValidationErrorproperties, while the label check already countsrequiredkeys as declared. Caveats round 3 found this after the merge, and the fix is on a follow-up ticketMedium
content_block_stoplitellm_settings.sse_keepalive_ping_interval_seconds(off by default) sends: pingcomments while a stream is held, which keeps idle timeouts from firing{"name": "json_tool_call", "arguments": {"input": {...}}}comes back as{"input": {...}}, since a layer that names the tool always counts as the one holding the schema objectoutput_formatreplaces a validoutput_config.formaton Vertex/v1/messagesoutput_formatwin, while Bedrock's fold only lets a dict win, anddrop_paramsdoes not drop the bad value, so Vertex answers 400 as it did on basedrop_paramsdrop is on the same follow-up ticketvaluesnow get the object, not the list[...]to{"values": [...]}on Anthropic, Bedrock, and Vertex AI. The new shape matches the schema, but a client that parsed the bare list breaks on upgradehotel_notesalone, since the model writes them that way on base toomodel_info.supports_native_structured_output: true) and Google's org-policy prerequisite are not documented yet, so the working route today is a model the cost map marks nativeLow
content_block_stop, so such a stream gives""withfinish_reason: stop, where base sent the partial textRemoteProtocolErrorin httpx and surfaces as a stream error on base and head alike, so only an upstream that closes its body cleanly mid-block hits this. Neither leg's answer parses as JSON therepropertieskey and Databricks onlyvalues, the same as maintool_calls{"values": [...]}streams and non-stream still return different shapesvalues, the stream returns{"values": [1, 2, 3]}and non-stream returns[1, 2, 3]on base and head. Base unwrapped the stream only when all arguments arrived in one delta{"meta": {"tier": 2, "note": "keep"}}comes back as{"tier": 2, "note": "keep"}when the schema sets neitheradditionalPropertiesnorrequired, the tradeoff the Decisions bullet on closed schemas names\uescapesHôtelarrives asHôtelon unwrapped streams and non-stream answers, while held text that passes through keeps its characters. The parsed value matches{"parameters": {...}, "name": "json_tool_call"}streams as sent when the schema has noproperties(everyjson_objectcall) or allows extra keys and requires none, while non-stream unwraps it. Base returned the envelope on bothjson.loadscome back as sent, wrapper included, instead of raisingoutput_formatwith its beta header, which Anthropic's API still accepts. Only Vertex rejects it/v1/messagesforwards the caller's schema to the native path as sentadditionalProperties: falsegets Vertex's 400 naming that field/v1/chat/completionsreturned 200 for the same schema without itFinal Attestation
Note
Medium Risk
Changes how structured JSON is parsed and streamed across Anthropic, Bedrock, Azure AI, and Vertex paths; streaming may buffer until block end, and Vertex request field mapping affects native structured-output calls.
Overview
Fixes Vertex AI Claude
json_schemaresponses that arrived wrapped inside tool-call JSON (e.g.parameters,tool_name/nameenvelopes) by unwrapping to the schema object on non-stream and stream paths for Anthropic-family providers (direct Anthropic, Azure AI, Bedrock invoke, Vertex tool emulation).Adds shared
ResponseFormatSchema/ envelope helpers inbase_utils, wires the json tool’sinput_schemathroughJsonModeRequestintoconvert_tool_response_to_messageandModelResponseIteratorstreaming (prefix buffering + flush on block end).For native Vertex structured output, maps deprecated top-level
output_format→output_config.formatin request sanitization (Anthropic direct still forwardsoutput_format).Includes broad wire/integration and unit coverage for unwrap shapes, folding, and streaming edge cases.
Reviewed by Cursor Bugbot for commit 3d3761a. Bugbot is set up for automated code reviews on this repo. Configure here.