Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions skills/nanobanana-skill/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
---
name: nanobanana-skill
description: 'Generate or edit images via Google Gemini (nanobanana). This is the DEFAULT image skill — use whenever the user asks to generate, create, or edit an image and does NOT name another provider. Triggers: "nanobanana", "generate image", "create image", "edit image", "图片生成", "生成图片", "AI绘图", "图片编辑". Do NOT use for diagrams (架构图/流程图/时序图) — draw those with Mermaid or code instead.'
description: 'Generate or edit images via Google Gemini (nanobanana), with optional Atlas Cloud text-to-image generation. This is the DEFAULT image skill — use whenever the user asks to generate, create, or edit an image and does NOT name another provider. Triggers: "nanobanana", "generate image", "create image", "edit image", "图片生成", "生成图片", "AI绘图", "图片编辑". Do NOT use for diagrams (架构图/流程图/时序图) — draw those with Mermaid or code instead.'
allowed-tools: Read, Write, Glob, Grep, Task, Bash(cat:*), Bash(ls:*), Bash(tree:*), Bash(python3:*)
---

# Nanobanana Image Generation Skill

Generate or edit images using Google Gemini API through the nanobanana tool.
Generate or edit images using Google Gemini API through the nanobanana tool. Atlas Cloud is available as an explicit, optional provider for text-to-image generation.

## Requirements

1. **GEMINI_API_KEY**: Must be configured in `~/.nanobanana.env` or `export GEMINI_API_KEY=<your-api-key>`
1. Configure the key for the provider you intend to use:
- **Gemini (default):** `GEMINI_API_KEY` in `~/.nanobanana.env` or the environment
- **Atlas Cloud:** `ATLASCLOUD_API_KEY` in the environment
2. **Python3 with dependent packages installed**: google-genai, Pillow, python-dotenv. They could be installed via `python3 -m pip install -r ${CLAUDE_SKILL_DIR}/requirements.txt` if not installed yet.
3. **Executable**: `${CLAUDE_SKILL_DIR}/nanobanana.py`

Expand All @@ -31,6 +33,15 @@ Generate or edit images using Google Gemini API through the nanobanana tool.
python3 ${CLAUDE_SKILL_DIR}/nanobanana.py --prompt "description of image" --output "filename.png"
```

To use Atlas Cloud instead of the default Gemini provider:

```bash
python3 ${CLAUDE_SKILL_DIR}/nanobanana.py \
--provider atlas \
--prompt "description of image" \
--output "filename.png"
```

3. Show the user the saved image path when complete

### For image editing
Expand All @@ -48,6 +59,15 @@ Generate or edit images using Google Gemini API through the nanobanana tool.

## Available Options

### Providers (--provider)

- `gemini` (default) - Google Gemini generation and editing
- `atlas` - Atlas Cloud asynchronous text-to-image generation

Atlas Cloud uses `google/nano-banana/text-to-image-developer` by default. Override it with `--model` only when the selected Atlas model accepts the same `prompt` and `aspect_ratio` schema. Atlas edit models require public image URLs, so local `--input` editing remains on the Gemini provider. `--resolution`, `--no-search`, and `--no-think` are Gemini-only options.

Atlas submits each generation request once and polls the returned prediction until completion. Use `--poll-interval`, `--poll-timeout`, and `--request-timeout` to tune that bounded polling behavior. Set `ATLASCLOUD_MEDIA_API_BASE` only when a compatible Atlas Cloud media endpoint is required; the default is `https://api.atlascloud.ai/api/v1`. The separate `ATLASCLOUD_API_BASE` variable is commonly used for the OpenAI-compatible LLM endpoint and is intentionally ignored here.

### Aspect Ratios (--size)

- `1024x1024` (1:1) - Square
Expand All @@ -63,10 +83,11 @@ Generate or edit images using Google Gemini API through the nanobanana tool.

### Models (--model)

- `gemini-nano-banana-2.1` (default) - Latest, fast, high quality
- `gemini-nano-banana-2.1` (default for Gemini) - Latest, fast, high quality
- `gemini-3.1-flash-image` - Previous fast model
- `gemini-3-pro-image` - Higher quality for detailed/complex scenes
- `gemini-2.5-flash-image` - Legacy model; no Google Search or thinking (auto-disabled), always outputs 1K regardless of `--resolution`
- `google/nano-banana/text-to-image-developer` (default for Atlas Cloud) - Fast text-to-image generation

### Resolution (--resolution)

Expand Down Expand Up @@ -128,7 +149,7 @@ python3 ${CLAUDE_SKILL_DIR}/nanobanana.py \

If the script fails:

- Check that `GEMINI_API_KEY` is exported or set in ~/.nanobanana.env
- Check that `GEMINI_API_KEY` or `ATLASCLOUD_API_KEY` is set for the selected provider
- Verify input image files exist and are readable
- Ensure the output directory is writable
- If no image is generated, try making the prompt more specific about wanting an image
Expand Down
166 changes: 149 additions & 17 deletions skills/nanobanana-skill/nanobanana.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
#!/usr/bin/env python3
# Generate or edit images using Google Gemini API
import os
# Generate or edit images using Google Gemini or Atlas Cloud
import argparse
import os
import time
import uuid
from io import BytesIO
from urllib.parse import quote

import httpx
from dotenv import load_dotenv
from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO

# Load environment variables
load_dotenv(os.path.expanduser("~") + "/.nanobanana.env")
Expand All @@ -26,11 +30,99 @@
"1536x672": "21:9", # 21:9
}

GEMINI_MODELS = (
"gemini-nano-banana-2.1",
"gemini-3.1-flash-image",
"gemini-3-pro-image",
"gemini-2.5-flash-image",
)
DEFAULT_GEMINI_MODEL = GEMINI_MODELS[0]
DEFAULT_ATLAS_MODEL = "google/nano-banana/text-to-image-developer"
DEFAULT_ATLAS_API_BASE = "https://api.atlascloud.ai/api/v1"
ATLAS_TERMINAL_FAILURES = {"failed", "canceled", "cancelled"}


def atlas_response_data(response):
response.raise_for_status()
body = response.json()
if not isinstance(body, dict):
raise TypeError("Atlas Cloud returned a non-object response.")
code = body.get("code")
if code not in (None, 0, 200):
raise RuntimeError(
body.get("message") or f"Atlas Cloud request failed with code {code}."
)
data = body.get("data", body)
if not isinstance(data, dict):
raise TypeError("Atlas Cloud response does not contain an object payload.")
return data


def generate_with_atlas(args, aspect_ratio, api_key):
api_base = os.getenv("ATLASCLOUD_MEDIA_API_BASE", DEFAULT_ATLAS_API_BASE).rstrip(
"/"
)
model = args.model or DEFAULT_ATLAS_MODEL
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
payload = {"model": model, "prompt": args.prompt, "aspect_ratio": aspect_ratio}

# Intentionally submit exactly once. A failed generation request must be retried by the user.
submitted = atlas_response_data(
httpx.post(
f"{api_base}/model/generateImage",
headers=headers,
json=payload,
timeout=args.request_timeout,
)
)
prediction_id = submitted.get("id")
if not prediction_id:
raise ValueError("Atlas Cloud response does not contain a prediction id.")

deadline = time.monotonic() + args.poll_timeout
result = submitted
while True:
status = str(result.get("status", "")).lower()
if status == "completed":
break
if status in ATLAS_TERMINAL_FAILURES:
raise RuntimeError(
result.get("error") or f"Atlas Cloud generation {status}."
)
if time.monotonic() >= deadline:
raise TimeoutError(
f"Atlas Cloud generation did not complete within {args.poll_timeout} seconds."
)
time.sleep(args.poll_interval)
result = atlas_response_data(
httpx.get(
f"{api_base}/model/prediction/{quote(str(prediction_id), safe='')}",
headers={"Authorization": f"Bearer {api_key}"},
timeout=args.request_timeout,
)
)

outputs = result.get("outputs")
if not isinstance(outputs, list) or not outputs or not isinstance(outputs[0], str):
raise ValueError("Atlas Cloud completed without an image output URL.")
output = httpx.get(outputs[0], timeout=args.request_timeout)
output.raise_for_status()
return output.content


def main():
# Parse command-line arguments
parser = argparse.ArgumentParser(
description="Generate or edit images using Google Gemini API"
description="Generate or edit images using Google Gemini or Atlas Cloud"
)
parser.add_argument(
"--provider",
choices=["gemini", "atlas"],
default="gemini",
help="Image provider to use (default: gemini)",
)
parser.add_argument(
"--prompt",
Expand All @@ -57,14 +149,8 @@ def main():
parser.add_argument(
"--model",
type=str,
default="gemini-nano-banana-2.1",
choices=[
"gemini-nano-banana-2.1",
"gemini-3.1-flash-image",
"gemini-3-pro-image",
"gemini-2.5-flash-image",
],
help="Model to use for image generation (default: gemini-nano-banana-2.1)",
help="Model override (Gemini: one of the listed models, default: %s; Atlas Cloud: any Atlas model ID, default: %s)"
% (DEFAULT_GEMINI_MODEL, DEFAULT_ATLAS_MODEL),
)
parser.add_argument(
"--resolution",
Expand All @@ -85,9 +171,52 @@ def main():
default=False,
help="Disable thinking/reasoning (useful for models that don't support it)",
)
parser.add_argument(
"--poll-interval",
type=float,
default=3.0,
help="Atlas Cloud result polling interval in seconds (default: 3)",
)
parser.add_argument(
"--poll-timeout",
type=float,
default=600.0,
help="Atlas Cloud result polling timeout in seconds (default: 600)",
)
parser.add_argument(
"--request-timeout",
type=float,
default=60.0,
help="Atlas Cloud HTTP request timeout in seconds (default: 60)",
)

args = parser.parse_args()

# Get aspect ratio from size
aspect_ratio = ASPECT_RATIO_MAP.get(args.size, "16:9")

if args.provider == "atlas":
if args.input:
parser.error(
"Atlas Cloud provider currently supports text-to-image generation only."
)
if (
args.poll_interval <= 0
or args.poll_timeout <= 0
or args.request_timeout <= 0
):
parser.error("Atlas Cloud timeout and polling values must be positive.")
api_key = os.getenv("ATLASCLOUD_API_KEY") or ""
if not api_key:
parser.error("Missing ATLASCLOUD_API_KEY environment variable.")
print(
f"Generating image via Atlas Cloud (size: {args.size}) with prompt: {args.prompt}"
)
image = Image.open(BytesIO(generate_with_atlas(args, aspect_ratio, api_key)))
image.save(args.output)
print(f"\n\nImage saved to: {args.output}")
return

# Google API configuration from environment variables
api_key = os.getenv("GEMINI_API_KEY") or ""
if not api_key:
Expand All @@ -96,12 +225,15 @@ def main():
"Set it in ~/.nanobanana.env or export it."
)

model = args.model or DEFAULT_GEMINI_MODEL
if model not in GEMINI_MODELS:
parser.error(
f"Unsupported Gemini model: {model} (choose from {', '.join(GEMINI_MODELS)})"
)

# Initialize Gemini client
client = genai.Client(api_key=api_key)

# Get aspect ratio from size
aspect_ratio = ASPECT_RATIO_MAP.get(args.size, "16:9")

# Build contents list for the API call
contents = []

Expand Down Expand Up @@ -132,15 +264,15 @@ def main():
),
}
# gemini-2.5 image models reject Google Search grounding and thinking
legacy_model = args.model.startswith("gemini-2.5")
legacy_model = model.startswith("gemini-2.5")
if not args.no_search and not legacy_model:
config_kwargs["tools"] = [types.Tool(google_search=types.GoogleSearch())]
if not args.no_think and not legacy_model:
config_kwargs["thinking_config"] = types.ThinkingConfig(include_thoughts=True)

# Generate or edit image
response = client.models.generate_content(
model=args.model,
model=model,
contents=contents,
config=types.GenerateContentConfig(**config_kwargs),
)
Expand Down
Loading