Skip to content

fix(vertex_ai): unwrap tool-emulated json_schema envelopes and send output_config.format for Claude - #45871

Merged
mateo-berri merged 13 commits into
mainfrom
litellm_vertex_claude_structured_output
Oct 14, 2026
Merged

mateo-berri merged 13 commits into
mainfrom
litellm_vertex_claude_structured_output

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Vertex AI Claude json_schema answers sometimes come back wrapped under parameters, input, or a similar key
  • Native structured-output rows send the deprecated output_format, so Vertex answers 400

How it solves it:

  • Unwrap a model-added envelope by its shape: one key the schema does not declare, holding an object, alone or beside a name or tool_name equal to the json tool's own name, or beside undeclared string labels such as parameter_name when the schema has required keys
  • Hold a streamed answer only while it can still be that envelope (it opens with our tool's name, with an undeclared key holding an object, or with an undeclared string followed by another undeclared key) and unwrap it when the block ends, so the stream delivers the same object the non-stream path does
  • Send output_format to Vertex AI Claude as output_config.format

Decisions made on purpose:

  • The unwrap reads only the schema's top-level property names and never validates against the schema, so no jsonschema import, metaschema check or $ref resolution runs on the request path. That works on every jsonschema the pin allows and cannot be stalled by a large schema
  • A key the schema declares is never treated as a wrapper, so a schema that legitimately nests an object under input or parameters keeps it
  • On a schema with required keys, undeclared keys holding strings next to one undeclared object are labels, so {"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
  • Any other answer with two or more keys besides our tool's name comes back as sent, so a valid answer such as {"meta": {...}, "label": "keep"} on an open schema with no required keys keeps every field
  • A schema that allows undeclared keys (additionalProperties set to true or a schema, or patternProperties) 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 a name or tool_name equal to our tool's name is still set aside there
  • A schema with no additionalProperties key 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 key
  • A held stream that turns out to carry no wrapper is sent exactly as the model wrote it, in one chunk when the tool block ends, so a held answer never changes its spacing, key order or escaping
  • A name or tool_name equal to the json tool's name is set aside even on a schema with no properties or one that declares name, since no answer names our tool by accident. The value beside it may also be a JSON-encoded object string
  • A name with any other value is ordinary data when the schema declares name or 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 foreign name or tool_name is a label like any other string. The stream waits for the key after that string before it decides, so both paths still agree
  • Arguments nested too deep for json.loads come 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
  • When the unwrapped object shares no key with the schema and is itself a lone undeclared wrapper, the unwrap repeats, so {"parameter": {"value": {...}}} reaches the caller as the inner object. A layer that names our tool stops the walk there (see Caveats)
  • The unwrapped object is returned even when it misses a required key, since it is closer to the schema than the wrapper, and enable_json_schema_validation then reports the missing key on the object the schema describes
  • A schema with no top-level properties (a map, anyOf or $ref root) streams as it arrives unless the answer opens with our tool's name
  • The old top-level values unwrap stays as the fallback when no envelope is found, except when the schema itself declares values, where {"values": [...]} now comes back as sent instead of as the bare array
  • The json tool carries no description: a one-line "fill every required field" description tried at 9b5ae73 made claude-sonnet-5 leave the required affected_systems key 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
  • The cost-map rows keep tool emulation for the non-native models, because flipping them to native would 400 on every project whose org policy does not allow partner-model structured outputs
  • 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
  • Bedrock invoke streaming reads the json tool's schema back from the request body, so its stream unwraps like the non-stream path already did
  • Bedrock keeps sending the legacy output_format first while Vertex sends only output_config.format, since Bedrock still accepts the old field
  • Every provider whose answer goes through the Anthropic chat transformation shares the non-stream unwrap (direct Anthropic models outside the cost map, Azure AI Anthropic, Bedrock invoke, Bedrock Mantle, Claude Platform), because the same model-added wrapper reaches them. The stream unwrap reaches direct Anthropic, Azure AI Anthropic, Bedrock invoke and Vertex AI. Bedrock Mantle and Claude Platform streams are left alone, since on the merge base they already stream the json tool as tool_calls deltas 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_validation now validates the unwrapped object, which is the object the schema describes

User Flow

Before: a developer asking a Vertex AI Claude deployment for a json_schema answer 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

  1. They send POST https://litellm-domain/v1/chat/completions with "model": "claude-opus-5" (a vertex_ai/claude-opus-5 deployment) and "response_format": {"type": "json_schema", "json_schema": {"name": "RiskAssessment", "schema": {...}}}
  2. HTTP 200 comes back with finish_reason: stop, but message.content is {"name": "json_tool_call", "parameters": {"tier": 3, ...}} on most calls, so parsing it as a RiskAssessment fails on the missing top-level keys
  3. They send the same request with "stream": true and join the delta.content chunks: the joined text is the same {"name": "json_tool_call", "parameters": {...}} wrapper
  4. They point the same request at "model": "claude-opus-5-5" (a vertex_ai/claude-opus-5-5 deployment, native structured outputs) and get HTTP 400 output_format: This field is deprecated. Use 'output_config.format' instead. on every call

After: the same requests come back as the schema object itself, streamed or not, and the native deployment reaches Vertex with the current field

  1. They send the same POST https://litellm-domain/v1/chat/completions with "model": "claude-opus-5" and the same response_format
  2. HTTP 200 comes back with message.content as {"tier": 3, "risk_level": "high", ...}, the schema's own keys at the top level, so the parse succeeds
  3. They send the same request with "stream": true: the delta.content chunks join to {"tier": 3, "risk_level": "high", ...} and the last chunk carries finish_reason: stop
  4. They point the same request at "model": "claude-opus-5-5" and it reaches Vertex as output_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 naming constraints/vertexai.allowedPartnerModelFeatures instead of the deprecation error

Linear ticket

Resolves LIT-9409

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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, location global. 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/completions and /v1/responses, streamed and not. One qa_cases.py run per case sends call i to both proxies at the same moment, 3 calls in flight per leg. The RiskAssessment cases send the exact messages and 8-field schema of chat.json below, with no max_tokens. Each answer is classed by the shallowest object in it that holds all 8 required keys. plain means that object is the top level, wrapped_depth1 means it sits one level down under the keys in wrapper, and incomplete means no object holds all 8. A stream is classed on its joined content deltas, with its chunk count and first-chunk time

Three more cases cover what 3d3761a changes, all on /v1/chat/completions with system message You are a hotel data assistant. Answer only with the requested JSON. lone_key_opus5 sends the HotelRecord schema below, which allows extra keys and requires none, and kept_whole means the asked-for ZRH-01 is still the only top-level key. held_text sends HotelNotes and asks for an undeclared, accented hotel_notes object before summary. claude-opus-5 writes hotel_notes first, so the proxy holds the stream until it can rule out an envelope. claude-sonnet-5 puts summary first, so it is a control with no hold. literal_text means hotel_notes comes first with literal accents and no \u escape. Every call is one row in this sheet tab, and the raw jsonl per case and leg is in this folder

The config has this entry for each of claude-opus-5, claude-sonnet-5, and claude-opus-5-5, and a small launcher drops DATABASE_URL and starts the proxy with the arguments below:

model_list:
  - model_name: claude-opus-5
    litellm_params:
      model: vertex_ai/claude-opus-5
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
      vertex_credentials: os.environ/VERTEXAI_CREDENTIALS
python litellm/proxy/proxy_cli.py --config config.yaml --port $LITELLM_PORT --num_workers 2 --timeout_worker_healthcheck 60

Client calls, per case:

# chat_opus5 / chat_sonnet5, and .create(..., stream=True) for their *_stream cases
raw = oai.chat.completions.with_raw_response.create(model=model, messages=messages,
    response_format={"type": "json_schema", "json_schema": {"name": "RiskAssessment", "schema": schema}})
# responses_sonnet5 (with_raw_response) and responses_sonnet5_stream (stream=True)
oai.responses.create(model=model, instructions=system, input=user,
    text={"format": {"type": "json_schema", "name": "RiskAssessment", "schema": schema}})
# lone_key_* and held_text_*, the same chat calls with
response_format={"type": "json_schema", "json_schema": {"name": "HotelRecord", "schema": hotel_record}}
response_format={"type": "json_schema", "json_schema": {"name": "HotelNotes", "schema": hotel_notes}}
{"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_key user message is Give 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. The held_text user message is Write 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.json is chat.json with "stream": true, and messages.json sends the schema under a top-level output_format. messages_both.json adds an output_config.format that asks for verdict and reason instead, so the answer's keys show which format the proxy sent. The messages loop is the last loop below with -d @messages.json

ERR='(.error.message | gsub("\\s+"; " ") | sub("^.*?Exception BadRequestError - "; "") | .[0:150])'
jq '.output_config = {format: {type: "json_schema", schema: {type: "object", properties: {verdict: {type: "string", enum: ["approve", "reject"]}, reason: {type: "string"}}, required: ["verdict", "reason"], additionalProperties: false}}}' messages.json > messages_both.json

# chat completions
for i in $(seq 1 5); do
  code=$(curl -s -o chat_$i.json -w '%{http_code}' http://127.0.0.1:$PORT/v1/chat/completions \
    -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d @chat.json)
  echo "$code $(jq -r "if .error then $ERR else (.choices[0].finish_reason + \" \" + (.choices[0].message.content | fromjson | keys_unsorted | join(\",\"))) end" chat_$i.json)"
done

# chat completions streaming
for i in $(seq 1 5); do
  code=$(curl -sN -o stream_$i.txt -w '%{http_code}' http://127.0.0.1:$PORT/v1/chat/completions \
    -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d @chat_stream.json)
  if [ "$code" = 200 ]; then
    echo "$code $(grep -c '^data: {' stream_$i.txt) chunks $(grep '^data: {' stream_$i.txt | sed 's/^data: //' | jq -rs '([.[].choices[0].finish_reason // empty] | join("")) + " " + ([.[].choices[0].delta.content // ""] | join("") | fromjson | keys_unsorted | join(","))')"
  else
    echo "$code $(jq -r "$ERR" stream_$i.txt)"
  fi
done

# messages with both output_format and output_config.format
for i in $(seq 1 5); do
  code=$(curl -s -o both_$i.json -w '%{http_code}' http://127.0.0.1:$PORT/v1/messages \
    -H "x-api-key: $LITELLM_MASTER_KEY" -H 'anthropic-version: 2023-06-01' -H 'Content-Type: application/json' -d @messages_both.json)
  echo "$code $(jq -r "if .error then $ERR else (.stop_reason + \" \" + (.content[0].text | fromjson | keys_unsorted | join(\",\"))) end" both_$i.json)"
done
chat.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

  1. 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 legs
  2. Observed, all 24 return HTTP 200, and 5 of them are wrapped under keys the model made up:
base chat_opus5 calls: 24 shapes: {"plain": 19, "wrapped_depth1:hotel_group_change": 1, "wrapped_depth1:input": 2, "wrapped_depth1:paramaters": 2}
{"i": 16, "http_status": 200, "finish": "stop", "shape": "wrapped_depth1", "wrapper": "input", "top_keys": ["input"]}

Call 16's message.content, as the client got it:

{"input": {"tier": 1, "risk_level": "high", "score": 78, "summary": "Weekend migration of loyalty-points ledger from self-managed PostgreSQL 13 to man...

Native structured outputs, claude-opus-5-5 (curl)

  1. The loops above with PORT=32069
  2. Observed, all 20 calls get HTTP 400 from Vertex, and the stream gets it before any chunk. The first line of the chat and both-formats loops:
# chat completions
400 {"type":"error","error":{"type":"invalid_request_error","message":"output_format: This field is deprecated. Use 'output_config.format' instead. See ht
# messages with both output_format and output_config.format
400 {"type":"error","error":{"type":"invalid_request_error","message":"output_format: This field is deprecated. Use 'output_config.format' instead. See ht

Permissive schema with one undeclared key, claude-opus-5, streaming

  1. The same command with lone_key_opus5_stream 6, and lone_key_opus5 6 without streaming
  2. Observed, ZRH-01 stays the only top-level key on all 6 streams, 9 chunks each. The joined stream is the last line:
base lone_key_opus5_stream calls: 6 shapes: {"kept_whole": 6}
{"i": 0, "http_status": 200, "finish": "stop", "shape": "kept_whole", "wrapper": "none", "top_keys": ["ZRH-01"], "content_chunks": 9, "first_content_s": 2.0}
{"ZRH-01": {"name":"Hotel Limmat","city":"Zurich","rooms":120}}

Stream that starts with an undeclared key and accented text, claude-opus-5

  1. The same command with held_text_opus5_stream 6, and held_text_sonnet5_stream 4 as the control
  2. Observed, all 6 start with hotel_notes and stream in 66 to 77 chunks, the first 4.0 to 5.2 s after the request, with literal accents:
base held_text_opus5_stream calls: 6 shapes: {"literal_text": 6}
{"i": 0, "http_status": 200, "finish": "stop", "shape": "literal_text", "wrapper": "none", "top_keys": ["hotel_notes", "summary"], "content_chunks": 75, "first_content_s": 4.0}

Call 0's joined delta.content, opening:

{"hotel_notes": {"Hôtel Lutèce":"Hôtel de charme situé au cœur du Quartier latin, à deux pas de la Seine et de Notre-Dame.","Gasthof Zürichsee":"Gemütlicher Gasthof direkt am Zürichsee, mit schöner Au...

After (3d3761a)

chat completions, claude-opus-5 (tool emulation), the customer's flow

  1. Same run as Before
  2. Observed, all 24 return HTTP 200 with the schema object itself as message.content:
head chat_opus5 calls: 24 shapes: {"plain": 24}

Call 16's message.content, as the client got it:

{"tier": 1, "risk_level": "high", "score": 78, "summary": "Weekend migration of loyalty-points ledger from self-managed PostgreSQL 13 to managed cloud...

Native structured outputs, claude-opus-5-5 (curl)

  1. The loops above with PORT=48959
  2. Observed, all 20 calls get HTTP 200, and each stream sends 124 to 148 chunks. The both-formats loop returns the output_format schema's 8 keys on all 5 calls, not verdict and reason, so output_format won. The first line of the chat and both-formats loops:
# chat completions
200 stop tier,risk_level,score,summary,affected_systems,findings,rollback_plan,requires_downtime
# messages with both output_format and output_config.format
200 end_turn tier,risk_level,score,summary,affected_systems,findings,rollback_plan,requires_downtime

Permissive schema with one undeclared key, claude-opus-5, streaming

  1. Same runs as Before
  2. Observed, ZRH-01 stays 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:
head lone_key_opus5_stream calls: 6 shapes: {"kept_whole": 6}
{"i": 0, "http_status": 200, "finish": "stop", "shape": "kept_whole", "wrapper": "none", "top_keys": ["ZRH-01"], "content_chunks": 8, "first_content_s": 1.9}
{"ZRH-01": {"name":"Hotel Limmat","city":"Zurich","rooms":120}}

Stream that starts with an undeclared key and accented text, claude-opus-5

  1. Same runs as Before
  2. Observed, the proxy held each stream and sent it as one chunk on all 6, 4.6 to 5.6 s after the request. Each one starts with hotel_notes, keeps the accents as literal characters with no \u escape, and keeps the model's own mixed spacing, which a re-serialization would have changed:
head held_text_opus5_stream calls: 6 shapes: {"literal_text": 6}
{"i": 0, "http_status": 200, "finish": "stop", "shape": "literal_text", "wrapper": "none", "top_keys": ["hotel_notes", "summary"], "content_chunks": 1, "first_content_s": 5.2}

Call 0's one chunk, whole:

{"hotel_notes": {"Hôtel Lutèce":"Hôtel de charme situé près du quartier Latin, à deux pas de la Seine, où le petit déjeuner est servi dès sept heures.","Gasthof Zürichsee":"Gemütlicher Gasthof direkt am Zürichsee mit schöner Aussicht über das Wasser; Frühstück wird täglich im Wintergarten angeboten.","Ryōkan Kyō-no-yado":"京都の静かな路地にある伝統的な旅館で、畳の客室と露天風呂、京料理の朝食をお楽しみいただけます。"}, "summary": "Notes for three hotels in Paris, Zürich, and Kyōto have been written in French, German, and Japanese respectively."}

Required-key completeness and raw wrappers, Before vs After

Each row links to its case and leg in the sheet, whose class, top_keys, and content_chunks columns give the counts. "Expected shape" is the schema object at the top for the RiskAssessment and native cases (the output_format schema for native_messages_both_opus55), kept_whole for lone_key, literal_text for held_text_opus5, and summary_first for the sonnet control. No call returned a 429 or any error other than the 20 native Before 400s

case leg calls HTTP 200 expected shape wrapped missing a key chunks per stream
chat_opus5 Before 24 24 19 5 0 n/a
chat_opus5 After 24 24 24 0 0 n/a
chat_opus5_stream Before 6 6 5 1 0 287 to 341
chat_opus5_stream After 6 6 6 0 0 255 to 346
chat_sonnet5 Before 12 12 0 12 0 n/a
chat_sonnet5 After 12 12 12 0 0 n/a
chat_sonnet5_stream Before 10 10 0 10 0 188 to 215
chat_sonnet5_stream After 10 10 10 0 0 1
responses_sonnet5 Before 10 10 0 9 1 n/a
responses_sonnet5 After 10 10 10 0 0 n/a
responses_sonnet5_stream Before 8 8 0 8 0 188 to 209
responses_sonnet5_stream After 8 8 8 0 0 1
native_chat_opus55 Before 5 0 0 n/a n/a n/a
native_chat_opus55 After 5 5 5 0 0 n/a
native_chat_opus55_stream Before 5 0 0 n/a n/a n/a
native_chat_opus55_stream After 5 5 5 0 0 124 to 148
native_messages_opus55 Before 5 0 0 n/a n/a n/a
native_messages_opus55 After 5 5 5 0 0 n/a
native_messages_both_opus55 Before 5 0 0 n/a n/a n/a
native_messages_both_opus55 After 5 5 5 0 0 n/a
lone_key_opus5 Before 6 6 6 n/a n/a n/a
lone_key_opus5 After 6 6 6 n/a n/a n/a
lone_key_opus5_stream Before 6 6 6 n/a n/a 9
lone_key_opus5_stream After 6 6 6 n/a n/a 8
held_text_opus5_stream Before 6 6 6 n/a n/a 66 to 77
held_text_opus5_stream After 6 6 6 n/a n/a 1
held_text_sonnet5_stream Before 4 4 4 n/a n/a 14 to 49
held_text_sonnet5_stream After 4 4 4 n/a n/a 16 to 54

Before 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 tier under $PARAMETER_NAME and $PARAMETER_VALUE, and no After answer did that

Observations from the run:

  • PR clears customer's opus-5 envelopes, 5 of 24 to 0
  • PR clears all tool-mode envelopes, 45 of 70 to 0
  • PR clears two-key envelopes, 4 Before to 0 After
  • PR turns native opus-5-5's 20 400s into 20 200s
  • PR keeps undeclared ZRH-01 whole, 6 plus 6 calls
  • PR sends held hotel_notes text as written, 6 of 6
  • PR makes output_format win over output_config.format, 5 of 5
  • PR holds sonnet tool streams to one chunk, 10 plus 8
  • PR delays held streams' first content to stream end
  • PR leaves the tier-only answer alone, 1 Before, 0 After
  • PR leaves sonnet dropping hotel_notes alone, both legs
  • No two-level envelope appeared, so that path went untested

/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_weather on one leg and not the other

Breaking

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: true and patternProperties keep the wrapper too, on Azure AI Sonnet 4.6 and Vertex AI Haiku 4.5. Fixed in 3d3761a

Backward incompatible

A schema with a declared values key 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 described

A 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 described

At 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 with json.dumps, the same way non-stream already returns it. Fixed in 3d3761a

The 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 described

On /v1/messages, output_format is now sent to Vertex AI as output_config.format. At c739e13 a request that set both fields lost output_format without an error. At 3d3761a output_format wins, the same as the Anthropic adapter, and other output_config keys such as effort are kept. On Vertex AI Opus 5.5 a request with both fields went from a 400 on base to a 200 with the output_format schema in output_config.format. Fixed in 3d3761a

Regression risk

A schema that sets no additionalProperties is 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 a parameter_name and parameter_value label through as sent, the same as base, as seen live on Vertex AI Haiku 4.5. If a stream ends before content_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. Malformed output_format values such as 5, [1], "", and {} still reach the provider, now inside output_config.format instead of as output_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 cover

Dependency graph

response_format_envelope_contents in litellm/llms/base_llm/base_utils.py has two callers, unwrap_response_format_envelope for non-stream in litellm/llms/anthropic/chat/transformation.py and _held_answer for the held stream in litellm/llms/anthropic/chat/handler.py. _holds_the_schema_object, _allows_undeclared_keys, and ResponseFormatSchema.accepts_a_lone_undeclared_key are used only by the envelope walk and by _prefix_verdict in the handler, and ResponseFormatSchema is built only by response_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_config has one caller, sanitize_vertex_anthropic_output_params, which runs for Vertex AI /chat/completions and /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 without effort and on /chat/completions JSON mode. Spend rows were written on both sides. Mapped unit tests pass except 3 retry tests in tests/unit/test_utils.py that fail the same way on base

Not verified

tests/integration/run.py providers could not run locally because every test fails setup with KeyError: '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/messages with 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 malformed output_config.format was 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_NAME and tool_name label shapes were prompted, but the models answered with other shapes on both sides, so unit tests are the only cover for those

Audit 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

Row What it checks Cells Base red Head green x2 Verdict
H envelope unwrap, non-stream 15 13 15 PASS
SH held stream, one frame 14 9 14 PASS
SR /v1/responses stream 1 1 1 PASS
SF other providers, stream 4 4 4 PASS
W wrapper variants 9 5 9 PASS
V opt-in schema validation 2 1 2 PASS
N native output_config.format 14 12 14 PASS
O output_format merges 7 4 7 PASS
C controls 3 0 3 PASS
S junk inputs kept 25 9 25 PASS
T event loop timing 4 0 4 PASS
E edge cases, spend rows 5 3 5 PASS
LB label rule 26 11 26 PASS
D encoded and deep inputs 6 4 6 PASS
K schema owns the key 2 1 2 PASS
DK dynamic-key schemas 22 16 22 PASS
NA non-ASCII held stream 4 2 4 PASS
P pass-through 17 0 16 Low
X outage and revival 2 2 2 PASS
L1 live sonnet-5 chat 12 7 wrapped 12 plain PASS
L2 live opus-5-5 chat, messages 2 2 x 400 2 x 200 PASS
L3 live Vertex pass-through 1 0 1 PASS

DK covers additionalProperties set to an object or true and patternProperties, on chat and /v1/messages, stream and non-stream. A wrapper those schemas allow stays whole, and a json_tool_call envelope 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 that output_format wins over the caller's output_config.format on /v1/messages and that effort is kept. Base 400s on L2 are Vertex rejecting the deprecated output_format

The 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

  • A valid answer is unwrapped when its single key is required but not in properties
    • On {"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. With enable_json_schema_validation on, that 200 becomes a JSONSchemaValidationError
    • The wrapper and first-key checks read only properties, while the label check already counts required keys as declared. Caveats round 3 found this after the merge, and the fix is on a follow-up ticket

Medium

  • Held json streams send nothing until the answer ends
    • While a stream could still be an envelope, the proxy holds the response headers and every chunk, then sends the whole answer as one chunk at content_block_stop
    • On a fake upstream sending one delta per second, the head sent headers and its only chunk at 11.3 s, while base sent headers at 1.2 s and then streamed. Live Bedrock Sonnet 5.5 label streams moved their first chunk from about 1.6 s to 7.4 s
    • A load balancer or client with an idle or first-byte timeout shorter than the answer can fail a long structured stream that base delivered, wrapped
    • Answers that open like an envelope are held (our tool's name, an undeclared key holding an object, or an undeclared string followed by another undeclared key). So is a valid answer of that shape on a schema that allows extra keys and requires some, and a prefix still undecided after 4096 characters. Non-stream calls and answers that open with a declared key are not delayed
    • Setting litellm_settings.sse_keepalive_ping_interval_seconds (off by default) sends : ping comments while a stream is held, which keeps idle timeouts from firing
    • This covers Vertex AI, direct Anthropic, Azure AI, Bedrock invoke, and the Responses API stream that runs on top of them. Streaming the inner object as it arrives is on a follow-up ticket
  • An envelope that names our tool is only unwrapped one layer
    • {"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 object
    • No two-level envelope came up in the live runs. The fix is on the same follow-up ticket
  • A malformed output_format replaces a valid output_config.format on Vertex /v1/messages
    • The Vertex fold lets any non-None output_format win, while Bedrock's fold only lets a dict win, and drop_params does not drop the bad value, so Vertex answers 400 as it did on base
    • Dict-only precedence with a drop_params drop is on the same follow-up ticket
  • Schemas that declare values now get the object, not the list
    • Non-stream answers for such a schema change from [...] to {"values": [...]} on Anthropic, Bedrock, and Vertex AI. The new shape matches the schema, but a client that parsed the bare list breaks on upgrade
  • Emulated answers can still miss required keys behind HTTP 200
    • The PR leaves the tier-only answer and claude-sonnet-5 dropping hotel_notes alone, since the model writes them that way on base too
    • claude-sonnet-5 sometimes splits one answer into several json tool blocks, one per field, and the client gets only the first block on base and head alike. The fix is on a follow-up ticket
    • The native opt-in (model_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 native

Low

  • A stream whose upstream body ends before the block ends returns empty content
    • The held buffer is sent only at content_block_stop, so such a stream gives "" with finish_reason: stop, where base sent the partial text
    • A real mid-body cut raises RemoteProtocolError in 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 there
  • Bedrock Converse and Databricks Claude still return model-added envelopes
    • Both use the same json tool but keep their own converters, which this PR does not touch. Converse unwraps only a lone properties key and Databricks only values, the same as main
  • Bedrock Mantle and Claude Platform streams still answer through tool_calls
    • Their non-stream path now unwraps, so stream and non-stream answers differ on those routes, as they did on base
  • {"values": [...]} streams and non-stream still return different shapes
    • With a schema that does not declare values, 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
  • Schemas open by default with no required keys lose a real outer key
    • {"meta": {"tier": 2, "note": "keep"}} comes back as {"tier": 2, "note": "keep"} when the schema sets neither additionalProperties nor required, the tradeoff the Decisions bullet on closed schemas names
  • Unwrapped answers come out re-encoded with \u escapes
    • Hôtel arrives as Hôtel on unwrapped streams and non-stream answers, while held text that passes through keeps its characters. The parsed value matches
  • An envelope with our tool's name in its second key is unwrapped only on non-stream
    • {"parameters": {...}, "name": "json_tool_call"} streams as sent when the schema has no properties (every json_object call) or allows extra keys and requires none, while non-stream unwraps it. Base returned the envelope on both
  • Arguments nested too deep for json.loads come back as sent, wrapper included, instead of raising
  • Direct Anthropic and Azure AI Anthropic still send the deprecated output_format with its beta header, which Anthropic's API still accepts. Only Vertex rejects it
  • /v1/messages forwards the caller's schema to the native path as sent
    • An object without additionalProperties: false gets Vertex's 400 naming that field
    • /v1/chat/completions returned 200 for the same schema without it
  • The /audit Gemini pass-through control cell timed out at proxy boot on all 3 runs of round 3, at box load 23 to 27. It passed in round 2, and the diff does not touch Gemini pass-through or proxy boot

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

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_schema responses that arrived wrapped inside tool-call JSON (e.g. parameters, tool_name/name envelopes) 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 in base_utils, wires the json tool’s input_schema through JsonModeRequest into convert_tool_response_to_message and ModelResponseIterator streaming (prefix buffering + flush on block end).

For native Vertex structured output, maps deprecated top-level output_format → output_config.format in request sanitization (Anthropic direct still forwards output_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.

…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.
@devin-ai-integration

devin-ai-integration Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@greptile-apps

greptile-apps Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 3/5

[Medium impact] Adjusts how structured output schemas are handled for Claude.

Fix the loss of valid response fields and the missing streaming support before merging.

Findings

  1. P1 Valid response fields disappear ▶
  2. P1 Streaming keeps the wrapper ▶

Summary

The PR moves Vertex Claude's output_format into output_config.format and adds schema-based wrapper removal for tool-emulated JSON responses.

  • Tool-emulated JSON replies return the matching object without its wrapper.
  • Vertex AI Claude gets structured output format inside output_config.

Reviews (1) · Last reviewed commit: "fix(vertex_ai): unwrap tool-emulated jso..." · Reviewed by Greptile

Comment thread litellm/llms/base_llm/base_utils.py Outdated
Comment on lines +186 to +192
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

53377d8 leaves any schema-accepted payload untouched and unwraps only when exactly one nested object matches the schema

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still holds at 71e8341, now by structure: an answer with two or more undeclared keys comes back as sent, so meta and label stay

Comment on lines +2869 to +2873
content: Final = (
payload
if response_format_schema is None
else unwrap_response_format_envelope(payload, response_format_schema)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Streaming keeps the wrapper

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

53377d8 holds a streamed wrapper until the block ends and emits the unwrapped object, same as the non-stream path

@codspeed

codspeed Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 31 untouched benchmarks


Comparing litellm_vertex_claude_structured_output (ef1c19f) with main (92faffa)

Open in CodSpeed

@codecov

codecov Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.10314% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/llms/anthropic/chat/handler.py 98.75% 1 Missing ⚠️
litellm/llms/base_llm/base_utils.py 98.82% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…_structured_output

# Conflicts:
#	tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py
#	tests/unit/llms/bedrock/chat/test_invoke_handler.py
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 3 potential issues.

Devin Review

Comment thread litellm/llms/base_llm/base_utils.py Outdated
Comment on lines +228 to +230
tool_call_payload: Final = _tool_call_envelope_payload(payload_object, tool_name)
if tool_call_payload is not None:
return tool_call_payload

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Withdrawn. 86450fe now checks schema acceptance first, so a schema-accepted payload keeps its tool-named wrapper as you suggested

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

71e8341 never treats a key the schema declares as a wrapper, so a declared field beside our tool's name keeps the whole answer

Comment thread litellm/llms/anthropic/chat/handler.py Outdated
Comment on lines +92 to +95
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"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by 71e8341. Neither path unwraps a wrapper with a foreign name now, so stream and non-stream return the same object

Comment thread litellm/llms/anthropic/chat/handler.py Outdated
Comment on lines +1142 to +1144
self._response_format_buffer = self._response_format_buffer + fragment
if self._response_format_verdict == "hold":
return ""

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

✅ code-review

Scope: 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. _STREAM_FAMILY in the integration test excludes Platform and Mantle. Both providers already streamed the json tool as tool_calls on the merge base, so this PR does not regress them. It leaves that separate bug unfixed.

Checks and execution details
  • Passed · Real testing evidence (required): Scope: the rule applies. The diff changes LLM translation in these files:

  • litellm/llms/anthropic/chat/handler.py: stream envelope hold and unwrap

  • litellm/llms/anthropic/chat/transformation.py: non-stream unwrap

  • litellm/llms/base_llm/base_utils.py

  • litellm/llms/bedrock/chat/invoke_handler.py

  • litellm/llms/azure_ai/anthropic/handler.py

  • litellm/llms/vertex_ai/.../output_params_utils.py: output_format becomes output_config.format

Evidence: the PR description contains inspectable manual E2E evidence:

  • Environment: live proxies on real Vertex AI Claude, project vertex-check-481318, location global. The description gives the proxy config, the launch command, the OpenAI SDK and curl client calls, and the full request bodies.
  • Comparison: each case ran on base 464a4dba9d and on 3d3761aaa6, with observed outputs inline.
  • Tool emulation: wrapped answers dropped from 45 of 70 to 0 of 70, streamed and non-streamed.
  • Native deployment: claude-opus-5-5 went from 400 output_format: This field is deprecated to 200 on chat, stream and /v1/messages.
  • Other cases: the description also covers the lone undeclared key (ZRH-01), as-written held text and output_format precedence.
  • Wider runs: the description reports side-by-side runs against real Anthropic, Azure AI and Bedrock through a recorder.

Tested commit matches head: the GitHub compare from 3d3761aaa6 to head ef1c19fbd6 shows one commit. It touches only tests/integration/providers/test_vertex_anthropic_structured_output_wire.py, so the live-tested product code is identical to head.

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.

  • Passed · Unit tests for changed modules (optional): Ran uv sync --frozen --all-extras, then uv run pytest on these targets:

  • tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py

  • tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.py

  • tests/unit/llms/bedrock/chat/test_invoke_handler.py

  • tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/

Result: 726 passed.

  • Passed · CI status on head (optional): The GitHub check-runs API for ef1c19fbd6 reports 88 runs:

  • All completed with success, except Cursor Bugbot, which returned neutral.

  • llms-anthropic, llms-bedrock and llms-vertex-ai all passed.

  • buildkite/e2e-tests build 28027 reports success.

  • Passed · Stream vs non-stream parity fuzz (optional): /tmp/fuzz.py fed 20,000 random payloads in random fragment sizes through _envelope_verdict and _held_answer. It compared each streamed result with unwrap_response_format_envelope.

The remaining mismatches fall into 2 groups:

  • Top-level values: these mismatches predate this PR, because the base stream also skipped the values unwrap.
  • Tool name after the wrapper key: the tool's name comes after the wrapper key on an open or property-less schema. The PR documents this limit: the stream holds only when the answer opens with the tool's name.

I found no mismatch on schemas with required keys, the case the PR targets.

  • Passed · Prior finding: Claude Platform / Mantle streams (optional): Reassessed against head. The description now says: "Bedrock Mantle and Claude Platform streams are left alone, since on the merge base they already stream the json tool as tool_calls deltas instead of content, which is a separate bug." The stream test is now parametrized on _STREAM_FAMILY, which excludes both providers. Their behavior predates this PR and is out of its stated scope, so I did not repeat the finding.

View review · Reviewed ef1c19fbd60f

@mateo-berri

Copy link
Copy Markdown
Contributor

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

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

✅ code-review

Scope: 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 tool_calls, so the gap predates this PR. The head commit no longer claims to fix them:

  • The PR description now says "Bedrock Mantle and Claude Platform streams are left alone… a separate bug".
  • _STREAM_FAMILY in the wire test now lists only anthropic_unmapped, azure_ai_unmapped, bedrock_invoke and vertex_haiku.
  • bedrock_mantle and claude_platform_unmapped appear only in the non-stream _FAMILY, and those cases pass.

That leaves a separate, known bug. This PR didn't cause it.

Checks and execution details
  • Passed · Real testing evidence (required): This rule applies because the PR changes translation code under litellm/llms/**:

  • anthropic/chat/handler.py and anthropic/chat/transformation.py add stream and non-stream unwrapping of the extra wrapper object.

  • bedrock/chat/invoke_handler.py reads the stream schema from the request body.

  • vertex_ai/.../output_params_utils.py moves output_format into output_config.format.

Integration tests run on the head commit: I set up local Postgres 15 and Redis, ran uv sync --frozen --all-groups --all-extras and prisma generate, then ran:

INTEGRATION_WORKERS=2 python tests/integration/run.py providers tests/integration/providers/test_vertex_anthropic_structured_output_wire.py

Result: 108 passed in 142.7s, with no skips (/tmp/itres/junit.xml). The tests send real HTTP through a running proxy (2 workers, DB, Redis) to scripted Vertex, Anthropic, Azure AI, Bedrock and Claude Platform peers. They assert the client-visible content, the body the upstream receives (output_config.format, no output_format), stream frames, failure paths (peer 400, outage, worker SIGKILL) and spend rows.

Where the fixtures come from: The scripted wrapper shapes (tool_name/name + parameters, values, the deep wrapper) and the Vertex deprecation 400 match what real Vertex returned in the PR's manual E2E runs. The PR documents the proxy config, client scripts, curl loops and per-call results for 464a4db (before) vs 86450fe (after), plus audit runs at 3b84374.

The manual runs used commits earlier than the head (f32acde). For the head itself, the evidence comes from the integration run above.

  • Passed · Changed unit tests (optional): Ran uv run pytest tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.py tests/unit/llms/bedrock/chat/test_invoke_handler.py tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/. Result: 697 passed.

  • Passed · Prior finding re-check (Claude Platform / Mantle streams) (optional): Withdrawn because the PR doesn't touch these streams and no longer claims to fix them.

  • litellm/llms/bedrock/claude_platform/transformation.py:92 and litellm/llms/bedrock/chat/mantle/transformation.py:131 are unchanged by this PR. The streaming gap there predates it.

  • The PR description now scopes these streams out.

  • The stream test family no longer asserts them (_STREAM_FAMILY at line 121 of the wire test).

The non-stream cases for both providers pass.

  • Passed · Breaking-change check (optional): No marker needed.

  • Vertex used to answer 400 to a top-level output_format, so moving it into output_config.format breaks no working request.

  • A caller's explicit output_config.format still wins.

  • Bedrock still sends output_format.

  • Direct Anthropic still sends output_format.


View review · Reviewed f32acde17d3a

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

Comment thread litellm/llms/base_llm/base_utils.py Resolved
@veria-ai

veria-ai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

…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.
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

⚠️ code-review

Scope: full · Full PR review.

Review incomplete.

BLOCKED · Test evidence BLOCKED · 3/5

No correctness findings.

The blocker is verification at the reviewed head. The PR changes translation in litellm/llms/anthropic/chat/handler.py, litellm/llms/anthropic/chat/transformation.py, litellm/llms/bedrock/chat/invoke_handler.py and the Vertex output_params_utils.py. The description's live Vertex proof ran on 86450fea50. It also says 71e8341ecc "replaces the unwrap logic, so both legs are being rerun". No rerun result appears for 71e8341ecc. I could not run tests/integration/providers/test_vertex_anthropic_structured_output_wire.py locally because it needs Postgres and Redis, and I found no CI result for this head. To clear the gate, post one of these for 71e8341ecc:

  • the live Before/After legs, or
  • a passing CI run of that integration file.

Earlier finding, withdrawn: "Claude Platform and Bedrock Mantle streams still return the json_tool_call wrapper". At this head, _STREAM_FAMILY drops bedrock_mantle and claude_platform_unmapped, so the stream test no longer asserts unwrapping for them. The description now lists those streams as left alone, as on the merge base, which already streamed the json tool as tool_calls. LIT-9409 is about Vertex AI. The behavior is pre-existing and the PR now states it accurately, so the finding no longer holds.

Couldn’t complete

  • Required real-testing-evidence is not_run. The live Vertex proof ran on 86450fea50, not head 71e8341ecc, which replaces the unwrap logic. The description says the rerun is pending, and no result is posted. I could not run the qualifying integration file tests/integration/providers/test_vertex_anthropic_structured_output_wire.py because Postgres and Redis are unavailable, and I found no CI result for this head.

  • Real testing evidence: In scope: the PR changes translation in these files:

  • litellm/llms/anthropic/chat/handler.py: buffers and unwraps the streamed json tool.

  • litellm/llms/anthropic/chat/transformation.py: unwraps the non-stream envelope.

  • litellm/llms/bedrock/chat/invoke_handler.py: reads the stream schema from the request body.

  • litellm/llms/vertex_ai/.../output_params_utils.py: moves output_format into output_config.format.

Evidence found:

  • Manual live E2E: real Vertex AI behind a live proxy, on 86450fea50, not the reviewed head 71e8341ecc. The PR says the head "replaces the unwrap logic" and that the rerun is pending. No rerun result is posted.
  • Integration test: tests/integration/providers/test_vertex_anthropic_structured_output_wire.py drives a real proxy against scripted Vertex, Anthropic, Azure, Bedrock and Platform peers. The envelope payloads are written by hand. They match the shapes the live runs observed ({"paramaters": {...}}, {"name": "json_tool_call", "parameters": ...}), but I found no capture procedure for them. The suite needs Postgres and Redis, which this sandbox lacks. I did not run it and found no CI result for this head.

Gap: no passing result for qualifying E2E or integration coverage at 71e8341ecc.

Checks and execution details
  • Not run · Real testing evidence (required): In scope: the PR changes translation in these files:

  • litellm/llms/anthropic/chat/handler.py: buffers and unwraps the streamed json tool.

  • litellm/llms/anthropic/chat/transformation.py: unwraps the non-stream envelope.

  • litellm/llms/bedrock/chat/invoke_handler.py: reads the stream schema from the request body.

  • litellm/llms/vertex_ai/.../output_params_utils.py: moves output_format into output_config.format.

Evidence found:

  • Manual live E2E: real Vertex AI behind a live proxy, on 86450fea50, not the reviewed head 71e8341ecc. The PR says the head "replaces the unwrap logic" and that the rerun is pending. No rerun result is posted.
  • Integration test: tests/integration/providers/test_vertex_anthropic_structured_output_wire.py drives a real proxy against scripted Vertex, Anthropic, Azure, Bedrock and Platform peers. The envelope payloads are written by hand. They match the shapes the live runs observed ({"paramaters": {...}}, {"name": "json_tool_call", "parameters": ...}), but I found no capture procedure for them. The suite needs Postgres and Redis, which this sandbox lacks. I did not run it and found no CI result for this head.

Gap: no passing result for qualifying E2E or integration coverage at 71e8341ecc.

  • Passed · Unit tests for changed files (optional): Ran uv run --frozen pytest -n 8 tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.py tests/unit/llms/bedrock/chat/test_invoke_handler.py tests/unit/llms/vertex_ai/vertex_ai_partner_models/anthropic/ at head: 708 passed. These are unit tests only, so they do not satisfy the evidence rule.
  • Not run · Integration wire suite (optional): tests/integration/providers/test_vertex_anthropic_structured_output_wire.py needs PostgreSQL and Redis, which this sandbox does not have. I did not install them or run the suite.
  • Passed · Earlier finding re-check (Mantle / Claude Platform stream) (optional): Withdrawn. At head, _STREAM_FAMILY (test file line 121) leaves out bedrock_mantle and claude_platform_unmapped. The PR Caveats say both streams stay as they are on the merge base. ClaudePlatformConfig.get_model_response_iterator and the Mantle get_model_response_iterator are unchanged from base, so this behavior predates the PR.
  • Passed · Breaking-change check (optional): Two behavior changes, neither breaking. Vertex AI Claude now receives output_config.format instead of output_format, which Vertex rejects as deprecated. {"values": ...} is no longer unwrapped when the schema declares values. Neither change alters a supported API, config option or default, so the title needs no !.

View review · Reviewed 71e8341eccc4

…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.
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread litellm/llms/base_llm/base_utils.py Resolved
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3d3761a. Configure here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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":

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, those expectations were stale. Since ef1c19f both other_tool cases expect the unwrapped schema object, matching the documented label rule

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Non-stream: unwrap_response_format_envelope in litellm/llms/base_llm/base_utils.py returns the inner object.
  2. Stream: _envelope_verdict in litellm/llms/anthropic/chat/handler.py holds the answer. _held_answer then emits the unwrapped object. other_tool sits 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
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

1 issue from previous review remains unresolved.

Fix All in Cursor

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit ef1c19f. Configure here.

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@mateo-berri

mateo-berri commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

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

PixelJonas added a commit to PixelJonas/home-ops that referenced this pull request Nov 23, 2026
* 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant