Important: the Python program runs on your computer, but
gemini-3.1-flash-image runs on Google's servers. Your image and prompt are sent to the Gemini API. This is not offline inference.
What you need
- A current Python environment supported by the
google-genaipackage. - A Gemini API key from Google AI Studio.
- An input image you have the right to upload and edit.
- The official
google-genaipackage.
This API route is not the same as a free local model. As checked on August 18, 2026, Google's
live pricing page
lists no standard free tier for gemini-3.1-flash-image. Recheck the page before estimating a
production workload.
pip install -U google-genai
Set the key in your shell instead of pasting it into source code:
# PowerShell
$env:GEMINI_API_KEY="your-api-key"
# macOS or Linux
export GEMINI_API_KEY="your-api-key"
Complete Python example
This follows Google's current image-editing pattern: base64-encode the input, call the Interactions API, then decode the returned image. The same maintained example is available in the project repository.
import base64
import mimetypes
import os
from pathlib import Path
from google import genai
def edit_image(input_path, prompt, output_path="output.png"):
api_key = os.getenv("GOOGLE_API_KEY") or os.getenv("GEMINI_API_KEY")
if not api_key:
raise RuntimeError("Set GOOGLE_API_KEY or GEMINI_API_KEY first.")
source = Path(input_path)
if not source.is_file():
raise FileNotFoundError(f"Input image not found: {source}")
image_bytes = source.read_bytes()
mime_type = mimetypes.guess_type(source.name)[0] or "image/png"
if not mime_type.startswith("image/"):
raise ValueError(f"Unsupported input type: {mime_type}")
client = genai.Client(api_key=api_key)
interaction = client.interactions.create(
model="gemini-3.1-flash-image",
input=[
{"type": "text", "text": prompt},
{
"type": "image",
"data": base64.b64encode(image_bytes).decode("utf-8"),
"mime_type": mime_type,
},
],
response_format={"type": "image"},
)
if not interaction.output_image:
raise RuntimeError("The API returned no image.")
Path(output_path).write_bytes(
base64.b64decode(interaction.output_image.data)
)
edit_image(
"reference.jpg",
"Replace the background with a quiet library. Preserve the subject's pose and lighting.",
"edited.png",
)
Run and verify
- Save the script as
nano_api.py. - Place
reference.jpgbeside it. - Run
python nano_api.py. - Open
edited.pngand inspect whether the requested change preserved the intended elements.
Common failures
- Missing key: confirm the environment variable exists in the same terminal session.
- No output image: simplify the request and check the API response, account quota, and safety policy.
- Unsupported input: use a normal JPEG, PNG, or another MIME type supported by the current Gemini documentation.
- Privacy requirement: do not use this cloud route for images that must remain offline. Choose a separate open-weight model from the local-model guide.