Skip to content

fix: ensure message history starts with a user turn for Gemini compatibility#1011

Open
nldhuyen0047 wants to merge 1 commit intoRightNow-AI:mainfrom
nldhuyen0047:fix/gemini-function-call-turn-ordering
Open

fix: ensure message history starts with a user turn for Gemini compatibility#1011
nldhuyen0047 wants to merge 1 commit intoRightNow-AI:mainfrom
nldhuyen0047:fix/gemini-function-call-turn-ordering

Conversation

@nldhuyen0047
Copy link
Copy Markdown

Summary

Fixes a crash/rejection from the Gemini API (INVALID_ARGUMENT) that occurs when the message history starts with a model (assistant) turn containing a functionCall block.

Root cause

After context trimming (validate_and_repair), the drain boundary can land on an assistant turn, leaving it at position 0. Gemini strictly requires:

  • The first message must be a user turn
  • A functionCall turn must be preceded by a user turn (not just followed by a functionResponse)

The existing sanitize_gemini_turns only checked that a functionCall was followed by a functionResponse — it did not guard against i == 0 (no preceding user turn).

Fix

  1. session_repair.rs — new ensure_starts_with_user(): drops leading assistant turns, re-runs validate_and_repair in a loop to clean up newly-orphaned ToolResult blocks.

  2. agent_loop.rs — calls ensure_starts_with_user() after context trim and after overflow recovery (both streaming and non-streaming loops).

  3. drivers/gemini.rssanitize_gemini_turns now drops functionCall parts when i == 0 as a last-resort defensive guard.

  4. channels/line.rs — minor: remove unnecessary borrow on base64::encode call (clippy lint).

Test plan

  • Send a message with Gemini after a long conversation that triggers context trimming — should no longer return INVALID_ARGUMENT
  • Verify other providers (OpenAI, Groq, Anthropic) are unaffected
  • cargo test --workspace passes

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant