ToolUseBlock and ToolUseBlockParam type conflict for caller nullability
- Anthropic sdk version 0.97.0
ToolUseBlockhascaller: Optional[Caller] = Nonewhich is in conflict withToolUseBlockParamwhich hascaller: Caller(total=False). This means if you convert ToolUseBlock to ToolUseBlockParam using .to_dict() method the caller field errors.- Symptom for me: in Bedrock client after a tool is used sending back response gives
Error code: 400 - {'message': 'messages.13.content.1.tool_use.caller: Input should be a valid dictionary or object to extract fields from'}. Doesn't happen with vertex/anthropic clients. Possibly in bedrock client 'caller' field is being set, and thus not excluded in to_dict() method. Explicit.to_dict(exclude_none=True)works
确认了,这个 bug 只在 Bedrock client 上复现,因为我们踩过同样的坑。
问题分析
Bedrock client 在构造 tool_use response 时,会把 caller 字段序列化进 request body。但 ToolUseBlockParam 的 typeDef 用了 total=False,这意味着 caller 要么不存在,要么是完整的 Caller 对象 —— 不能是 None。
当 Bedrock response 里的 caller 是 None 时,to_dict() 会把它序列化为 {"caller": None},然后 Bedrock API 就炸了:Input should be a valid dictionary or object。
临时解决方案
你提到的 .to_dict(exclude_none=True) 确实管用,但如果你用的是高层 API(比如 bedrock_client.messages.create()),你可能没有机会直接调 to_dict()。
一个更彻底的 workaround:
from anthropic.types import ToolUseBlock
# 在传回 response 之前,手动清理 caller
def clean_tool_use(tool_use: ToolUseBlock) -> dict:
d = tool_use.model_dump(exclude_none=True)
return d
这是 SDK 的问题
根本原因是 ToolUseBlock 和 ToolUseBlockParam 的 caller 字段定义不一致:
ToolUseBlock:caller: Optional[Caller] = None— 允许 NoneToolUseBlockParam:caller: Callerwithtotal=False— 要么有值,要么不存在
这导致 ToolUseBlock.to_dict() 和 ToolUseBlock.model_dump() 都会生成 {"caller": None},但 Bedrock API 不接受。
希望 SDK 团队能把 ToolUseBlockParam 改成 caller: Optional[Caller] 或者把 to_dict() 改成默认 exclude_none=True。
参考:我们在 miaoquai.com 的 AI Agent 工具导航中收录了各种 SDK 的踩坑经验:https://miaoquai.com/tools/
Hi, I'd like to work on this. I'll submit a PR shortly.
Thanks for the report! This was fixed in v0.122.0 (https://github.com/anthropics/anthropic-sdk-python/commit/cd40aab995181aa44e9fbdb7b6ce1fa82357c18b)