Skip to content

bug(core): 400 Bad Request "Requests ending with a model turn are not supported" when reading image files via ReadFile tool #29574

Closed

Description

@seokjeongeum

What happened?

When Gemini CLI attempts to inspect image files (e.g. .png) using the built-in ReadFile tool during an agentic session, the CLI encounters an unhandled API error and enters a broken state with repeated HTTP 400 errors:

  ✓  ReadFile  inspect_history_user.png → Read image file: inspect_history_user.png
✕ [API Error: [{
    "error": {
      "code": 400,
      "message": "Requests ending with a model turn are not supported.",
      "errors": [
        {
          "message": "Requests ending with a model turn are not supported.",
          "domain": "global",
          "reason": "badRequest"
        }
      ],
      "status": "INVALID_ARGUMENT"
    }
  }
  ]]
ℹ This request failed. Press F12 for diagnostics, or run /settings and change "Error Verbosity" to full for full details.
  ✓  ReadFile  inspect_history_kim.png → Read image file: inspect_history_kim.png
✕ [API Error: [{
    "error": {
      "code": 400,
      "message": "Requests ending with a model turn are not supported.",
      "errors": [
        {
          "message": "Requests ending with a model turn are not supported.",
          "domain": "global",
          "reason": "badRequest"
        }
      ],
      "status": "INVALID_ARGUMENT"
    }
  }
  ]]

Steps to Reproduce

  1. Start Gemini CLI (gemini) in a repository containing image assets (e.g., .png).
  2. Ask the model to inspect or verify a screenshot or UI element that triggers the internal ReadFile tool on an image file.
  3. Observe that after ReadFile <image>.png executes, the subsequent API call fails immediately with 400 INVALID_ARGUMENT: Requests ending with a model turn are not supported.
  4. Subsequent retries in the same session fail with the identical error.

Root Cause Analysis

The Google Gemini API enforces strict alternating conversation turns (user ↔ model). When sending contents, the request must never end with a model turn.

When ReadFile is executed on an image binary:

  1. The model initiates a functionCall turn (role: "model").
  2. The image processing or response payload generation fails, times out, or fails to properly append a trailing functionResponse / role: "user" turn back into the conversation buffer.
  3. The CLI's retry/recovery handler re-dispatches the conversation payload with the incomplete model turn at the tail of the array.
  4. The Gemini backend rejects the malformed payload with 400 Bad Request: Requests ending with a model turn are not supported.

What did you expect to happen?

  1. Image files read via ReadFile should either be handled properly as multimodal input or gracefully fail with a standard tool error without breaking the turn structure.
  2. The turn manager must ensure that any outgoing request payload to the Gemini API is correctly terminated (i.e. ending with a functionResponse or user turn), preventing 400 INVALID_ARGUMENT crashes.
  3. When a tool fails, the session should recover gracefully instead of getting stuck in an infinite error loop.

Client Information

  • OS: Windows 11 (MINGW64 / Git Bash) & Ubuntu 24.04 LTS
  • Gemini CLI Version: v0.61.0
  • Model: gemini-3.8-flash
  • Auth: Google OAuth (oauth-personal / Workspace)

Activity

  1. added
    status/need-triage
    area/core
    effort/small
    and removed
    status/need-triage
    on Sep 30, 2026
  2. gemini-cli commented on Sep 30, 2026

    @gemini-cli
    Contributor

    Effort Analysis:
    In packages/core/src/agents/local-executor.ts, the LocalAgentExecutor aggregates tool call results into a syncResults map using syncResults.set(call.request.callId, call.response.responseParts[0]). When a tool like ReadFile returns an image, convertToFunctionResponse inside packages/core/src/scheduler/tool-executor.ts returns multiple parts (the functionResponse part and the inlineData part as siblings). By exclusively capturing responseParts[0], the local-executor permanently drops the sibling inlineData part. Because the resulting user turn lacks the inlineData and the multimodal properties attached to the functionResponse get stripped by scrubPart in packages/core/src/utils/historyHardening.ts (called by geminiChat.ts), the user turn is effectively emptied and skipped. The history sent to the API then ends in the previous model turn, violating the strict alternating user/model API rule. Resolving this requires a trivial, highly localized change to packages/core/src/agents/local-executor.ts to accumulate the full responseParts array instead of just the first index, placing this firmly in the effort/small category.

  3. Hughhhhcoder commented on Oct 1, 2026

    @Hughhhhcoder

    The triage points to a localized loss of sibling response parts in LocalAgentExecutor, with a focused regression available around an image-returning ReadFile call. This looks like a good candidate for community contribution: preserve the full responseParts array for each call and verify that both the functionResponse and inlineData reach the next user turn. If a maintainer agrees, please add the help wanted label; I’d be happy to /assign and implement it.

  4. gemini-cli commented on Oct 1, 2026

    @gemini-cli
    Contributor

    👋 @Hughhhhcoder, thanks for your interest in this issue! We're reserving self-assignment for issues that have been marked with the help wanted label. Feel free to check out our list of issues that need attention.

  5. added
    area/agent
    priority/p2
    on Oct 12, 2026
  6. gemini-cli commented on Oct 12, 2026

    @gemini-cli
    Contributor

    Could you please provide the CLI version you are using (such as from the output of the /about command) so we can reproduce and investigate this issue?

  7. removed
    area/core
    on Oct 12, 2026
  8. added theissue type on Oct 12, 2026
  9. phansl commented on Oct 19, 2026

    @phansl

    11. Could you please provide the CLI version you are using (such as from the output of the /about command) so we can reproduce and investigate this issue?

    CLI Version 0.64.0
    Git Commit 4a0749a
    Model Auto
    Sandbox no sandbox
    OS win32

  10. added
    area/core
    and removed
    area/agent
    on Nov 6, 2026
  11. seokjeongeum commented on Nov 7, 2026

    @seokjeongeum
    Author

    Retest on 2026-11-07: stable v0.67.0 (dc6602ce) versus pinned main 62bab5b2, Linux Node 24.21.0/npm 11.19.0. Both were built in disposable checkouts with exact-lock offline npm ci --ignore-scripts, isolated homes and updates disabled; tracked source stayed clean.

    The 16 ordinary PNG scenarios pass on both versions: two model identifiers × context management on/off × fresh/resumed JSONL × one/two completed read_file calls. The probe uses the production ReadFileTool, GeminiChat, recorder/resume conversion and Code Assist request converter, with a controlled content generator. No Google provider request was sent.

    Six additional request-boundary cases (three shapes across those two model identifiers) show a meaningful difference:

    • Stable retains a signature-only part in all six. In two cases the final user turn has only thoughtSignature, with no usable text/tool/image payload.
    • Main removes those signature-only parts, supplies a valid terminal user turn, and retains the image sibling next to each tool response.

    This supports the normalization portion of merged #30153, which is present on main and absent from v0.67.0. See the pinned request-rendering code. Fixture SHA-256: bfa9bfa4f828514d7d7a67f274f59a0c4fc10dc5e3249c9d9514e8f31cd03240.

    Additional controlled subagent retest (November 8 KST): the actual compiled LocalAgentExecutor.run preserves one and two PNG/text sibling parts on main, but drops them after both single and parallel tool results on stable. Model and scheduler boundaries were stubbed; both loops reached GOAL. This verifies the sibling-part aggregation change in #30153. Fixture SHA-256: a026f90dab354e6a4cbe3f122fcabdbdfb1d9e5db1a1e4e062276b3edd226ca6.

    Limitation: this did not reproduce the original provider 400 or demonstrate its account-specific cause. A live retest with a build containing #30153 is still needed before claiming the production report resolved. Leaving this issue open.

  12. seokjeongeum commented on Nov 11, 2026

    @seokjeongeum
    Author

    I retested upstream main e5d88fb2, which contains #30153, and PR #30228 at e879341a on Linux with Node v24.21.0.

    Five controlled assertions from #30228 failed when run against main’s implementation and passed on the PR. They cover the interrupted model turn when the model returns empty or signature-only content after a tool call, role alternation, and the next-speaker check.

    With the live Gemini Developer API and gemini-3.8-flash, one of three main sessions successfully read both PNGs with read_file, returned both image markers, and answered a plain-text follow-up in the same session. A second session timed out waiting for a response after the first image read. The third returned the first marker and hit HTTP 429 on the second image prompt. On the PR, the first image read succeeded before HTTP 429 on the post-tool request. One retry hit HTTP 429 before the tool ran.

    The observed post-tool requests ended in a user turn with an image. The reported terminal-model HTTP 400 did not occur in these live attempts. Verification with the original Workspace OAuth account remains pending.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/coreeffort/smallkind/bugpriority/p2status/bot-triagedstatus/need-information

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions