Skip to content

anthropic[patch]: correctly handle tool msg with empty list #27109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions libs/partners/anthropic/langchain_anthropic/chat_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,13 @@ def _merge_messages(
for curr in messages:
curr = curr.model_copy(deep=True)
if isinstance(curr, ToolMessage):
if isinstance(curr.content, list) and all(
isinstance(block, dict) and block.get("type") == "tool_result"
for block in curr.content
if (
isinstance(curr.content, list)
and curr.content
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: maybe worth adding a code comment for posterity

and all(
isinstance(block, dict) and block.get("type") == "tool_result"
for block in curr.content
)
):
curr = HumanMessage(curr.content) # type: ignore[misc]
else:
Expand Down
21 changes: 21 additions & 0 deletions libs/partners/anthropic/tests/unit_tests/test_chat_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,13 @@ def test__merge_messages() -> None:
"text": None,
"name": "blah",
},
{
"tool_input": {"a": "c"},
"type": "tool_use",
"id": "3",
"text": None,
"name": "blah",
},
]
),
ToolMessage("buz output", tool_call_id="1", status="error"), # type: ignore[misc]
Expand All @@ -175,6 +182,7 @@ def test__merge_messages() -> None:
],
tool_call_id="2",
), # type: ignore[misc]
ToolMessage([], tool_call_id="3"), # type: ignore[misc]
HumanMessage("next thing"), # type: ignore[misc]
]
expected = [
Expand All @@ -198,6 +206,13 @@ def test__merge_messages() -> None:
"text": None,
"name": "blah",
},
{
"tool_input": {"a": "c"},
"type": "tool_use",
"id": "3",
"text": None,
"name": "blah",
},
]
),
HumanMessage( # type: ignore[misc]
Expand All @@ -223,6 +238,12 @@ def test__merge_messages() -> None:
"tool_use_id": "2",
"is_error": False,
},
{
"type": "tool_result",
"content": [],
"tool_use_id": "3",
"is_error": False,
},
{"type": "text", "text": "next thing"},
]
),
Expand Down
Loading