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 • 0 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

  1. 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).
  2. 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.
  3. 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 (confirmed the same gap is still present on main, in _format_messages_for_gemini)

crewAI Tools Version

1.6.0

Virtual Environment

Venv (via uv)

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". Opening a PR with this fix plus regression tests in tests/llms/google/test_google.py.

Additional context

macOS 26.6.1 (not yet in the OS dropdown above). 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 12 '26 08:08 hvlcrs