crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] Gemini native provider never appends trailing user turn -> 400 'Requests ending with a model turn are not supported'

Open hvlcrs opened this issue 3 months ago • 4 comments

Description

GeminiCompletion._format_messages_for_gemini (the native Google Gen AI provider used for gemini/... and google/... model strings) converts assistant messages to Gemini's model role but never guards against the resulting contents list ending on a model turn. CrewAI's own agent loop can produce exactly that history -- e.g. handle_max_iterations_exceeded appending an assistant message and re-calling the LLM, or a task guardrail/guardrail_max_retries re-invocation after the last LLM turn -- and the malformed history is sent to Gemini's generateContent API verbatim, which rejects it.

Other providers already guard this exact case in LLM._format_messages_for_provider (Mistral and Ollama append a synthetic trailing user message when the last message is assistant), but that method is only used on the LiteLLM fallback path. The native Gemini/Google provider (crewai/llms/providers/gemini/completion.py), which is what actually handles gemini/* and google/* model strings once google-genai is installed, has no equivalent guard.

Steps to Reproduce

  • Build a CrewAI Agent/Task/Crew using LLM(model="gemini/gemini-flash-latest") (or any google/.../gemini/... model, with the google-genai extra installed so the native provider is used).

  • Give the task a guardrail with guardrail_max_retries set (or otherwise get the agent loop to hit handle_max_iterations_exceeded), so the executor re-invokes the LLM after an assistant/tool-call turn was already appended to history without an intervening user turn.

  • Run the crew against a real Gemini endpoint (or reproduce directly, see snippet below).

Minimal reproduction without needing a live agent run -- call the formatter directly with a history ending on an assistant turn:

from crewai.llms.providers.gemini.completion import GeminiCompletion

llm = GeminiCompletion(model="gemini-flash-latest", api_key="...")
contents, _ = llm._format_messages_for_gemini([
    {"role": "user", "content": "hi"},
    {"role": "assistant", "content": "partial"},
])
print([c.role for c in contents])  # ['user', 'model'] -- ends on 'model'
# Sending these `contents` via self.client.models.generate_content(...) 400s.

Expected behavior

_format_messages_for_gemini should guarantee the returned contents list ends on a user turn (mirroring the Mistral/Ollama guard already present in LLM._format_messages_for_provider), so the agent loop can safely re-invoke the LLM after an assistant/tool-call turn without a 400.

Screenshots/Code snippets

Actual error surfaced when this happens in a running agent (via the Gemini API, both AI Studio and Vertex enforce the same contents contract):

400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': 'Requests ending with a model turn are not supported.', 'status': 'INVALID_ARGUMENT'}}

We hit this specifically with a single-agent Crew whose Task sets guardrail=<completeness_check> and guardrail_max_retries=2 -- the guardrail retry path is what most reliably leaves contents ending on a model turn. It does not reproduce on short, guardrail-free crews (e.g. Google's own CrewAI+Gemini example at https://ai.google.dev/gemini-api/docs/crewai-example uses the identical LLM(model='gemini/...') setup but never hits the re-invoke-after-assistant paths, so the same latent gap doesn't surface there).

Operating System

Other (specify in additional context)

Python Version

3.11

crewAI Version

1.6.0

crewAI Tools Version

1.6.0

Virtual Environment

Venv

Evidence

Traced the missing guard to crewai/llms/providers/gemini/completion.py::_format_messages_for_gemini (both the crewai==1.6.0 release and current main): it maps role == "assistant" to Gemini's "model" role in two branches (the plain-text branch and the tool-call branch) but never checks whether the final entry in contents ends up being "model". Compare with crewai/llm.py::LLM._format_messages_for_provider, which already has:

# Handle Mistral models - they require the last message to have a role of 'user' or 'tool'
if "mistral" in self.model.lower():
    if messages and messages[-1]["role"] == "assistant":
        return [*messages, {"role": "user", "content": "Please continue."}]
    return messages

That guard is never reached for Gemini because gemini/google model strings resolve to the native GeminiCompletion class, not the LiteLLM fallback path.

Possible Solution

Add an equivalent guard at the end of GeminiCompletion._format_messages_for_gemini, appending a synthetic trailing user types.Content when contents[-1].role == "model".

Additional context

This surfaced running a CrewAI "bring your own" agent under kagent, but the bug is entirely in crewai's own message formatting and reproduces with plain CrewAI + google-genai installed, independent of kagent.

hvlcrs avatar Aug 13 '26 11:08 hvlcrs

Solid root-cause work...... the LiteLLM fallback having the guard while the native provider doesn't is exactly why it feels inconsistent. For anyone stuck before a PR merges: raising max_iterations and setting guardrail_max_retries=0 avoids the re-invoke path, and uninstalling google-genai makes gemini/* fall back to LiteLLM where the trailing-user guard already exists. Hope your PR lands, it's clearly the right fix.

MilkyWay008 avatar Aug 14 '26 13:08 MilkyWay008

This is a very AgentCI-shaped failure: the guardrail/retry path is supposed to make the run more reliable, but it leaves a provider-invalid history and the next request dies before the retry can do useful work.

We’re recruiting retry/history breakers like this. A portable fixture could run the same logical trajectory through native providers and bind: pre-retry history → provider-specific effective history → exact wire turn ordering → terminal outcome. If a synthetic turn is required, its provenance should be explicit instead of silently changing the conversation.

If you or an external agent contribute the network-free formatter fixture, we’ll preserve this issue as provenance and give permanent public credit/backlink in AgentCI’s Breaker Hall of Fame, plus help generalize it into a cross-provider retry-history regression.

AgentCI: https://github.com/jinngimk-lang/agentci Recognition: https://github.com/jinngimk-lang/agentci/blob/main/COMMUNITY.md

Affiliation disclosed; no CrewAI certification claim.

jinngimk-lang avatar Aug 17 '26 06:08 jinngimk-lang

Confirmed this is still present on current main — contents[-1].role == "model" goes straight into generate_content with no guard, while the LiteLLM path has had one since the Mistral/Ollama handling in _format_messages_for_provider.

I'm putting up a PR that mirrors the existing Mistral guard at the end of _format_messages_for_gemini: when the last content is a model turn, append a synthetic user turn ("Please continue.", same text the Mistral path uses) so the agent loop can safely re-invoke after a guardrail retry or handle_max_iterations_exceeded. Regression tests cover the trailing-assistant case plus the no-op cases (already-user-ending, tool-response-ending, system-only).

nolanchic avatar Aug 31 '26 17:08 nolanchic

OSS-147

linear[bot] avatar Sep 03 '26 10:09 linear[bot]