fix(core): remove orphaned ToolMessages in trim_message #33265
+307
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
Fixes a bug where
trim_messages
withstrategy="last"
could create invalid message histories by orphaningToolMessage
s when their correspondingAIMessage
withtool_calls
was trimmed away.Issue
When trimming message history, if a
ToolMessage
was included in the trimmed result but its correspondingAIMessage
(containing the tool call that theToolMessage
responds to) was removed, this created an orphanedToolMessage
with atool_call_id
that references a non-existent tool call. This invalid message history would be rejected by most LLM APIs.Fix
Added a
_remove_orphaned_tool_messages()
helper function that:tool_call_id
s fromAIMessage
sToolMessage
s whosetool_call_id
doesn't match a valid tool callToolMessage
s removedThis function is called in
_first_max_tokens()
before returning, which fixes bothstrategy="first"
andstrategy="last"
(since "last" internally uses "first" with reversed messages).Example
Before (broken):
After (fixed):
Issue
Resolves #33245
Dependencies
None - this is a pure bug fix with no new dependencies.
Testing