sdk-python
sdk-python copied to clipboard
[BUG] SlidingWindowConversationManager can emit assistant-first function call history causing Gemini 400 INVALID_ARGUMENT
Checks
- [x] I have updated to the lastest minor and patch version of Strands
- [x] I have checked the documentation and this is not expected behavior
- [x] I have searched ./issues and there are no duplicates of my issue
Strands Version
1.23.0
Python Version
3.12.12
Operating System
Ubuntu 24.04 LTS 6.8.0-94-generic
Installation Method
Docker + uv (uv pip install --system .)
Steps to Reproduce
- Use
SlidingWindowConversationManager(window_size=40)in a long multi-turn chat with tool calls. - Let history reach context reduction path where latest
toolResultwas already replaced with:status: "error"content: [{"text": "The tool result was too large!"}]
reduce_context()calls_truncate_tool_results()once on the latesttoolResultmessage._truncate_tool_results()returnsFalseimmediately when it sees that already-truncatedtoolResult.reduce_context()falls through to window trimming.- Trim result can start with an assistant
toolUseturn. - Send that history to Gemini model.
Minimal sequence shape that can be produced after trimming:
[
{"role":"assistant","content":[{"toolUse":{"toolUseId":"a1","name":"get_pod_status","input":{}}}]},
{"role":"user","content":[{"toolResult":{"toolUseId":"a1","status":"success","content":[{"text":"..."}]}}]}
]
Expected Behavior
- Context reduction should continue searching for another truncatable
toolResultwhen latest one is already truncated. - Reduced history should not start with assistant
toolUse(function call) turn. - Gemini requests should avoid 400 invalid turn-order errors caused by conversation reduction.
Actual Behavior
_truncate_tool_results()short-circuits on already-truncated latest result, so no other candidates are attempted.- Window trimming may leave assistant function-call turn as the first message.
- Gemini returns
400 INVALID_ARGUMENTwith message similar to:
Please ensure that function call turn comes immediately after a user turn or after a function response turn.
Additional Context
- Related logging before failure frequently includes:
ToolResult has already been updated, skipping overwrite
- This appears to be a combination of two issues:
- Early return in
_truncate_tool_results()on already-truncated result. - No post-trim guard against assistant
toolUseat history start.
- Early return in
Possible Solution
- In
reduce_context(), scan older messages for truncation candidates when latest candidate cannot be truncated. - In
_truncate_tool_results(), skip already-truncated entries (continue) instead of aborting. - After trimming/truncation, sanitize leading assistant
toolUseturns so reduced history does not start with a function call.
Related Issues
- #1545 (related to tool-result truncation behavior; does not cover turn-order bug)