Skip to content

Commit 1ef23d6

Browse files
ccurmeopen-sweroshangardi
authored
fix(anthropic): serialize invalid tool calls as tool use on replay (#40864)
Co-authored-by: ccurme <[email protected]> Co-authored-by: open-swe[bot] <[email protected]> Co-authored-by: roshangardi <[email protected]>
1 parent 80b7409 commit 1ef23d6

2 files changed

Lines changed: 82 additions & 2 deletions

File tree

‎libs/partners/anthropic/langchain_anthropic/chat_models.py‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -957,8 +957,9 @@ def _format_messages(
957957
else:
958958
content = message.content
959959

960-
# Ensure all tool_calls have a tool_use content block
961-
if isinstance(message, AIMessage) and message.tool_calls:
960+
if isinstance(message, AIMessage) and (
961+
message.tool_calls or message.invalid_tool_calls
962+
):
962963
content = content or []
963964
content = (
964965
[{"type": "text", "text": message.content}]
@@ -981,6 +982,31 @@ def _format_messages(
981982
cast("list", content).extend(
982983
_lc_tool_calls_to_anthropic_tool_use_blocks(missing_tool_calls),
983984
)
985+
tool_use_ids.extend(
986+
cast("str", _normalize_tool_call_id(tc["id"]))
987+
for tc in missing_tool_calls
988+
)
989+
for invalid_call in message.invalid_tool_calls:
990+
tool_call_id = invalid_call.get("id")
991+
tool_name = invalid_call.get("name")
992+
if not tool_call_id or not tool_name:
993+
continue
994+
normalized_id = _normalize_tool_call_id(tool_call_id)
995+
if normalized_id in tool_use_ids:
996+
continue
997+
try:
998+
args = json.loads(invalid_call.get("args") or "{}")
999+
except json.JSONDecodeError:
1000+
args = {}
1001+
cast("list", content).append(
1002+
_AnthropicToolUse(
1003+
type="tool_use",
1004+
name=tool_name,
1005+
input=args if isinstance(args, dict) else {},
1006+
id=cast("str", normalized_id),
1007+
)
1008+
)
1009+
tool_use_ids.append(normalized_id)
9841010

9851011
if role == "assistant" and _i == last_non_system_index:
9861012
if isinstance(content, str):

‎libs/partners/anthropic/tests/unit_tests/test_chat_models.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4144,6 +4144,60 @@ def test_format_messages_preserves_nonempty_thinking_field() -> None:
41444144
assert block["signature"] == "sig_xyz"
41454145

41464146

4147+
@pytest.mark.parametrize(
4148+
("args", "expected_input"),
4149+
[('{"city":', {}), ('{"city":"Paris"}', {"city": "Paris"}), ("[1]", {})],
4150+
)
4151+
def test_invalid_tool_call_retains_tool_use_for_error_result(
4152+
args: str, expected_input: dict[str, Any]
4153+
) -> None:
4154+
tool_call_id = "toolu_invalid"
4155+
ai_message = AIMessage(
4156+
content=[{"type": "text", "text": "Calling tool"}],
4157+
invalid_tool_calls=[{"name": "get_weather", "args": args, "id": tool_call_id}],
4158+
)
4159+
tool_message = ToolMessage(
4160+
"Tool call arguments were malformed.",
4161+
tool_call_id=tool_call_id,
4162+
status="error",
4163+
)
4164+
4165+
_, messages = _format_messages(
4166+
[HumanMessage("Check the weather"), ai_message, tool_message],
4167+
model=MODEL_NAME,
4168+
)
4169+
4170+
assert messages[1]["content"] == [
4171+
{"type": "text", "text": "Calling tool"},
4172+
{
4173+
"type": "tool_use",
4174+
"name": "get_weather",
4175+
"input": expected_input,
4176+
"id": tool_call_id,
4177+
},
4178+
]
4179+
assert messages[2]["content"][0]["tool_use_id"] == tool_call_id
4180+
assert messages[2]["content"][0]["is_error"] is True
4181+
4182+
4183+
def test_invalid_tool_call_does_not_duplicate_existing_tool_use() -> None:
4184+
ai_message = AIMessage(
4185+
content=[
4186+
{"type": "tool_use", "name": "get_weather", "input": {}, "id": "toolu_1"}
4187+
],
4188+
tool_calls=[{"name": "get_weather", "args": {}, "id": "toolu_2"}],
4189+
invalid_tool_calls=[
4190+
{"name": "get_weather", "args": "bad", "id": "toolu_1"},
4191+
{"name": "get_weather", "args": "bad", "id": "toolu_2"},
4192+
{"name": "get_weather", "args": "bad", "id": None},
4193+
],
4194+
)
4195+
4196+
_, messages = _format_messages([ai_message], model=MODEL_NAME)
4197+
4198+
assert [block["id"] for block in messages[0]["content"]] == ["toolu_1", "toolu_2"]
4199+
4200+
41474201
def test_v1_invalid_tool_call_retains_tool_use_for_error_result() -> None:
41484202
"""An error result must retain its Anthropic tool-use block on replay."""
41494203
tool_call_id = "toolu_invalid"

0 commit comments

Comments
 (0)