Repository navigation
fix(bedrock): emit tool_choice.type when parallel_tool_calls is set - #24
pseudotensor merged 5 commits into
Conversation
When `parallel_tool_calls=False` is set for a Bedrock Converse Anthropic
model, litellm builds `additionalModelRequestFields.tool_choice` with only
`disable_parallel_tool_use` and no `type`. Anthropic's Bedrock validator
rejects it with 400 "missing field `type`", failing every tool-calling
request on current models (Sonnet 5, Opus 4.8, Sonnet 4/4.5, ...).
Two parts:
1. Add `type` to the passthrough tool_choice, derived from an explicit
tool_choice when present (required->any, auto->auto, named-fn->tool),
defaulting to "auto" — mirroring the native Anthropic transform.
2. When an explicit tool_choice was ALSO mapped into the native
`toolConfig.toolChoice`, drop it: the disable-parallel flag can only ride
on the passthrough, and sending both makes Bedrock reject the request
("tool_choice/type conflicts with the existing field
toolConfig.toolChoice.<type>"). The passthrough carries the equivalent
type, so one channel suffices.
Verified live against Bedrock Converse (us-east-1) via litellm.completion:
`tool_choice=required|auto` + `parallel_tool_calls=False`, and
`parallel_tool_calls=False` alone, all return 200 with tool_calls; the
typeless / dual-channel shapes 400.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
(cherry picked from commit 7038d23)
CodeRabbit follow-up: for a named-function tool_choice with
parallel_tool_calls=False, the config emitted {"type": "tool", ...} but dropped
the function name. _apply_parallel_tool_use_config then removes the native
toolChoice that carried the name, so Bedrock received a nameless "tool" choice
and rejected it.
Mirror the native Anthropic transform (which sets _tool_choice["name"] =
_tool_name): extract _bedrock_parallel_tool_choice() to build the full payload
(type + disable_parallel_tool_use, plus name when type == "tool").
Live before/after against Bedrock claude-sonnet-5 (named tool_choice +
parallel_tool_calls=False):
- before: 400 BadRequest "tool_choice.tool.name: Field required"
- after: 200, single tool_call to the named function
Added a parametrized name assertion + an end-to-end test asserting the request
carries {"type": "tool", "name": ..., "disable_parallel_tool_use": True} and
the native toolChoice is dropped. Non-vacuous (both fail against the nameless
build). ruff/lint clean, C901 strict budget unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
(cherry picked from commit b1b434e)
Note for whoever bumps the fork base laterFound after opening this PR, so recording it here rather than editing the description. Upstream landed a partial version of this fix in v1.95.0 (and main), independently of the two open PRs, which are both still open along with the issue: BerriAI#22637, BerriAI#22638, BerriAI#32605. Our pin is on v1.93.0, which predates it. Upstream took the hardcoded
Two gaps remain upstream:
So a base bump to >= 1.95.0 does cover the case reported in h2oai/h2ogpte#11994 (no Do not drop this change when bumping the base. Once the fork moves to >= 1.95.0, the parts of this PR that upstream lacks are the type derivation ( For reference, the separate Azure |
…l_choice
Round 1 of review. The config was built inside the param loop from the caller's
RAW OpenAI tool_choice, using a second classifier that could disagree with
map_tool_choice_values -- and then win, because _apply_parallel_tool_use_config
deletes the native toolChoice. Three confirmed defects, two of them silent:
1. THE REASONING DOWNGRADE WAS BYPASSED. map_openai_params downgrades forced tool
use to auto when thinking is enabled, rewriting optional_params AFTER the loop.
A config built inside the loop still said type="any", so
{tools, tool_choice: required, parallel_tool_calls: false, thinking: enabled}
sent the forced-tool payload the downgrade exists to prevent -- a NEW 400
introduced by this feature, on the exact combination the code already guards.
The existing guard test asserts optional_params, so it could not see this.
2. A DICT tool_choice WITHOUT "type" LOST THE DIRECTIVE. The raw classifier
required tool_choice["type"] == "function"; the native mapper treats ANY dict
as a named-tool choice. {"function": {"name": "get_current_weather"}} came out
as type="auto" with the native block deleted, so the request SUCCEEDED and the
model was free to answer in prose instead of calling the required tool. Silent
wrong behaviour is worse than the 400 this PR fixes.
3. THE FORWARDED NAME WAS UNSANITIZED. The tool list and native toolChoice both
sanitize via make_valid_bedrock_tool_name. A tool named "get.current weather"
forced a tool absent from toolConfig.tools, with a name violating Bedrock's
[a-zA-Z][a-zA-Z0-9_-]* -- guaranteed ValidationException for namespaced/MCP
tool names, which h2ogpte generates.
Fix: build it after the loop and after the downgrade, from the FINAL mapped
tool_choice block. Disagreement becomes impossible -- it is the same value
Bedrock would have received natively, and it already carries the sanitized name.
_bedrock_tool_choice_type and _bedrock_parallel_tool_choice are deleted.
Two behaviour narrowings, both removing risk:
* parallel_tool_calls: TRUE now emits nothing. It maps to
disable_parallel_tool_use: false, which is Anthropic's default, so the old
code relocated the caller's forced-tool directive into an undocumented
passthrough for zero benefit -- on the OpenAI default, sent explicitly by many
SDKs. Whether Bedrock HONORS tool_choice there (vs merely validating it) is
unverified, so this was a real risk of silently dropping "required".
* no tools -> emits nothing. Anthropic rejects tool_choice without tools.
* parallel_tool_calls: None no longer disables parallel use (`not None` is True).
Also collapses the unreachable merge branch in _apply_parallel_tool_use_config:
additional_request_params is the params NOT in total_supported_params, and
tool_choice IS in that set, so the key can never already be present. Had it been
reachable it produced a corrupt hybrid {"type","name","disable_parallel_tool_use"}.
TESTS. Two existing tests enshrined the no-tools payload as correct and had to be
corrected rather than worked around. Added 7 request-level tests: the thinking
downgrade, name sanitization, parallel_tool_calls true/None, no-tools, the
untouched-without-the-flag non-regression claim (previously unpinned), and the
unsupported-model gate. Verified they FAIL with the production change reverted (6
failed) rather than passing vacuously. 170 pass.
Trimmed test_parallel_tool_calls_tool_choice_includes_type from 6 models to 2:
every model with supports_parallel_tool_use_config is Anthropic and the code does
not branch beyond that flag, so the other four asserted the cost map, not this
code, and moved together under every mutation. Kept one bare and one us. id.
Reworded two comments claiming "verified live against Sonnet 5 / Opus 4.8" -- the
PR body states the Bedrock key had no access to those models and the error text
came from a customer traceback. They now cite the report.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Round 2 of review, on round 1's own fix.
1. THE tools GUARD READ THE WRONG DICT. It checked non_default_params while the
tools that reach the request are the MAPPED ones in optional_params, and the
two disagree in both directions:
* False positive -- it produced the very 400 it exists to prevent. A truthy
NON-LIST tools (a bare dict) satisfies the guard but is skipped by the
mapping loop's isinstance(value, list) check, so nothing lands in
optional_params["tools"]. Verified through the real get_optional_params: the
request came out with additionalModelRequestFields.tool_choice =
{"type":"any","disable_parallel_tool_use":true} and NO toolConfig key at all.
litellm guards this correctly on the native channel (`if len(bedrock_tools) >
0`); the passthrough channel had no equivalent.
* False negative -- parallel_tool_calls was silently ignored for a json_schema
response_format, which injects a synthetic tool into optional_params with
nothing in non_default_params. claude-sonnet-4-5-20250929-v1:0 is exactly
such a model in the cost map.
2. tool_choice="none" WAS REINVENTED AS "auto". map_tool_choice_values drops
"none" and returns None, which inside the config builder is indistinguishable
from "the caller sent nothing" -- so the else branch asserted type="auto" for a
caller who said "do not use tools". litellm's own Anthropic transform refuses
this explicitly (`if tool_choice == "none": pass`). On the wire today this is
equivalent, because auto is Anthropic's default once tools are present, but the
structure was wrong and the same class covers a model with
supports_tool_choice=False.
Also removes the comment-only `pass` branch left in the hot param loop (the
explanation already lives on the method), and hardens the name read against a
malformed pre-seeded tool_choice such as {"tool": "get_weather"}, which would
raise AttributeError.
Corrected an overstatement in the round-1 commit message: it listed
`parallel_tool_calls: None` under "narrowings, both removing risk", implying a
live defect. It was not reachable -- get_optional_params filters a value equal to
the param default, and the default for parallel_tool_calls is None, so an explicit
null never reaches map_openai_params. The isinstance(value, bool) guard stays as
defence in depth and its test does kill the mutation, but the test docstring now
says it is defensive rather than a regression pin.
Confirmed round 1 was right about parallel_tool_calls: TRUE: disable_parallel_tool_use
defaults to false (documented in-repo at types/llms/anthropic.py), no model
overrides that default, so emitting it is a wire-level no-op. Note for the PR body:
litellm's direct-Anthropic transform DOES emit it unconditionally, so the same
request now yields different payloads on anthropic/ vs bedrock/ -- behaviourally
identical, but worth stating so nobody "fixes" the divergence by reverting.
3 new tests; verified each fails with its guard reverted. 173 pass.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…hardening
Round 3 of review. The production logic held up -- 6 of 7 mutations killed, no
breakage across the full bedrock directory (1089 passed; the 5 errors are a
missing pytest-mock in this env and reproduce at base) -- but one round-2 test
asserted nothing.
test_response_format_injected_tools_still_honour_parallel_tool_calls picked
"anthropic.claude-sonnet-4-5-20250929-v1:0", which advertises
supports_native_structured_output, so _translate_response_format_param takes the
outputConfig branch and injects NO synthetic tool. optional_params had no tools,
the list was empty, and the whole assertion sat behind `if listed:` and never ran
-- it passed with the round-2 fix reverted, which made it the only coverage for
half that fix and worthless. Of the 59 models carrying
supports_parallel_tool_use_config exactly one lacks native structured output
("claude-sonnet-4-5-20250929-v1:0", bare id), so the test now uses that and
asserts the exact payload unconditionally:
toolConfig.tools = [json_tool_call]
additionalModelRequestFields.tool_choice = {"type": "tool",
"name": "json_tool_call", "disable_parallel_tool_use": True}
Verified it now dies under the mutation it exists to catch.
Dropped `and "type" in passthrough_tool_choice` from
_apply_parallel_tool_use_config: the builder sets type on all three branches, so
it could never be false -- the same reasoning round 1 used to delete the
unreachable merge branch two lines above.
Softened the guard comment, which claimed more than the guard delivers. A
non-empty optional_params["tools"] does not imply a non-empty toolConfig.tools:
_bedrock_tools_pt later drops tools carrying neither "function" nor
"input_schema" (the Responses built-ins, e.g. web_search), so a request whose
tools are all of that kind still reaches the provider with a tool_choice and no
toolConfig. Measured, and identical before this feature, so it is not a
regression -- but the comment should not assert the payload is prevented.
Added the one test that pins the non-dict native["tool"] hardening, which no
mutation was catching.
Confirmed by review that the tool_choice="none" early return is in the right
place: Anthropic's ToolChoiceNone carries only `type`, and
disable_parallel_tool_use exists on auto/any/tool only -- so emitting the bare
flag is the "missing field type" 400 this PR fixes, and {"type":"none",
disable_parallel_tool_use} would be rejected as an extra input. Emitting nothing
is the only correct option, which is also what litellm's own Anthropic transform
does.
174 pass.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Three rounds of review-and-fix, pushed to this branch@achraf-mer I ran three review→fix cycles on this and pushed the fixes as commits here (
The root causeThe passthrough config was built inside the param loop from the caller's raw
Fixed by building it after the loop and after the downgrade, derived from the final mapped Two narrowings
Heads-up for the PR body: litellm's direct-Anthropic transform does emit the flag unconditionally, so the same request now yields different payloads on Rounds 2 and 3 caught my own mistakes
Two notes on your testsThey were not vacuous — full revert produced 11 failures, and 12 of 12 targeted mutations were caught. But:
Residual, not fixedA non-empty Happy to move any of this into separate commits or drop pieces you disagree with — it's your PR. 🤖 Generated with Claude Code |
Brings h2o-main (upstream 1.93.0 release line + the h2o commits) up to the upstream v1.99.4 release. The 1.93.0 release-line backports on our side (BerriAI#33499, BerriAI#33847, BerriAI#33869, BerriAI#33904) are all present in v1.99.4 from main, so every file only they touched takes upstream's version; the h2o changes are re-applied on top of upstream's new code. Conflicted files and their resolution: - Dockerfile, docker/Dockerfile.database, docker/Dockerfile.non_root: upstream (the /opt/prisma bake from the 1.93 backports is in v1.99.4; no h2o lines). - litellm-rust/Cargo.lock, litellm-rust/crates/python-bridge/src/lib.rs: upstream (release-line backport only). - pyproject.toml, uv.lock: upstream. No h2o commit added a dependency. - litellm/litellm_core_utils/core_helpers.py, get_litellm_params.py, litellm/llms/anthropic/experimental_pass_through/messages/transformation.py, litellm/main.py, litellm/proxy/utils.py, litellm/router.py, litellm/types/guardrails.py, litellm/proxy/guardrails/guardrail_hooks/ model_armor/{__init__,file_scanning,model_armor}.py: upstream (release-line backports, e.g. coerce_token_limit / skip_unscannable_attachments, already in v1.99.4). - tests/test_litellm/proxy/guardrails/guardrail_hooks/test_model_armor.py, tests/test_litellm/proxy/test_proxy_utils.py, tests/test_litellm/test_main.py, tests/test_litellm/test_router.py: upstream (same backports). - litellm/litellm_core_utils/get_llm_provider_logic.py: upstream code, h2o redaction kept -- "dynamic_api_key needs to be a string." never echoes the key. - litellm/proxy/auth/user_api_key_auth.py: upstream's %-style logging, h2o redaction kept -- the custom-header debug line no longer logs the (abbreviated) key. - litellm/proxy/route_llm_request.py: upstream. The h2o lazy DB reload (reload_models_on_demand) is DROPPED: v1.99.4's route_request retries a ProxyModelNotFoundError through model_registry_read_through, which loads the missing model from the DB (bounded by a miss TTL and a resync budget). Upstream's read-through requires store_model_in_db=True. - litellm/llms/bedrock/chat/converse_transformation.py: upstream's fix for the same bug as h2o h2oai#24 (the toolChoice / tool_choice.type conflict and the missing type): native toolConfig.toolChoice keeps the caller's choice and the passthrough drops its type. h2o's rework that deleted the native toolChoice is dropped in its favour. Re-applied on top: the guards upstream lacks -- no passthrough without MAPPED tools, for tool_choice="none", or for a non-bool parallel_tool_calls (_drop_parallel_tool_use_config_with_nothing_to_say). - tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py: both sides kept; the h2o tests re-pinned to upstream's design (native toolChoice carries the choice, passthrough carries only disable_parallel_tool_use); the test of the removed h2o builder is dropped. Also, outside the conflicts: - litellm/llms/gemini/count_tokens/handler.py: upstream; its own "if not contents" guard supersedes the h2o None check. - litellm/llms/vertex_ai/vertex_llm_base.py: h2o base64 credentials kept, ruff-formatted. - litellm/integrations/h2o/router/h2orouter_policy.py: docstring no longer names the removed reload_models_on_demand. - gateway/routes/allowlist.py: the h2o /v1/router/models endpoint added to the gateway component (v1.99.4 splits routes across gateway/backend and test_component_allowlists fails on an uncovered route). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ports the upstream fix for the Bedrock Converse
parallel_tool_callsdefect onto our fork. Cherry-picked with-xfrom BerriAI#32605, original authorship preserved.The defect
Sending
parallel_tool_callsto a Bedrock-routed Claude model returns HTTP 500. Bedrock rejects the translated request becausetool_choiceis emitted without its requiredtypediscriminator:converse_transformation.pybuilds{"tool_choice": {"disable_parallel_tool_use": <bool>}}and passes it throughadditionalModelRequestFieldsto the Anthropic model, which validates against a schema requiringtype. The native Anthropic route builds the same object correctly, which is why only Bedrock fails.Reported against h2oGPTe 1.7.4-13 on a customer deployment, affecting all 5 Bedrock Claude models. See h2oai/h2ogpte#11994.
Why this port and not the one-liner
BerriAI#22638 hardcodes
"type": "auto". That contradicts the native channel when the caller senttool_choice: "required"(which maps totoolConfig {"any":{}}) or a named function. This PR derives the type from the caller'stool_choiceand drops the now-redundant nativetoolChoice, avoiding a second Bedrock rejection for conflicting directives.Verification
Wire-level capture through a real litellm proxy with a Bedrock deployment,
api_basepointed at a capture server so the serialized Converse body could be inspected. Requests are ordinary OpenAI chat-completions payloads.Before:
toolConfig.toolChoiceadditionalModelRequestFields.tool_choicenullparallel_tool_calls: truenull{"disable_parallel_tool_use": false}parallel_tool_calls: falsenull{"disable_parallel_tool_use": true}tool_choice: auto+parallel: true{"auto": {}}{"disable_parallel_tool_use": false}tool_choice: required+parallel: true{"any": {}}{"disable_parallel_tool_use": false}tool_choice: named+parallel: false{"tool": {...}}{"disable_parallel_tool_use": true}After:
toolConfig.toolChoiceadditionalModelRequestFields.tool_choicenullparallel_tool_calls: truenull{"type": "auto", "disable_parallel_tool_use": false}parallel_tool_calls: falsenull{"type": "auto", "disable_parallel_tool_use": true}tool_choice: auto+parallel: truenull{"type": "auto", ...}tool_choice: required+parallel: truenull{"type": "any", ...}tool_choice: named+parallel: falsenull{"type": "tool", "name": "get_air_quality", ...}Non-regression:
tool_choicewithoutparallel_tool_callsis byte-identical before and after for auto, required and named. The change is fully scoped to requests carrying the flag.Tests, same environment both sides:
The 10 extra passes are this PR's tests.
Corrected: an earlier revision of this description reported 17 failures on both sides. Those were an artefact of my test harness running without
pytest-asyncio, so everyasync deftest errored out. With the plugin loaded the suite is clean on both sides. The before/after comparison was unaffected, since the same harness ran both, but the failure count was wrong.Note:
converse_transformation.pyis byte-identical between upstream v1.93.0 and our pin, so there is no h2o customization in this file for the port to collide with.Not verified here
The AWS round trip. The Bedrock key available for testing has no access to those Claude models, so the
tool_choice.type: Field requiredresponse text comes from the customer traceback rather than a call made here. Everything up to the serialized request body is reproduced above.Follow-up
Taking this requires bumping the fork pin in h2ogpt_internal (
Dockerfileanddocs/linux_install.sh, same SHA in both) and rebuilding the h2ogpt image.