Skip to content

fix: prevent assistant-first tool-use history after context reduction#1750

Open
KKamJi98 wants to merge 1 commit intostrands-agents:mainfrom
KKamJi98:fix/sliding-window-gemini-turn-order
Open

fix: prevent assistant-first tool-use history after context reduction#1750
KKamJi98 wants to merge 1 commit intostrands-agents:mainfrom
KKamJi98:fix/sliding-window-gemini-turn-order

Conversation

@KKamJi98
Copy link

Description

Motivation

SlidingWindowConversationManager.reduce_context() can produce invalid history for Gemini in long tool-heavy chats:

  1. _truncate_tool_results() aborts early when latest toolResult is already truncated.
  2. Fallback trimming can leave assistant toolUse as the first message.

Gemini rejects this with 400 INVALID_ARGUMENT (function call turn ...). This change keeps context reduction stable while preserving existing behavior for assistant text-only starts.

Resolves #1749

Public API Changes

No public API changes.

What changed

  • Continue scanning older messages for truncatable toolResult entries when the latest candidate cannot be truncated.
  • Skip already-truncated toolResult entries instead of returning early from _truncate_tool_results().
  • Sanitize reduced history only when it starts with assistant toolUse (function-call start), preventing invalid Gemini turn order.
  • Add regression tests for:
    • older candidate truncation,
    • assistant-first tool-use trimming behavior,
    • overflow when no valid user-start remains.

Related Issues

Documentation PR

N/A

Type of Change

Bug fix

Testing

How have you tested the change? Verify that the changes do not break functionality or introduce warnings in consuming repositories: agents-docs, agents-tools, agents-cli

  • I ran hatch run prepare

Checklist

  • I have read the CONTRIBUTING document
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] SlidingWindowConversationManager can emit assistant-first function call history causing Gemini 400 INVALID_ARGUMENT

1 participant