Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update generate-image for the OpenRouter Image API

Timothy Kassis3f530cf49e63
diff --git a/skills/generate-image/SKILL.md b/skills/generate-image/SKILL.md
index 668f2f3f..0f8c3486 100644
--- a/skills/generate-image/SKILL.md
+++ b/skills/generate-image/SKILL.md
@@ -1,184 +1,215 @@
---
name: generate-image
-description: Generate or edit images using AI models (FLUX, Nano Banana 2). Use for general-purpose image generation including photos, illustrations, artwork, visual assets, concept art, and any image that is not a technical diagram or schematic. For flowcharts, circuits, pathways, and technical diagrams, use the scientific-schematics skill instead.
-license: MIT license
-compatibility: Requires an OpenRouter API key
+description: Generate or edit images with AI models through the OpenRouter Image API (Gemini, FLUX, Seedream, Recraft, GPT-Image). Use for photos, illustrations, artwork, concept art, visual assets, logos, and image editing or compositing from reference images. For flowcharts, circuits, pathways, and other technical diagrams, use the scientific-schematics skill instead.
+license: MIT
+compatibility: Requires Python 3.9+ and network access to openrouter.ai. The bundled script uses only the standard library. Image generation requires the OPENROUTER_API_KEY credential and bills per request; listing models does not. Targets the OpenRouter Image API (POST /api/v1/images) as documented on 2026-07-26.
+allowed-tools: Read Write Edit Bash
metadata:
- version: "1.0"
+ version: "2.0"
skill-author: K-Dense Inc.
+ last-reviewed: "2026-07-26"
+ openclaw:
+ primaryEnv: OPENROUTER_API_KEY
+ envVars:
+ - name: OPENROUTER_API_KEY
+ required: true
+ description: OpenRouter API key used for image generation.
---
# Generate Image
-Generate and edit high-quality images using OpenRouter's image generation models including FLUX.2 Pro and Gemini 3.1 Flash Image Preview.
+Generate and edit images through OpenRouter's Image API, which reaches Gemini, FLUX, Seedream,
+Recraft, GPT-Image, and roughly thirty other models behind one request shape.
-## When to Use This Skill
+## When to use
-**Use generate-image for:**
-- Photos and photorealistic images
-- Artistic illustrations and artwork
-- Concept art and visual concepts
-- Visual assets for presentations or documents
-- Image editing and modifications
-- Any general-purpose image generation needs
+**Use this skill for:** photos and photorealistic images, illustrations and artwork, concept art,
+presentation and poster visuals, logos and vector marks, image editing, and compositing from
+reference images.
-**Use scientific-schematics instead for:**
-- Flowcharts and process diagrams
-- Circuit diagrams and electrical schematics
-- Biological pathways and signaling cascades
-- System architecture diagrams
-- CONSORT diagrams and methodology flowcharts
-- Any technical/schematic diagrams
+**Use `scientific-schematics` instead for:** flowcharts, circuit diagrams, biological pathways,
+system architecture diagrams, CONSORT diagrams, and other technical schematics.
-## Quick Start
+## API key
-Use the `scripts/generate_image.py` script to generate or edit images:
+Generation requires an OpenRouter key. The script resolves it in this order:
+
+1. `--api-key`
+2. the `OPENROUTER_API_KEY` environment variable
+3. `OPENROUTER_API_KEY=` in a `.env` file, searching the working directory upward
+
+If none is present the script exits with setup instructions. Keys: https://openrouter.ai/keys
+
+`--list-models` needs no key.
+
+## Quick start
```bash
-# Generate a new image
+# Generate
python scripts/generate_image.py "A beautiful sunset over mountains"
# Edit an existing image
-python scripts/generate_image.py "Make the sky purple" --input photo.jpg
+python scripts/generate_image.py "Make the sky purple" -i photo.jpg -o edited.png
```
-This generates/edits an image and saves it as `generated_image.png` in the current directory.
+Output defaults to `generated_image.<ext>`, where the extension follows the media type the model
+returned. The per-request cost is printed from `usage.cost`.
-## API Key Setup
+## Choosing a model
-**CRITICAL**: The script requires an OpenRouter API key. Before running, check if the user has configured their API key:
+Default: `google/gemini-3.1-flash-image`.
-1. Look for a `.env` file in the project directory or parent directories
-2. Check for `OPENROUTER_API_KEY=<key>` in the `.env` file
-3. If not found, inform the user they need to:
- - Create a `.env` file with `OPENROUTER_API_KEY=your-api-key-here`
- - Or set the environment variable: `export OPENROUTER_API_KEY=your-api-key-here`
- - Get an API key from: https://openrouter.ai/keys
+| Need | Model |
+| --- | --- |
+| General quality, prompt adherence | `google/gemini-3.1-flash-image` |
+| Highest Gemini tier | `google/gemini-3-pro-image` |
+| Photoreal control, reproducible seeds | `black-forest-labs/flux.2-pro` |
+| Cheap iteration | `black-forest-labs/flux.2-klein-4b` |
+| Several images per request | `bytedance-seed/seedream-4.5`, `openai/gpt-image-2` |
+| Vector / SVG output | `recraft/recraft-v4-vector` |
+| Transparent background | `openai/gpt-image-2` with `--background transparent` |
-The script will automatically detect the `.env` file and provide clear error messages if the API key is missing.
+`references/models.md` carries the full catalogue with per-model parameter support. The live
+listing is authoritative:
-## Model Selection
+```bash
+python scripts/generate_image.py --list-models
+```
-**Default model**: `google/gemini-3.1-flash-image-preview` (high quality, recommended)
+## Parameter support varies by model
-**Available models for generation and editing**:
-- `google/gemini-3.1-flash-image-preview` - High quality, supports generation + editing
-- `black-forest-labs/flux.2-pro` - Fast, high quality, supports generation + editing
+This is the main thing to get right. Models advertise different parameter sets, and **sending a
+parameter a model does not support is rejected, not ignored**. The script omits every flag you do
+not pass, so pass only what the target model accepts.
-**Generation only**:
-- `black-forest-labs/flux.2-flex` - Fast and cheap, but not as high quality as pro
+- `--resolution` (`512`, `1K`, `2K`, `4K`) — Gemini, Seedream, Riverflow, Krea, Grok. **Not FLUX.**
+- `--output-format` — FLUX and Riverflow 2.5. **Not Gemini.**
+- `--quality`, `--background`, `--output-compression` — the OpenAI family.
+- `--seed` — FLUX, Seedream, Krea. **Not Gemini, not OpenAI.**
+- `--aspect-ratio` — nearly all models, but the allowed enum differs.
+- `--n` — capped per model: 1 for Gemini and FLUX, 6 for Recraft, 10 for Seedream and OpenAI.
-Select based on:
-- **Quality**: Use gemini-3.1-flash-image-preview or flux.2-pro
-- **Editing**: Use gemini-3.1-flash-image-preview or flux.2-pro (both support image editing)
-- **Cost**: Use flux.2-flex for generation only
+On an HTTP 400 the script prints OpenRouter's message and points at `--list-models`.
-## Common Usage Patterns
+## Editing and reference images
-### Basic generation
-```bash
-python scripts/generate_image.py "Your prompt here"
-```
+`-i/--input` is repeatable and accepts local paths, HTTP(S) URLs, or data URLs. Local files are
+base64-encoded and sent as `input_references`.
-### Specify model
```bash
-python scripts/generate_image.py "A cat in space" --model "black-forest-labs/flux.2-pro"
-```
+# Single-image edit
+python scripts/generate_image.py "Add sunglasses to the person" -i portrait.png
-### Custom output path
-```bash
-python scripts/generate_image.py "Abstract art" --output artwork.png
-```
+# Composite several references
+python scripts/generate_image.py "Blend these two styles" -i style_a.png -i style_b.jpg -o blend.png
-### Edit an existing image
-```bash
-python scripts/generate_image.py "Make the background blue" --input photo.jpg
+# Reference an image already on the web
+python scripts/generate_image.py "Restyle as a watercolor" -i https://example.com/photo.jpg
```
-### Edit with a specific model
-```bash
-python scripts/generate_image.py "Add sunglasses to the person" --input portrait.png --model "black-forest-labs/flux.2-pro"
-```
+Reference limits differ: 16 for OpenAI, 14 for Gemini and Seedream, 8 for FLUX, 1 for Recraft and
+MAI. Accepted local formats: PNG, JPEG, GIF, WebP.
-### Edit with custom output
-```bash
-python scripts/generate_image.py "Remove the text from the image" --input screenshot.png --output cleaned.png
-```
+## Worked examples
-### Multiple images
-Run the script multiple times with different prompts or output paths:
```bash
-python scripts/generate_image.py "Image 1 description" --output image1.png
-python scripts/generate_image.py "Image 2 description" --output image2.png
+# Wide hero image for a poster
+python scripts/generate_image.py \
+ "Laboratory with modern equipment, photorealistic, well-lit" \
+ -m black-forest-labs/flux.2-pro --aspect-ratio 21:9 -o poster/hero.png
+
+# Conceptual figure for a manuscript
+python scripts/generate_image.py \
+ "Microscopic view of cancer cells attacked by immunotherapy agents, scientific illustration" \
+ --resolution 2K -o figures/immunotherapy_concept.png
+
+# Vector logo
+python scripts/generate_image.py \
+ "Minimal geometric fox logo, two colors" \
+ -m recraft/recraft-v4-vector -o assets/logo.svg
+
+# Slide background with a transparent alpha channel
+python scripts/generate_image.py \
+ "Abstract molecular pattern, subtle, blue and white" \
+ -m openai/gpt-image-2 --background transparent -o slides/bg.png
+
+# Four variations in one request
+python scripts/generate_image.py \
+ "Stylized neuron network illustration" \
+ -m bytedance-seed/seedream-4.5 --n 4 -o variations.png
+# -> variations_1.png ... variations_4.png
+
+# Reproducible output
+python scripts/generate_image.py "A cat astronaut" \
+ -m black-forest-labs/flux.2-pro --seed 42
```
-## Script Parameters
-
-- `prompt` (required): Text description of the image to generate, or editing instructions
-- `--input` or `-i`: Input image path for editing (enables edit mode)
-- `--model` or `-m`: OpenRouter model ID (default: google/gemini-3.1-flash-image-preview)
-- `--output` or `-o`: Output file path (default: generated_image.png)
-- `--api-key`: OpenRouter API key (overrides .env file)
-
-## Example Use Cases
+## Script parameters
+
+| Flag | Purpose |
+| --- | --- |
+| `prompt` | Image description, or the edit to apply (required unless `--list-models`) |
+| `-m`, `--model` | Model slug (default `google/gemini-3.1-flash-image`) |
+| `-o`, `--output` | Output path; extension defaults to the returned media type |
+| `-i`, `--input` | Reference image — path, URL, or data URL. Repeatable |
+| `--n` | Images per request, model-capped |
+| `--aspect-ratio` | `1:1`, `16:9`, `9:16`, `4:3`, `3:2`, `21:9`, … |
+| `--resolution` | `512`, `1K`, `2K`, `4K` |
+| `--size` | Explicit pixels, e.g. `2048x2048` |
+| `--quality` | `auto`, `low`, `medium`, `high` |
+| `--output-format` | `png`, `jpeg`, `webp`, `svg` |
+| `--background` | `auto`, `transparent`, `opaque` |
+| `--output-compression` | 0–100, for WebP/JPEG |
+| `--seed` | Deterministic output where supported |
+| `--api-key` | Overrides the environment and `.env` |
+| `--timeout` | Request timeout, seconds (default 300) |
+| `--list-models` | Print the catalogue with parameter support, then exit |
+
+## API shape
+
+For direct requests without the script:
-### For Scientific Documents
```bash
-# Generate a conceptual illustration for a paper
-python scripts/generate_image.py "Microscopic view of cancer cells being attacked by immunotherapy agents, scientific illustration style" --output figures/immunotherapy_concept.png
-
-# Create a visual for a presentation
-python scripts/generate_image.py "DNA double helix structure with highlighted mutation site, modern scientific visualization" --output slides/dna_mutation.png
+curl -s https://openrouter.ai/api/v1/images \
+ -H "Authorization: Bearer $OPENROUTER_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "google/gemini-3.1-flash-image",
+ "prompt": "A red bicycle against a white wall",
+ "aspect_ratio": "16:9"
+ }'
```
-### For Presentations and Posters
-```bash
-# Title slide background
-python scripts/generate_image.py "Abstract blue and white background with subtle molecular patterns, professional presentation style" --output slides/background.png
+Response:
-# Poster hero image
-python scripts/generate_image.py "Laboratory setting with modern equipment, photorealistic, well-lit" --output poster/hero.png
+```json
+{
+ "created": 1748372400,
+ "data": [{ "b64_json": "<base64>", "media_type": "image/png" }],
+ "usage": { "prompt_tokens": 0, "completion_tokens": 4175, "total_tokens": 4175, "cost": 0.04 }
+}
```
-### For General Visual Content
-```bash
-# Website or documentation images
-python scripts/generate_image.py "Professional team collaboration around a digital whiteboard, modern office" --output docs/team_collaboration.png
-
-# Marketing materials
-python scripts/generate_image.py "Futuristic AI brain concept with glowing neural networks" --output marketing/ai_concept.png
-```
-
-## Error Handling
-
-The script provides clear error messages for:
-- Missing API key (with setup instructions)
-- API errors (with status codes)
-- Unexpected response formats
-- Missing dependencies (requests library)
-
-If the script fails, read the error message and address the issue before retrying.
-
-## Notes
+`b64_json` is raw base64, **not** a data URL. `media_type` reflects the real format, so honour it
+when naming files — vector models return `image/svg+xml`.
-- Images are returned as base64-encoded data URLs and automatically saved as PNG files
-- The script supports both `images` and `content` response formats from different OpenRouter models
-- Generation time varies by model (typically 5-30 seconds)
-- For image editing, the input image is encoded as base64 and sent to the model
-- Supported input image formats: PNG, JPEG, GIF, WebP
-- Check OpenRouter pricing for cost information: https://openrouter.ai/models
+Streaming (`"stream": true`) emits `image_generation.partial_image`, `image_generation.completed`,
+and `error` events, terminating with `data: [DONE]`. Only the OpenAI models support it, and the
+bundled script does not use it.
-## Image Editing Tips
+Billing is all-or-nothing: a generation is either completed and billed in full, or it fails and is
+not billed. Streaming preview frames are not charged separately.
-- Be specific about what changes you want (e.g., "change the sky to sunset colors" vs "edit the sky")
-- Reference specific elements in the image when possible
-- For best results, use clear and detailed editing instructions
-- Both Gemini 3.1 Flash Image Preview and FLUX.2 Pro support image editing through OpenRouter
+## Notes and caveats
-## Integration with Other Skills
+- Generation is a paid API call. Prefer a cheap model while iterating on a prompt.
+- Generation takes roughly 5–60 seconds depending on model and resolution.
+- Reference images are uploaded to OpenRouter. Do not send unpublished or sensitive data.
+- Never hardcode the API key. Keep it in the environment or an ignored `.env`.
+- Prompt specifically when editing: "change the sky to sunset colours" beats "edit the sky".
-- **scientific-schematics**: Use for technical diagrams, flowcharts, circuits, pathways
-- **generate-image**: Use for photos, illustrations, artwork, visual concepts
-- **scientific-slides**: Combine with generate-image for visually rich presentations
-- **latex-posters**: Use generate-image for poster visuals and hero images
+## Related skills
+- `scientific-schematics` — technical diagrams, flowcharts, circuits, pathways
+- `scientific-slides` — presentations that embed generated visuals
+- `latex-posters` — posters that embed hero images
diff --git a/skills/generate-image/references/models.md b/skills/generate-image/references/models.md
new file mode 100644
index 00000000..2d9d4ddf
--- /dev/null
+++ b/skills/generate-image/references/models.md
@@ -0,0 +1,100 @@
+# OpenRouter image model reference
+
+Snapshot of `GET https://openrouter.ai/api/v1/images/models`, taken 2026-07-26 (38 models).
+The catalogue moves; re-read it rather than trusting this table:
+
+```bash
+python scripts/generate_image.py --list-models
+```
+
+No API key is needed to list models.
+
+## Capability table
+
+`refs` is the maximum number of `input_references` accepted; `n` is images per request.
+
+| Model | n | refs | stream | Parameters |
+| --- | --- | --- | --- | --- |
+| `google/gemini-3.1-flash-image` | 1 | 14 | no | aspect_ratio, resolution, n, input_references |
+| `google/gemini-3.1-flash-image-preview` | 1 | 14 | no | aspect_ratio, resolution, n, input_references |
+| `google/gemini-3.1-flash-lite-image` | 1 | 14 | no | aspect_ratio, resolution, n, input_references |
+| `google/gemini-3-pro-image` | 1 | 14 | no | aspect_ratio, resolution, n, input_references |
+| `google/gemini-3-pro-image-preview` | 1 | 14 | no | aspect_ratio, resolution, n, input_references |
+| `google/gemini-2.5-flash-image` | 1 | 3 | no | aspect_ratio, n, input_references |
+| `black-forest-labs/flux.2-pro` | 1 | 8 | no | aspect_ratio, output_format, seed, n, input_references |
+| `black-forest-labs/flux.2-max` | 1 | 8 | no | aspect_ratio, output_format, seed, n, input_references |
+| `black-forest-labs/flux.2-flex` | 1 | 8 | no | aspect_ratio, output_format, seed, n, input_references |
+| `black-forest-labs/flux.2-klein-4b` | 1 | 4 | no | aspect_ratio, output_format, seed, n, input_references |
+| `bytedance-seed/seedream-4.5` | 10 | 14 | no | aspect_ratio, resolution, seed, n, input_references |
+| `openai/gpt-image-2` | 10 | 16 | yes | aspect_ratio, background, quality, output_compression, n, input_references |
+| `openai/gpt-image-1` | 10 | 16 | yes | aspect_ratio, background, quality, output_compression, n, input_references |
+| `openai/gpt-image-1-mini` | 10 | 16 | yes | aspect_ratio, background, quality, output_compression, n, input_references |
+| `openai/gpt-5.4-image-2` | 10 | 16 | yes | background, quality, output_compression, n, input_references |
+| `openai/gpt-5-image` | 10 | 16 | yes | background, quality, output_compression, n, input_references |
+| `openai/gpt-5-image-mini` | 10 | 16 | yes | background, quality, output_compression, n, input_references |
+| `recraft/recraft-v4.1-pro` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `recraft/recraft-v4.1` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `recraft/recraft-v4.1-vector` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `recraft/recraft-v4.1-pro-vector` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `recraft/recraft-v4.1-utility` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `recraft/recraft-v4.1-utility-pro` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `recraft/recraft-v4-pro` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `recraft/recraft-v4` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `recraft/recraft-v4-vector` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `recraft/recraft-v4-pro-vector` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `recraft/recraft-v3` | 6 | 1 | no | aspect_ratio, n, input_references |
+| `sourceful/riverflow-v2.5-pro` | 1 | 10 | no | aspect_ratio, background, output_format, resolution, n, input_references |
+| `sourceful/riverflow-v2.5-fast` | 1 | 4 | no | aspect_ratio, background, output_format, resolution, n, input_references |
+| `sourceful/riverflow-v2-pro` | 1 | 10 | no | aspect_ratio, resolution, n, input_references |
+| `sourceful/riverflow-v2-fast` | 1 | 4 | no | aspect_ratio, resolution, n, input_references |
+| `microsoft/mai-image-2.5-pro` | 1 | 1 | no | aspect_ratio, n, input_references |
+| `microsoft/mai-image-2.5` | 1 | 1 | no | aspect_ratio, n, input_references |
+| `krea/krea-2-large` | — | 1 | no | aspect_ratio, resolution, seed, input_references |
+| `krea/krea-2-medium` | — | 1 | no | aspect_ratio, resolution, seed, input_references |
+| `krea/krea-2-medium-turbo` | — | 1 | no | aspect_ratio, resolution, seed, input_references |
+| `x-ai/grok-imagine-image-quality` | 1 | 3 | no | aspect_ratio, resolution, n, input_references |
+
+## Reading the parameter columns
+
+Parameters are not universal, and an unsupported one is **rejected, not ignored**:
+
+- `resolution` (`512`, `1K`, `2K`, `4K`) — Gemini, Seedream, Riverflow, Krea, Grok. Not FLUX.
+- `output_format` — FLUX (`png`, `jpeg`) and Riverflow 2.5. Gemini does not take it.
+- `quality`, `background`, `output_compression` — the OpenAI family (`background` also on Riverflow 2.5).
+- `seed` — FLUX, Seedream, Krea. Not Gemini, not OpenAI.
+- `aspect_ratio` — nearly everything, but the enum differs. FLUX 2 Pro accepts
+ `1:1, 4:3, 3:4, 3:2, 2:3, 16:9, 9:16, 21:9, auto`.
+
+Per-model detail, including provider-specific passthrough parameters and pricing:
+
+```bash
+curl -s https://openrouter.ai/api/v1/images/models/black-forest-labs/flux.2-pro/endpoints
+```
+
+FLUX 2 Pro, for example, allows `steps`, `guidance`, and `safety_tolerance` as passthrough
+parameters and bills $0.03 per output megapixel.
+
+## Choosing a model
+
+- **General quality, prompt adherence** — `google/gemini-3.1-flash-image` (skill default), or
+ `google/gemini-3-pro-image` for the higher tier.
+- **Photoreal and artistic control, seeded reproducibility** — `black-forest-labs/flux.2-pro`.
+- **Cheap iteration** — `black-forest-labs/flux.2-klein-4b`, `google/gemini-3.1-flash-lite-image`.
+- **Batches** — `bytedance-seed/seedream-4.5` or the OpenAI family (up to 10 per request).
+- **True vector output (SVG)** — `recraft/recraft-v4-vector`, `recraft/recraft-v4.1-vector`, and
+ the `-pro-vector` variants. These return `media_type: image/svg+xml`.
+- **Transparent backgrounds** — the OpenAI family via `--background transparent`.
+- **Heavy multi-reference compositing** — OpenAI (16 references), Gemini and Seedream (14).
+
+## Provider routing
+
+The Image API accepts the same `provider` block as chat completions — `provider.only`,
+`provider.order`, `provider.ignore`, `provider.sort` (`price`, `throughput`, `latency`), and
+`provider.allow_fallbacks`. The bundled script does not expose these; send a direct request when
+routing control matters.
+
+## Billing
+
+Image billing is all-or-nothing: a generation either completes and is billed in full, or fails and
+is not billed. Partial preview frames delivered during streaming are not charged separately.
+Per-request cost comes back in `usage.cost`, which the script prints.
diff --git a/skills/generate-image/scripts/generate_image.py b/skills/generate-image/scripts/generate_image.py
index 9c613b89..9477995b 100755
--- a/skills/generate-image/scripts/generate_image.py
+++ b/skills/generate-image/scripts/generate_image.py
@@ -1,281 +1,353 @@
#!/usr/bin/env python3
"""
-Generate and edit images using OpenRouter API with various image generation models.
+Generate and edit images through the OpenRouter Image API (POST /api/v1/images).
-Supports models like:
-- google/gemini-3.1-flash-image-preview (generation and editing)
-- black-forest-labs/flux.2-pro (generation and editing)
-- black-forest-labs/flux.2-flex (generation)
-- And more image generation models available on OpenRouter
+The Image API is model-agnostic: the same request shape reaches Gemini, FLUX,
+Seedream, Recraft, GPT-Image, and the rest of the image catalogue. Responses
+carry base64 payloads in ``data[].b64_json`` alongside the concrete
+``media_type``, so the output extension follows what the model actually
+returned rather than an assumption.
-For image editing, provide an input image along with an editing prompt.
+Reference images (image-to-image and editing) go in ``input_references`` as
+HTTP(S) URLs or base64 data URLs.
+
+Only the standard library is required.
"""
-import sys
-import json
-import base64
+from __future__ import annotations
+
import argparse
+import base64
+import json
+import os
+import sys
+import urllib.error
+import urllib.request
from pathlib import Path
-from typing import Optional
-
-
-def check_env_file() -> Optional[str]:
- """Check if .env file exists and contains OPENROUTER_API_KEY."""
- # Look for .env in current directory and parent directories
- current_dir = Path.cwd()
- for parent in [current_dir] + list(current_dir.parents):
- env_file = parent / ".env"
- if env_file.exists():
- with open(env_file, 'r') as f:
- for line in f:
- if line.startswith('OPENROUTER_API_KEY='):
- api_key = line.split('=', 1)[1].strip().strip('"').strip("'")
- if api_key:
- return api_key
- return None
-
-
-def load_image_as_base64(image_path: str) -> str:
- """Load an image file and return it as a base64 data URL."""
- path = Path(image_path)
- if not path.exists():
- print(f"❌ Error: Image file not found: {image_path}")
- sys.exit(1)
-
- # Determine MIME type from extension
- ext = path.suffix.lower()
- mime_types = {
- '.png': 'image/png',
- '.jpg': 'image/jpeg',
- '.jpeg': 'image/jpeg',
- '.gif': 'image/gif',
- '.webp': 'image/webp',
- }
- mime_type = mime_types.get(ext, 'image/png')
-
- with open(path, 'rb') as f:
- image_data = f.read()
-
- base64_data = base64.b64encode(image_data).decode('utf-8')
- return f"data:{mime_type};base64,{base64_data}"
-
-
-def save_base64_image(base64_data: str, output_path: str) -> None:
- """Save base64 encoded image to file."""
- # Remove data URL prefix if present
- if ',' in base64_data:
- base64_data = base64_data.split(',', 1)[1]
-
- # Decode and save
- image_data = base64.b64decode(base64_data)
- with open(output_path, 'wb') as f:
- f.write(image_data)
-
-
-def generate_image(
- prompt: str,
- model: str = "google/gemini-3.1-flash-image-preview",
- output_path: str = "generated_image.png",
- api_key: Optional[str] = None,
- input_image: Optional[str] = None
-) -> dict:
- """
- Generate or edit an image using OpenRouter API.
+from typing import Any
+
+API_BASE = "https://openrouter.ai/api/v1"
+IMAGES_URL = f"{API_BASE}/images"
+MODELS_URL = f"{API_BASE}/images/models"
+
+DEFAULT_MODEL = "google/gemini-3.1-flash-image"
+
+# media_type -> file extension. Vector-capable models return image/svg+xml.
+EXTENSIONS = {
+ "image/png": ".png",
+ "image/jpeg": ".jpg",
+ "image/jpg": ".jpg",
+ "image/webp": ".webp",
+ "image/gif": ".gif",
+ "image/svg+xml": ".svg",
+}
+
+# Local file extension -> MIME type, for encoding reference images.
+INPUT_MIME = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+}
+
+
+class ApiError(RuntimeError):
+ """An error surfaced by the OpenRouter API or the transport beneath it."""
+
+
+def find_api_key(explicit: str | None = None) -> str:
+ """Resolve the API key from --api-key, the environment, then any .env file."""
+ if explicit:
+ return explicit
+
+ from_env = os.environ.get("OPENROUTER_API_KEY", "").strip()
+ if from_env:
+ return from_env
+
+ cwd = Path.cwd()
+ for directory in [cwd, *cwd.parents]:
+ env_file = directory / ".env"
+ if not env_file.is_file():
+ continue
+ try:
+ content = env_file.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ continue
+ for raw in content.splitlines():
+ line = raw.strip()
+ if line.startswith("#") or "=" not in line:
+ continue
+ name, _, value = line.partition("=")
+ if name.strip() == "OPENROUTER_API_KEY":
+ value = value.strip().strip('"').strip("'")
+ if value:
+ return value
+
+ raise ApiError(
+ "OPENROUTER_API_KEY not found.\n"
+ " export OPENROUTER_API_KEY=your-key\n"
+ " or add OPENROUTER_API_KEY=your-key to a .env file\n"
+ " or pass --api-key\n"
+ "Keys: https://openrouter.ai/keys"
+ )
+
- Args:
- prompt: Text description of the image to generate, or editing instructions
- model: OpenRouter model ID (default: google/gemini-3.1-flash-image-preview)
- output_path: Path to save the generated image
- api_key: OpenRouter API key (will check .env if not provided)
- input_image: Path to an input image for editing (optional)
+def encode_reference(source: str) -> str:
+ """Return an image reference as a URL the API accepts.
- Returns:
- dict: Response from OpenRouter API
+ HTTP(S) URLs and existing data URLs pass through; local paths are read and
+ encoded as base64 data URLs.
"""
+ if source.startswith(("http://", "https://", "data:")):
+ return source
+
+ path = Path(source)
+ if not path.is_file():
+ raise ApiError(f"Reference image not found: {source}")
+
+ mime = INPUT_MIME.get(path.suffix.lower())
+ if mime is None:
+ supported = ", ".join(sorted(INPUT_MIME))
+ raise ApiError(
+ f"Unsupported reference image type '{path.suffix}' ({source}). "
+ f"Supported: {supported}"
+ )
+
+ encoded = base64.b64encode(path.read_bytes()).decode("ascii")
+ return f"data:{mime};base64,{encoded}"
+
+
+def request_json(url: str, api_key: str | None, payload: dict | None, timeout: float) -> Any:
+ """POST (or GET when payload is None) and decode the JSON response."""
+ headers = {"Accept": "application/json"}
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
+
+ data = None
+ if payload is not None:
+ data = json.dumps(payload).encode("utf-8")
+ headers["Content-Type"] = "application/json"
+
+ req = urllib.request.Request(url, data=data, headers=headers)
try:
- import requests
- except ImportError:
- print("Error: 'requests' library not found. Install with: pip install requests")
- sys.exit(1)
-
- # Check for API key
- if not api_key:
- api_key = check_env_file()
-
- if not api_key:
- print("❌ Error: OPENROUTER_API_KEY not found!")
- print("\nPlease create a .env file in your project directory with:")
- print("OPENROUTER_API_KEY=your-api-key-here")
- print("\nOr set the environment variable:")
- print("export OPENROUTER_API_KEY=your-api-key-here")
- print("\nGet your API key from: https://openrouter.ai/keys")
- sys.exit(1)
-
- # Determine if this is generation or editing
- is_editing = input_image is not None
-
- if is_editing:
- print(f"✏️ Editing image with model: {model}")
- print(f"📷 Input image: {input_image}")
- print(f"📝 Edit prompt: {prompt}")
-
- # Load input image as base64
- image_data_url = load_image_as_base64(input_image)
-
- # Build multimodal message content for image editing
- message_content = [
- {
- "type": "text",
- "text": prompt
- },
- {
- "type": "image_url",
- "image_url": {
- "url": image_data_url
- }
- }
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ return json.loads(resp.read().decode("utf-8"))
+ except urllib.error.HTTPError as exc:
+ body = exc.read().decode("utf-8", errors="replace")
+ detail = body
+ try:
+ parsed = json.loads(body)
+ detail = parsed.get("error", {}).get("message") or body
+ except (json.JSONDecodeError, AttributeError):
+ pass
+ hint = ""
+ if exc.code == 400:
+ hint = (
+ "\nParameter support varies by model. Check what this model accepts:\n"
+ " python generate_image.py --list-models"
+ )
+ raise ApiError(f"OpenRouter returned HTTP {exc.code}: {detail}{hint}") from exc
+ except urllib.error.URLError as exc:
+ raise ApiError(f"Could not reach OpenRouter: {exc.reason}") from exc
+ except json.JSONDecodeError as exc:
+ raise ApiError(f"OpenRouter returned a non-JSON response: {exc}") from exc
+
+
+def build_payload(args: argparse.Namespace) -> dict:
+ """Assemble the request body, omitting every parameter the caller left unset.
+
+ Omission matters: models advertise different parameter sets, and sending one
+ a model does not support is rejected rather than ignored.
+ """
+ payload: dict[str, Any] = {"model": args.model, "prompt": args.prompt}
+
+ optional = {
+ "n": args.n,
+ "aspect_ratio": args.aspect_ratio,
+ "resolution": args.resolution,
+ "size": args.size,
+ "quality": args.quality,
+ "output_format": args.output_format,
+ "background": args.background,
+ "output_compression": args.output_compression,
+ "seed": args.seed,
+ }
+ payload.update({key: value for key, value in optional.items() if value is not None})
+
+ if args.input:
+ payload["input_references"] = [
+ {"type": "image_url", "image_url": {"url": encode_reference(src)}}
+ for src in args.input
]
- else:
- print(f"🎨 Generating image with model: {model}")
- print(f"📝 Prompt: {prompt}")
- message_content = prompt
-
- # Make API request
- response = requests.post(
- url="https://openrouter.ai/api/v1/chat/completions",
- headers={
- "Authorization": f"Bearer {api_key}",
- "Content-Type": "application/json",
- },
- json={
- "model": model,
- "messages": [
- {
- "role": "user",
- "content": message_content
- }
- ],
- "modalities": ["image", "text"]
- }
- )
- # Check for errors
- if response.status_code != 200:
- print(f"❌ API Error ({response.status_code}): {response.text}")
- sys.exit(1)
-
- result = response.json()
-
- # Extract and save image
- if result.get("choices"):
- message = result["choices"][0]["message"]
-
- # Handle both 'images' and 'content' response formats
- images = []
-
- if message.get("images"):
- images = message["images"]
- elif message.get("content"):
- # Some models return content as array with image parts
- content = message["content"]
- if isinstance(content, list):
- for part in content:
- if isinstance(part, dict) and part.get("type") == "image":
- images.append(part)
-
- if images:
- # Save the first image
- image = images[0]
- if "image_url" in image:
- image_url = image["image_url"]["url"]
- save_base64_image(image_url, output_path)
- print(f"✅ Image saved to: {output_path}")
- elif "url" in image:
- save_base64_image(image["url"], output_path)
- print(f"✅ Image saved to: {output_path}")
- else:
- print(f"⚠️ Unexpected image format: {image}")
- else:
- print("⚠️ No image found in response")
- if message.get("content"):
- print(f"Response content: {message['content']}")
- else:
- print("❌ No choices in response")
- print(f"Response: {json.dumps(result, indent=2)}")
+ return payload
- return result
+def output_paths(requested: str | None, media_type: str, count: int) -> list[Path]:
+ """Choose filenames for the returned images.
-def main():
+ The extension follows the model's media_type unless the caller named a file
+ explicitly, in which case their choice is kept and a mismatch is reported.
+ """
+ extension = EXTENSIONS.get(media_type, ".png")
+
+ if requested is None:
+ stem, suffix = Path("generated_image"), extension
+ else:
+ given = Path(requested)
+ stem, suffix = given.with_suffix(""), given.suffix or extension
+ if given.suffix and given.suffix.lower() != extension:
+ print(
+ f"Note: model returned {media_type} but --output ends in "
+ f"'{given.suffix}'; writing the returned bytes under that name.",
+ file=sys.stderr,
+ )
+
+ if count == 1:
+ return [stem.with_suffix(suffix)]
+ return [stem.parent / f"{stem.name}_{i + 1}{suffix}" for i in range(count)]
+
+
+def save_images(result: dict, requested_output: str | None) -> list[Path]:
+ """Decode data[].b64_json into files and return the paths written."""
+ items = result.get("data")
+ if not items:
+ raise ApiError(
+ "Response contained no images.\n"
+ f"Raw response: {json.dumps(result, indent=2)[:800]}"
+ )
+
+ first_media = items[0].get("media_type", "image/png")
+ paths = output_paths(requested_output, first_media, len(items))
+ written: list[Path] = []
+
+ for item, path in zip(items, paths):
+ payload = item.get("b64_json")
+ if not payload:
+ print(f"Skipping an entry with no b64_json: {list(item)}", file=sys.stderr)
+ continue
+ if "," in payload and payload.startswith("data:"):
+ payload = payload.split(",", 1)[1]
+ if str(path.parent) not in ("", "."):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(base64.b64decode(payload))
+ written.append(path)
+
+ if not written:
+ raise ApiError("Response carried image entries but none contained data.")
+ return written
+
+
+def list_models(timeout: float) -> int:
+ """Print the image catalogue with each model's supported parameters."""
+ result = request_json(MODELS_URL, None, None, timeout)
+ models = result.get("data", [])
+ if not models:
+ print("No models returned.", file=sys.stderr)
+ return 1
+
+ print(f"{len(models)} image models available\n")
+ for model in sorted(models, key=lambda m: m.get("id", "")):
+ params = model.get("supported_parameters") or {}
+ n_spec = params.get("n") or {}
+ refs = params.get("input_references") or {}
+ print(f"{model.get('id', '?')}")
+ print(
+ f" images/request: up to {n_spec.get('max', 1)}"
+ f" | reference images: up to {refs.get('max', 0)}"
+ f" | streaming: {'yes' if model.get('supports_streaming') else 'no'}"
+ )
+ if params:
+ print(f" parameters: {', '.join(sorted(params))}")
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
- description="Generate or edit images using OpenRouter API",
+ description="Generate or edit images via the OpenRouter Image API.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
- # Generate with default model (Gemini 3.1 Flash Image Preview)
+ # Generate with the default model
python generate_image.py "A beautiful sunset over mountains"
- # Use a specific model
- python generate_image.py "A cat in space" --model "black-forest-labs/flux.2-pro"
-
- # Specify output path
- python generate_image.py "Abstract art" --output my_image.png
+ # Pick a model and shape
+ python generate_image.py "A cat in space" -m black-forest-labs/flux.2-pro --aspect-ratio 16:9
# Edit an existing image
- python generate_image.py "Make the sky purple" --input photo.jpg --output edited.png
+ python generate_image.py "Make the sky purple" -i photo.jpg -o edited.png
- # Edit with a specific model
- python generate_image.py "Add a hat to the person" --input portrait.png -m "black-forest-labs/flux.2-pro"
+ # Composite from several references (model-dependent limit)
+ python generate_image.py "Blend these styles" -i a.png -i b.png -o blended.png
-Popular image models:
- - google/gemini-3.1-flash-image-preview (default, high quality, generation + editing)
- - black-forest-labs/flux.2-pro (fast, high quality, generation + editing)
- - black-forest-labs/flux.2-flex (development version)
- """
- )
+ # Vector output
+ python generate_image.py "Minimal fox logo" -m recraft/recraft-v4-vector -o logo.svg
- parser.add_argument(
- "prompt",
- type=str,
- help="Text description of the image to generate, or editing instructions"
+ # Inspect the catalogue and per-model parameter support
+ python generate_image.py --list-models
+""",
)
- parser.add_argument(
- "--model", "-m",
- type=str,
- default="google/gemini-3.1-flash-image-preview",
- help="OpenRouter model ID (default: google/gemini-3.1-flash-image-preview)"
- )
+ parser.add_argument("prompt", nargs="?", help="Description of the image, or the edit to apply")
+ parser.add_argument("--model", "-m", default=DEFAULT_MODEL,
+ help=f"Model slug (default: {DEFAULT_MODEL})")
+ parser.add_argument("--output", "-o",
+ help="Output path; extension defaults to the returned media type")
+ parser.add_argument("--input", "-i", action="append", metavar="IMAGE",
+ help="Reference image: local path, HTTP(S) URL, or data URL. Repeatable.")
+ parser.add_argument("--n", type=int, help="Number of images (model-dependent maximum)")
+ parser.add_argument("--aspect-ratio", help="e.g. 1:1, 16:9, 9:16, 4:3, 3:2, 21:9")
+ parser.add_argument("--resolution", help="Tier: 512, 1K, 2K, 4K")
+ parser.add_argument("--size", help='Explicit pixels, e.g. "2048x2048"')
+ parser.add_argument("--quality", choices=["auto", "low", "medium", "high"])
+ parser.add_argument("--output-format", choices=["png", "jpeg", "webp", "svg"])
+ parser.add_argument("--background", choices=["auto", "transparent", "opaque"])
+ parser.add_argument("--output-compression", type=int, metavar="0-100",
+ help="Compression for webp/jpeg output")
+ parser.add_argument("--seed", type=int, help="Seed for deterministic output, where supported")
+ parser.add_argument("--api-key", help="Overrides OPENROUTER_API_KEY and any .env file")
+ parser.add_argument("--timeout", type=float, default=300.0,
+ help="Request timeout in seconds (default: 300)")
+ parser.add_argument("--list-models", action="store_true",
+ help="List image models and their supported parameters, then exit")
+
+ args = parser.parse_args(argv)
- parser.add_argument(
- "--output", "-o",
- type=str,
- default="generated_image.png",
- help="Output file path (default: generated_image.png)"
- )
+ try:
+ if args.list_models:
+ return list_models(args.timeout)
- parser.add_argument(
- "--input", "-i",
- type=str,
- help="Input image path for editing (enables edit mode)"
- )
+ if not args.prompt:
+ parser.error("a prompt is required unless --list-models is given")
- parser.add_argument(
- "--api-key",
- type=str,
- help="OpenRouter API key (will check .env if not provided)"
- )
+ api_key = find_api_key(args.api_key)
+ payload = build_payload(args)
- args = parser.parse_args()
+ action = "Editing" if args.input else "Generating"
+ print(f"{action} with {args.model}")
+ print(f"Prompt: {args.prompt}")
+ if args.input:
+ print(f"References: {', '.join(args.input)}")
- generate_image(
- prompt=args.prompt,
- model=args.model,
- output_path=args.output,
- api_key=args.api_key,
- input_image=args.input
- )
+ result = request_json(IMAGES_URL, api_key, payload, args.timeout)
+ written = save_images(result, args.output)
+
+ for path in written:
+ print(f"Saved {path}")
+
+ cost = (result.get("usage") or {}).get("cost")
+ if cost is not None:
+ print(f"Cost: ${cost}")
+ return 0
+
+ except ApiError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+ except KeyboardInterrupt:
+ print("Interrupted.", file=sys.stderr)
+ return 130
if __name__ == "__main__":
- main()
+ sys.exit(main())
diff --git a/tests/generate-image/test_scripts.py b/tests/generate-image/test_scripts.py
new file mode 100644
index 00000000..ccf361b6
--- /dev/null
+++ b/tests/generate-image/test_scripts.py
@@ -0,0 +1,243 @@
+"""Dependency-free, network-free tests for the generate-image helper CLI."""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import importlib.util
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "generate-image"
+SCRIPT = SKILL_ROOT / "scripts" / "generate_image.py"
+
+
+def load_module():
+ """Import the CLI under a unique name so it cannot collide with other skills.
+
+ Bytecode writing is suppressed: a __pycache__ left inside the skill directory
+ would ship as an artifact the agent never loads.
+ """
+ spec = importlib.util.spec_from_file_location("generate_image_skill_cli", SCRIPT)
+ module = importlib.util.module_from_spec(spec)
+ previous = sys.dont_write_bytecode
+ sys.dont_write_bytecode = True
+ try:
+ spec.loader.exec_module(module)
+ finally:
+ sys.dont_write_bytecode = previous
+ return module
+
+
+gi = load_module()
+
+
+def make_args(**overrides) -> argparse.Namespace:
+ defaults = dict(
+ prompt="a prompt",
+ model=gi.DEFAULT_MODEL,
+ output=None,
+ input=None,
+ n=None,
+ aspect_ratio=None,
+ resolution=None,
+ size=None,
+ quality=None,
+ output_format=None,
+ background=None,
+ output_compression=None,
+ seed=None,
+ )
+ defaults.update(overrides)
+ return argparse.Namespace(**defaults)
+
+
+class CliSurfaceTests(unittest.TestCase):
+ def test_help_exits_zero(self):
+ completed = subprocess.run(
+ [sys.executable, "-B", str(SCRIPT), "--help"],
+ text=True, capture_output=True, timeout=20, check=False,
+ )
+ self.assertEqual(completed.returncode, 0, completed.stderr)
+ self.assertIn("usage:", completed.stdout.lower())
+
+ def test_missing_prompt_is_an_error(self):
+ completed = subprocess.run(
+ [sys.executable, "-B", str(SCRIPT)],
+ text=True, capture_output=True, timeout=20, check=False,
+ )
+ self.assertNotEqual(completed.returncode, 0)
+ self.assertIn("prompt is required", completed.stderr)
+
+ def test_targets_the_images_endpoint_not_chat_completions(self):
+ self.assertEqual(gi.IMAGES_URL, "https://openrouter.ai/api/v1/images")
+ self.assertEqual(gi.MODELS_URL, "https://openrouter.ai/api/v1/images/models")
+ source = SCRIPT.read_text(encoding="utf-8")
+ self.assertNotIn("chat/completions", source)
+ self.assertNotIn("modalities", source)
+
+ def test_uses_only_the_standard_library(self):
+ source = SCRIPT.read_text(encoding="utf-8")
+ for third_party in ("import requests", "import httpx", "from requests"):
+ self.assertNotIn(third_party, source)
+
+
+class ApiKeyResolutionTests(unittest.TestCase):
+ def test_explicit_key_wins(self):
+ self.assertEqual(gi.find_api_key("explicit-key"), "explicit-key")
+
+ def test_environment_variable_is_read(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ previous = os.getcwd()
+ os.chdir(tmp)
+ try:
+ os.environ["OPENROUTER_API_KEY"] = "env-key"
+ self.assertEqual(gi.find_api_key(None), "env-key")
+ finally:
+ os.environ.pop("OPENROUTER_API_KEY", None)
+ os.chdir(previous)
+
+ def test_dotenv_is_read_when_environment_is_empty(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ (Path(tmp) / ".env").write_text(
+ "# comment\nOTHER=1\nOPENROUTER_API_KEY=\"dotenv-key\"\n", encoding="utf-8"
+ )
+ previous = os.getcwd()
+ os.chdir(tmp)
+ try:
+ os.environ.pop("OPENROUTER_API_KEY", None)
+ self.assertEqual(gi.find_api_key(None), "dotenv-key")
+ finally:
+ os.chdir(previous)
+
+ def test_absent_key_raises_with_guidance(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ previous = os.getcwd()
+ os.chdir(tmp)
+ try:
+ os.environ.pop("OPENROUTER_API_KEY", None)
+ with self.assertRaises(gi.ApiError) as caught:
+ gi.find_api_key(None)
+ self.assertIn("OPENROUTER_API_KEY", str(caught.exception))
+ finally:
+ os.chdir(previous)
+
+
+class PayloadTests(unittest.TestCase):
+ def test_unset_parameters_are_omitted(self):
+ payload = gi.build_payload(make_args())
+ self.assertEqual(set(payload), {"model", "prompt"})
+
+ def test_set_parameters_are_included(self):
+ payload = gi.build_payload(make_args(aspect_ratio="16:9", seed=42, n=3))
+ self.assertEqual(payload["aspect_ratio"], "16:9")
+ self.assertEqual(payload["seed"], 42)
+ self.assertEqual(payload["n"], 3)
+ self.assertNotIn("quality", payload)
+
+ def test_zero_seed_survives_omission_filtering(self):
+ payload = gi.build_payload(make_args(seed=0))
+ self.assertEqual(payload["seed"], 0)
+
+ def test_references_use_the_input_references_shape(self):
+ payload = gi.build_payload(make_args(input=["https://example.com/a.png"]))
+ self.assertEqual(
+ payload["input_references"],
+ [{"type": "image_url", "image_url": {"url": "https://example.com/a.png"}}],
+ )
+
+
+class ReferenceEncodingTests(unittest.TestCase):
+ def test_urls_and_data_urls_pass_through(self):
+ for value in ("https://e.com/a.png", "http://e.com/a.png", "data:image/png;base64,AAA"):
+ self.assertEqual(gi.encode_reference(value), value)
+
+ def test_local_file_becomes_a_data_url(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "pic.png"
+ path.write_bytes(b"\x89PNG\r\n\x1a\nfake")
+ encoded = gi.encode_reference(str(path))
+ self.assertTrue(encoded.startswith("data:image/png;base64,"))
+ self.assertEqual(
+ base64.b64decode(encoded.split(",", 1)[1]), b"\x89PNG\r\n\x1a\nfake"
+ )
+
+ def test_jpeg_extension_maps_to_jpeg_mime(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "pic.jpg"
+ path.write_bytes(b"jpegbytes")
+ self.assertTrue(gi.encode_reference(str(path)).startswith("data:image/jpeg;base64,"))
+
+ def test_missing_file_raises(self):
+ with self.assertRaises(gi.ApiError):
+ gi.encode_reference("/nonexistent/nope.png")
+
+ def test_unsupported_extension_raises(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "pic.tiff"
+ path.write_bytes(b"x")
+ with self.assertRaises(gi.ApiError):
+ gi.encode_reference(str(path))
+
+
+class OutputPathTests(unittest.TestCase):
+ def test_default_name_follows_media_type(self):
+ self.assertEqual(gi.output_paths(None, "image/png", 1), [Path("generated_image.png")])
+ self.assertEqual(gi.output_paths(None, "image/svg+xml", 1), [Path("generated_image.svg")])
+ self.assertEqual(gi.output_paths(None, "image/jpeg", 1), [Path("generated_image.jpg")])
+
+ def test_unknown_media_type_falls_back_to_png(self):
+ self.assertEqual(gi.output_paths(None, "image/unheard-of", 1), [Path("generated_image.png")])
+
+ def test_explicit_output_is_respected(self):
+ self.assertEqual(gi.output_paths("art.png", "image/png", 1), [Path("art.png")])
+
+ def test_multiple_images_are_numbered(self):
+ self.assertEqual(
+ gi.output_paths("out.png", "image/png", 3),
+ [Path("out_1.png"), Path("out_2.png"), Path("out_3.png")],
+ )
+
+
+class SaveImageTests(unittest.TestCase):
+ def test_saves_base64_payload(self):
+ payload = base64.b64encode(b"imagebytes").decode("ascii")
+ response = {"data": [{"b64_json": payload, "media_type": "image/png"}]}
+ with tempfile.TemporaryDirectory() as tmp:
+ target = Path(tmp) / "out.png"
+ written = gi.save_images(response, str(target))
+ self.assertEqual(written, [target])
+ self.assertEqual(target.read_bytes(), b"imagebytes")
+
+ def test_creates_missing_parent_directories(self):
+ payload = base64.b64encode(b"x").decode("ascii")
+ response = {"data": [{"b64_json": payload, "media_type": "image/png"}]}
+ with tempfile.TemporaryDirectory() as tmp:
+ target = Path(tmp) / "nested" / "dir" / "out.png"
+ gi.save_images(response, str(target))
+ self.assertTrue(target.is_file())
+
+ def test_empty_data_raises(self):
+ with self.assertRaises(gi.ApiError):
+ gi.save_images({"data": []}, None)
+
+
+class SkillDocumentTests(unittest.TestCase):
+ def test_frontmatter_version_matches_expected(self):
+ text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")
+ self.assertIn('version: "2.0"', text)
+
+ def test_documented_default_model_matches_the_script(self):
+ text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")
+ self.assertIn(gi.DEFAULT_MODEL, text)
+
+ def test_reference_file_is_present(self):
+ self.assertTrue((SKILL_ROOT / "references" / "models.md").is_file())
+
+
+if __name__ == "__main__":
+ unittest.main()