-
Notifications
You must be signed in to change notification settings - Fork 3k
fix(anthropic): reorder tool_result parts to front of combined user messages #8474
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
fix(anthropic): reorder tool_result parts to front of combined user messages #8474
Conversation
…API error - Modified groupIntoBlocks to ensure tool messages create separate user blocks - Prevents Claude API error: 'tool_use ids were found without tool_result blocks immediately after' - Added regression test reproducing the exact scenario from issue vercel#8318 - All existing tests continue to pass (98/98) Fixes vercel#8318
}); | ||
|
||
it('should combine user and tool messages', async () => { | ||
it('should separate tool and user messages', async () => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm hesitant to just change the current behavior. Given that it has a test, it might have been intentional.
@lgrammel introduced this test as part of #2067, which in turn fixed #2047
AI_APICallError: messages: roles must alternate between "user" and "assistant", but found multiple "user" roles in a row.
I think this "fix" could re-introduce the above error message? Could you look into that and make sure we don't introduce a regression?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@gr2m Thanks for the thoughtful feedback and for pointing out the potential for a regression. I'll dig into the history of the related issues you mentioned and will report back here with my findings.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @gr2m, thanks for the valuable feedback and the context on the role alternation issue. You were right to flag that as a potential regression.
I've updated the PR with a new approach. It addresses the Claude API validation error by reordering the content parts within the user message, ensuring tool_result always comes first.
This preserves the message-combining logic from #2067, so the original role-alternation fix remains intact. All existing tests pass, and I've added new ones for this specific tool-use case. I also confirmed this works against the live Claude API.
Ready for another look when you have a moment.
- Addresses Claude API validation requiring tool_result immediately after tool_use - Preserves role alternation by reordering within combined user messages - Maintains message combining behavior from vercel#2067 that solved vercel#2047 - Added comprehensive tests for single/multi-tool scenarios
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can you update the pull request title as well? That will be used in the release notes
packages/anthropic/src/convert-to-anthropic-messages-prompt.test.ts
Outdated
Show resolved
Hide resolved
- Update changeset to reflect reordering approach instead of separation - Remove issue number from test name per maintainer guidance - Make test descriptions focus on actual behavior (tool_result before text)
Hi @gr2m, I've updated the PR title and description to better reflect the reordering approach, and cleaned up the test names as you suggested. Let me know what you think. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great first PR to the AI SDK! Congratulations! And thank you 💐
Thanks so much, @gr2m! I really appreciate the guidance and the opportunity to contribute. Glad I could help get this fixed! |
Still seems to be an issue. Tried testing a sample API call using the test inputs below. Using versions: Test input const modelMessages = [
{
role: "user",
content: [{ type: "text", text: "generate 10 items" }]
},
{
role: "assistant",
content: [
{
type: "tool-call",
toolCallId: "tool-example-123",
toolName: "json",
input: {
message: "generate 10 items"
}
},
{
type: "text",
text: "I generated code for 10 items."
}
]
},
{
role: "tool",
content: [
{
type: "tool-result",
toolCallId: "tool-example-123",
toolName: "json",
output: {
type: "json",
value: {
code: "export const code = () => [...]",
packageJson: "{}"
}
}
}
]
},
{
role: "user",
content: [{ type: "text", text: "generate 100 items" }]
}
]; error message
|
@abhi-slash-git could you please create a separate issue with a minimal reproduction? You can mention both of us and we can look into it. Comments on closed issues/PRs get easily lost. |
Reverting because of #8516 |
Fixes #8318
Description
fix(anthropic): reorder tool_result parts to front of combined user messages
Background
Why was this change necessary?
Users were encountering a Claude API error when using tool calling functionality:
This error occurred because the AI SDK's Anthropic message converter was placing user text before
tool_result
content in combined user messages, violating Claude's strict validation requirements.The Problem:
tool_use
→ expectstool_result
in the very next message[tool_result, user_text]
in one messageSummary
What did you change?
Modified the user message processing in
convert-to-anthropic-messages-prompt.ts
:tool_result
vs other content partstool_result
parts now appear first in combined messagesResult
[{role: 'user', content: [user_text, tool_result]}]
[{role: 'user', content: [tool_result, user_text]}]
Manual Verification
How I manually verified the fix:
generateObject
fails using Claude provider fails with "tool_use ids were found without tool_result" error on valid role:'tool' message structure #8318Test Scenarios Verified:
is_error: true
) with user contentTasks
PR Checklist:
Tests have been added / updated (for bug fixes / features)
Documentation has been added / updated (for bug fixes / features)
A patch changeset for relevant packages has been added (for bug fixes / features)
pretty-carpets-cheer.md
for@ai-sdk/anthropic
Formatting issues have been fixed (run
pnpm prettier-fix
)I have reviewed this pull request (self-review)
Future Work
Potential follow-up improvements (not in scope for this bug fix):
Note: These are enhancements, not requirements for fixing the reported bug.
Related Issues
generateObject
fails using Claude provider fails with "tool_use ids were found without tool_result" error on valid role:'tool' message structure #8318 - generateObject fails using Claude provider with "tool_use ids were found without tool_result" errorTechnical Details
Files Changed:
packages/anthropic/src/convert-to-anthropic-messages-prompt.ts
(core reordering logic)packages/anthropic/src/convert-to-anthropic-messages-prompt.test.ts
(comprehensive test updates).changeset/pretty-carpets-cheer.md
(release notes)Key Implementation
packages/anthropic/src/convert-to-anthropic-messages-prompt.ts
(core reordering logic)packages/anthropic/src/convert-to-anthropic-messages-prompt.test.ts
(comprehensive test updates).changeset/pretty-carpets-cheer.md
(release notes)