openclaw - 💡(How to fix) Fix [Bug]: Google Gemini Image Generation Failure [1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
openclaw/openclaw#59486Fetched 2026-04-08 02:25:20
View on GitHub
Comments
0
Participants
1
Timeline
2
Reactions
0
Author
Participants
Timeline (top)
labeled ×2

The image_generate tool returns a fetch failed error when calling the Google Gemini image generation model, but direct API calls to Google work successfully.

Error Message

All image generation models failed (2): 
  google/gemini-3.1-flash-image-preview: fetch failed 
  google/gemini-3-pro-image-preview: fetch failed

Root Cause

Root Cause Analysis

Fix Action

Fix / Workaround

  • google/gemini-3.1-flash-image-preview may not be correctly mapped to the API endpoint

Workaround

Code Example

All image generation models failed (2): 
  google/gemini-3.1-flash-image-preview: fetch failed 
  google/gemini-3-pro-image-preview: fetch failed

---



---

#!/usr/bin/env python3
import requests
import base64

def generate_image_gemini(prompt, api_key, output_path):
    endpoint = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent?key={api_key}"

    payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
    }

    response = requests.post(endpoint, headers={"Content-Type": "application/json"}, json=payload)
    data = response.json()

    for part in data["candidates"][0]["content"]["parts"]:
        if "inlineData" in part and part["inlineData"]["mimeType"].startswith("image/"):
            image_data = base64.b64decode(part["inlineData"]["data"])
            with open(output_path, "wb") as f:
                f.write(image_data)
            return output_path

    raise Exception("No image in response")
RAW_BUFFERClick to expand / collapse

Bug type

Crash (process/app exits or hangs)

Beta release blocker

No

Summary

The image_generate tool returns a fetch failed error when calling the Google Gemini image generation model, but direct API calls to Google work successfully.

Error Message

All image generation models failed (2): 
  google/gemini-3.1-flash-image-preview: fetch failed 
  google/gemini-3-pro-image-preview: fetch failed

Steps to reproduce

<html> <body> <!--StartFragment--><p>Step 1: Using OpenClaw image_generate Tool (Fails)</p> <pre><code class="fenced-code-block language-javascript">// Tool call { &quot;tool&quot;: &quot;image_generate&quot;, &quot;params&quot;: { &quot;model&quot;: &quot;google/gemini-3.1-flash-image-preview&quot;, &quot;prompt&quot;: &quot;A futuristic AI assistant&quot; } }</code></pre> <p><strong>Result</strong>: ❌ <code>fetch failed</code></p> <h3 id="step-2-direct-api-call-using-curl-success" class="atx">Step 2: Direct API Call Using curl (Success)</h3> <pre><code class="fenced-code-block language-bash">curl -X POST \ &quot;https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent?key=API_KEY&quot; \ -H &#39;Content-Type: application/json&#39; \ -d &#39;{ &quot;contents&quot;: [{&quot;parts&quot;:[{&quot;text&quot;:&quot;Draw a futuristic AI office&quot;}]}], &quot;generationConfig&quot;: {&quot;responseModalities&quot;:[&quot;TEXT&quot;,&quot;IMAGE&quot;]} }&#39;</code></pre> <p><strong>Result</strong>: ✅ Successfully returns image data</p> <h3 id="step-3-using-python-script-with-same-api-call-success" class="atx">Step 3: Using Python Script with Same API Call (Success)</h3> <pre><code class="fenced-code-block language-python">import requests

response = requests.post( "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent?key=API_KEY", headers={"Content-Type": "application/json"}, json={ "contents": [{"parts": [{"text": "Draw a futuristic AI office"}]}], "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]} } )

Successfully generates and saves image</code></pre>

<p><strong>Result</strong>: ✅ Successfully generates a 925KB PNG image</p> <hr> <h2 id="environment-verification" class="atx">Environment Verification</h2>
Check ItemStatusVerification Method
API Key Validity✅ NormalChat functionality works normally
Network Connectivity✅ Connectedcurl can access API normally
Proxy Configuration✅ CorrectTerminal curl and Python both go through proxy
Model Existence✅ ConfirmedAPI returns model list containing target model
API Billing✅ EnabledDirect call success indicates billing is active
<hr> <!--EndFragment--> </body> </html>

Expected behavior

The image_generate tool should successfully generate images just like direct API calls.

Actual behavior

Returns fetch failed error, unable to generate images.

OpenClaw version

2026.3.31 (213a704)

Operating system

Ubuntu

Install method

No response

Model

google/gemini-3.1-flash-image-preview

Provider / routing chain

openclaw ➡️google

Additional provider/model setup details

No response

Logs, screenshots, and evidence

Impact and severity

No response

Additional information

Root Cause Analysis

Hypothesized Causes

The image_generate tool in OpenClaw may have one of the following issues:

  1. Incorrect API Endpoint
  • May be using the Imagen predict endpoint instead of Gemini's generateContent
  1. Missing Required Parameters
  • Gemini image generation requires "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
  • OpenClaw may not be passing this parameter
  1. Incompatible Request Format
  • Request body structure may not match the format expected by Gemini API
  1. Model Name Resolution Issue
  • google/gemini-3.1-flash-image-preview may not be correctly mapped to the API endpoint

Workaround

Use the following alternative solution until the bug is fixed:

#!/usr/bin/env python3
import requests
import base64

def generate_image_gemini(prompt, api_key, output_path):
    endpoint = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent?key={api_key}"

    payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
    }

    response = requests.post(endpoint, headers={"Content-Type": "application/json"}, json=payload)
    data = response.json()

    for part in data["candidates"][0]["content"]["parts"]:
        if "inlineData" in part and part["inlineData"]["mimeType"].startswith("image/"):
            image_data = base64.b64decode(part["inlineData"]["data"])
            with open(output_path, "wb") as f:
                f.write(image_data)
            return output_path

    raise Exception("No image in response")

Suggested Fixes

  1. Verify image_generate Tool Implementation Logic
  • Check if the generateContent endpoint is being used correctly
  • Check if the responseModalities parameter is being passed
  1. Update Model Mapping
  • Ensure google/gemini-3.1-flash-image-preview is correctly mapped to the Gemini API
  1. Add Detailed Error Logging
  • Current fetch failed is too generic; should return specific HTTP error codes and response content
  1. Test Coverage
  • Add integration tests for the Google Gemini image generation API

extent analysis

TL;DR

The image_generate tool in OpenClaw likely has an issue with its API endpoint, required parameters, or request format, causing a fetch failed error when calling the Google Gemini image generation model.

Guidance

  • Verify the image_generate tool implementation logic to ensure it uses the correct generateContent endpoint and passes the required responseModalities parameter.
  • Check the model mapping to ensure google/gemini-3.1-flash-image-preview is correctly mapped to the Gemini API.
  • Add detailed error logging to provide more specific error information instead of the generic fetch failed message.
  • Consider using the provided Python workaround script as a temporary solution until the issue is fixed.

Example

The provided Python script can be used as a workaround:

import requests
import base64

def generate_image_gemini(prompt, api_key, output_path):
    endpoint = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent?key={api_key}"

    payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
    }

    response = requests.post(endpoint, headers={"Content-Type": "application/json"}, json=payload)
    data = response.json()

    for part in data["candidates"][0]["content"]["parts"]:
        if "inlineData" in part and part["inlineData"]["mimeType"].startswith("image/"):
            image_data = base64.b64decode(part["inlineData"]["data"])
            with open(output_path, "wb") as f:
                f.write(image_data)
            return output_path

    raise Exception("No image in response")

Notes

The issue may be specific to the OpenClaw image_generate tool and its implementation. The provided workaround script uses the Google Gemini API directly, which may not be affected by the same issue.

Recommendation

Apply the workaround using the provided Python script until the image_generate tool issue is fixed, as it provides a functional alternative for generating images using the Google Gemini model.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

FAQ

Expected behavior

The image_generate tool should successfully generate images just like direct API calls.

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING