fix: handle dangling tool results when history is cleared due to size limits #1527
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.
Problem
We receive
Improperly formed requests
failures due to:Message with ToolResults must be preceded by AssistantResponseMessage
There is an edge case where when the context size is exceeded, we remove the history entirely if we cannot find a valid userInputMessage without toolResults to trim up to. This results in validation issues on the backend if the new UserInputMessage contains toolResults (there is no existing previous message with toolUses to pair with the toolResult).
Solution
Short-term solution: Abandon the toolResult for this case and inform the LLM that the context limit was execeeded.
This is the current approach done by CLI: https://github.com/aws/amazon-q-developer-cli/blob/main/crates/cli/src/cli/chat/conversation_state.rs#L327
TODO:
Long-term: Come up with a way to preserve the history while fitting it in the context char limit
Testing
Reproduced the issue. Now instead of returning an Improperly formed request, the user is able to continue:
Screen.Recording.2025-06-04.at.9.41.35.PM.mov
License
By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.