instructor icon indicating copy to clipboard operation
instructor copied to clipboard

fix(anthropic): use exclude_none=True in reask_anthropic_tools to fix Bedrock retry

Open adgapar opened this issue 7 months ago • 3 comments

Summary

Fixes #2277

When using AWS Bedrock with ANTHROPIC_TOOLS or ANTHROPIC_REASONING_TOOLS mode, retries after a Pydantic validation error fail with HTTP 400:

Error code: 400 - {'message': 'messages.3.content.1.tool_use.caller: Input should be a valid dictionary or object to extract fields from'}

Root cause: anthropic>=0.88.0 added a caller: Optional[Caller] = None field to ToolUseBlock. Bedrock does not populate this field (returns caller=None), while the direct Anthropic API correctly returns caller=DirectCaller(type='direct'). In reask_anthropic_tools, the failed completion is serialized via content.model_dump(), which includes "caller": null for Bedrock responses. The API rejects null for this field.

Fix

One-line change in reask_anthropic_tools — use exclude_none=True when serializing content blocks for the retry message:

# Before:
assistant_content.append(content.model_dump())

# After:
assistant_content.append(content.model_dump(exclude_none=True))

This strips "caller": null from Bedrock responses while leaving direct Anthropic API responses unchanged (where caller is a valid DirectCaller dict and is preserved).

Verification

Confirmed with live calls to both providers using an impossible Pydantic constraint (value: int = Field(ge=10, le=5)) to force retries:

  • Bedrock: ToolUseBlock(caller=None) → model_dump() → {"caller": null} → HTTP 400 on retry (broken before fix)
  • Direct Anthropic API: ToolUseBlock(caller=DirectCaller(type='direct')) → model_dump() → {"caller": {"type": "direct"}} → retries succeed (unaffected)

Test plan

  • [ ] Verify reask_anthropic_tools retry succeeds on AWS Bedrock after a Pydantic validation error
  • [ ] Verify direct Anthropic API retries are unaffected
  • [ ] Both ANTHROPIC_TOOLS and ANTHROPIC_REASONING_TOOLS modes (they share the same reask_anthropic_tools handler)

adgapar avatar Apr 16 '26 14:04 adgapar

Thanks for the fix. This is covered by #2301, which applies the same change and adds regression tests, so I am closing this one as a duplicate in favor of #2301.

jxnl-oai avatar May 10 '26 17:05 jxnl-oai

Correction to my earlier triage: keeping this PR as the preferred version for #2277.

jxnl-oai avatar May 10 '26 17:05 jxnl-oai

Correction to my earlier triage: keeping this PR as the preferred version for #2277.

I see you already merged #2301 , should I close this PR?

adgapar avatar May 10 '26 22:05 adgapar