Skip to content

The agent engineering platform.

fix(anthropic): serialize invalid tool calls as tool use on replay (#40864)

ccurme1ef23d6b7f6d
diff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.py
index a13a6ff1d0..d15acdedef 100644
--- a/libs/partners/anthropic/langchain_anthropic/chat_models.py
+++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py
@@ -957,8 +957,9 @@ def _format_messages(
else:
content = message.content
- # Ensure all tool_calls have a tool_use content block
- if isinstance(message, AIMessage) and message.tool_calls:
+ if isinstance(message, AIMessage) and (
+ message.tool_calls or message.invalid_tool_calls
+ ):
content = content or []
content = (
[{"type": "text", "text": message.content}]
@@ -981,6 +982,31 @@ def _format_messages(
cast("list", content).extend(
_lc_tool_calls_to_anthropic_tool_use_blocks(missing_tool_calls),
)
+ tool_use_ids.extend(
+ cast("str", _normalize_tool_call_id(tc["id"]))
+ for tc in missing_tool_calls
+ )
+ for invalid_call in message.invalid_tool_calls:
+ tool_call_id = invalid_call.get("id")
+ tool_name = invalid_call.get("name")
+ if not tool_call_id or not tool_name:
+ continue
+ normalized_id = _normalize_tool_call_id(tool_call_id)
+ if normalized_id in tool_use_ids:
+ continue
+ try:
+ args = json.loads(invalid_call.get("args") or "{}")
+ except json.JSONDecodeError:
+ args = {}
+ cast("list", content).append(
+ _AnthropicToolUse(
+ type="tool_use",
+ name=tool_name,
+ input=args if isinstance(args, dict) else {},
+ id=cast("str", normalized_id),
+ )
+ )
+ tool_use_ids.append(normalized_id)
if role == "assistant" and _i == last_non_system_index:
if isinstance(content, str):
diff --git a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py
index 704409d71b..f83b66a845 100644
--- a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py
+++ b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py
@@ -4144,6 +4144,60 @@ def test_format_messages_preserves_nonempty_thinking_field() -> None:
assert block["signature"] == "sig_xyz"
+ ("args", "expected_input"),
+ [('{"city":', {}), ('{"city":"Paris"}', {"city": "Paris"}), ("[1]", {})],
+)
+def test_invalid_tool_call_retains_tool_use_for_error_result(
+ args: str, expected_input: dict[str, Any]
+) -> None:
+ tool_call_id = "toolu_invalid"
+ ai_message = AIMessage(
+ content=[{"type": "text", "text": "Calling tool"}],
+ invalid_tool_calls=[{"name": "get_weather", "args": args, "id": tool_call_id}],
+ )
+ tool_message = ToolMessage(
+ "Tool call arguments were malformed.",
+ tool_call_id=tool_call_id,
+ status="error",
+ )
+
+ _, messages = _format_messages(
+ [HumanMessage("Check the weather"), ai_message, tool_message],
+ model=MODEL_NAME,
+ )
+
+ assert messages[1]["content"] == [
+ {"type": "text", "text": "Calling tool"},
+ {
+ "type": "tool_use",
+ "name": "get_weather",
+ "input": expected_input,
+ "id": tool_call_id,
+ },
+ ]
+ assert messages[2]["content"][0]["tool_use_id"] == tool_call_id
+ assert messages[2]["content"][0]["is_error"] is True
+
+
+def test_invalid_tool_call_does_not_duplicate_existing_tool_use() -> None:
+ ai_message = AIMessage(
+ content=[
+ {"type": "tool_use", "name": "get_weather", "input": {}, "id": "toolu_1"}
+ ],
+ tool_calls=[{"name": "get_weather", "args": {}, "id": "toolu_2"}],
+ invalid_tool_calls=[
+ {"name": "get_weather", "args": "bad", "id": "toolu_1"},
+ {"name": "get_weather", "args": "bad", "id": "toolu_2"},
+ {"name": "get_weather", "args": "bad", "id": None},
+ ],
+ )
+
+ _, messages = _format_messages([ai_message], model=MODEL_NAME)
+
+ assert [block["id"] for block in messages[0]["content"]] == ["toolu_1", "toolu_2"]
+
+
def test_v1_invalid_tool_call_retains_tool_use_for_error_result() -> None:
"""An error result must retain its Anthropic tool-use block on replay."""
tool_call_id = "toolu_invalid"