Skill: skydream9527-ctrl/minimax-image-gyh (version 1.0.0)

--- name: minimax-image-gyh description: MiniMax 图像生成模型（image-01），根据文本描述生成高质量图片。使用 MINIMAX_API_KEY 环境变量。 metadata: {"openclaw":{"emoji":"🖼️","requires":{"bins":["python3"]}}} --- # MiniMax 图像生成 使用 MiniMax image-01 模型根据文本描述生成图片。 ## 支持的模型 | 模型 | 说明 | |------|------| | `image-01` | 最新图像生成模型，支持文生图 | | `image-01-live` | 实时图像生成 | ## 前置要求 - Python 3 - `pip3 install requests` - 设置环境变量 `MINIMAX_API_KEY` ## 使用方法 ```bash # 文生图 python3 {baseDir}/scripts/image_gen.py \ --prompt "一个穿古装的东方美女，银杏树下，月光皎洁" \ --output girl.png # 指定尺寸 python3 {baseDir}/scripts/image_gen.py \ --prompt "未来城市夜景，霓虹灯光，科幻风格" \ --size 1024x1024 \ --output city.png ``` ## 参数说明 | 参数 | 说明 | 默认值 | |------|------|--------| | `--prompt` | 图片描述文本（建议中英混杂效果更好） | - | | `--model` | 模型名称 | `image-01` | | `--size` | 图片尺寸 | `1024x1024` | | `--output` | 输出文件路径 | `output.png` |

path: _meta.json
content: ownerId: gyh
slug: minimax-image-gyh
version: 1.0.0
publishedAt: 1744394400000
name: minimax-image
description: MiniMax 图像生成技能（image-01），支持文生图。

path: examples.md
content: # MiniMax Image Skill - Usage Examples

## Frontend Development Scenarios

### Hero Image for Landing Page
```
User: "I need a hero image for my fintech startup landing page"

Claude will run:
python scripts/generate_image.py "Modern fintech hero image with abstract flowing gradients in blue and purple, suggesting financial growth and technology, clean minimalist style" "./src/assets/hero.png"
```

### App Icons
```
User: "Generate an app icon for my weather app"

Claude will run:
python scripts/generate_image.py --size 1K --aspect 1:1 "Minimalist weather app icon, stylized sun partially behind a cloud, warm orange and blue gradient, rounded square suitable for iOS/Android" "./assets/icons/weather-icon.png"
```

### Placeholder Images
```
User: "I need placeholder images for my e-commerce product grid"

Claude will run:
python scripts/generate_image.py "E-commerce product placeholder image, neutral gray background, subtle product box outline, professional and clean" "./public/images/placeholder-product.png"
```

### Background Patterns
```
User: "Create a subtle background pattern for my website"

Claude will run:
python scripts/generate_image.py --size 2K --aspect 4:3 "Seamless tileable subtle geometric pattern, very light gray on white, minimalist, suitable for website background" "./assets/bg-pattern.png"
```

## Documentation & Diagrams

### Architecture Diagram
```
User: "Visualize our microservices architecture"

Claude will run:
python scripts/generate_image.py "Clean technical diagram showing microservices architecture, boxes connected by arrows, services labeled API Gateway, Auth Service, User Service, Order Service, white background, professional style" "./docs/images/architecture.png"
```

### Process Flowchart
```
User: "Create a flowchart for user onboarding"

Claude will run:
python scripts/generate_image.py "Flowchart diagram showing user onboarding process, start with signup, branches for email verification, profile setup, tutorial completion, clean business style with blue accents" "./docs/onboarding-flow.png"
```

## Marketing & Creative

### Social Media Graphics
```
User: "I need a banner for our product launch on Twitter"

Claude will run:
python scripts/generate_image.py --size 2K --aspect 16:9 "Modern product launch banner 1200x675, bold typography space for text overlay, dynamic abstract tech background, vibrant gradients purple to blue" "./marketing/twitter-banner.png"
```

### Blog Post Headers
```
User: "Generate a header image for my blog post about AI"

Claude will run:
python scripts/generate_image.py --size 2K --aspect 16:9 "Blog header image about artificial intelligence, abstract neural network visualization, glowing nodes and connections, dark background with blue accent lights, futuristic and professional" "./blog/images/ai-header.png"
```

## Command Line Usage

```bash
# Generate with default settings
python scripts/generate_image.py "A peaceful zen garden"

# Specify output location
python scripts/generate_image.py "Mountain landscape" "./wallpapers/mountains.png"

# High resolution output
python scripts/generate_image.py --size 2K "Detailed cityscape" "./high-res/city.png"

# Wide aspect ratio
python scripts/generate_image.py --aspect 16:9 "Cinematic landscape" "./cinematic.png"

# Portrait aspect ratio
python scripts/generate_image.py --aspect 9:16 "Mobile wallpaper" "./phone-wallpaper.png"
```

### Windows PowerShell

```powershell
# Generate with default settings
python scripts/generate_image.py "A peaceful zen garden"

# With environment variable for size
$env:IMAGE_SIZE = "2K"
python scripts/generate_image.py "Detailed cityscape" "./high-res/city.png"
```

### Batch Generation (via shell)

**macOS/Linux:**
```bash
# Generate multiple variations
for i in 1 2 3; do
    python scripts/generate_image.py "Abstract art variation $i" "./art/abstract-$i.png"
done
```

**Windows PowerShell:**
```powershell
# Generate multiple variations
1..3 | ForEach-Object {
    python scripts/generate_image.py "Abstract art variation $_" "./art/abstract-$_.png"
}
```

## Integration with Frontend Workflow

### React Project
```
User: "Add a loading spinner image to my React components"

Claude will:
1. Generate the image: python scripts/generate_image.py "Minimal loading spinner, circular design, gradient from light to dark blue, clean vector style" "./src/assets/spinner.png"
2. Update component to use the new image
```

### Vue Project
```
User: "Need an empty state illustration for when there's no data"

Claude will:
1. Generate: python scripts/generate_image.py "Friendly empty state illustration, person looking at empty box, soft pastel colors, friendly and approachable, modern SaaS style" "./src/assets/empty-state.png"
2. Add to the component template
```

### Flutter Project
```
User: "Generate an onboarding illustration"

Claude will:
1. Generate: python scripts/generate_image.py --size 2K "Mobile app onboarding illustration, person using smartphone, abstract flowing shapes in background, modern gradient style" "./assets/images/onboarding.png"
2. Add to pubspec.yaml assets
3. Use in the onboarding widget
```

## Tips for Better Results

### Basic Tips
1. **Be Descriptive**: The more detail, the better the output
2. **Mention Style**: "flat design", "3D render", "watercolor", "minimalist"
3. **Specify Colors**: "blue and orange gradient", "monochrome", "pastel colors"
4. **Include Context**: "suitable for dark mode", "web-safe", "mobile app"
5. **Define Purpose**: "for hero section", "app icon", "documentation"

### Advanced Tips
6. **Specify Lighting**: "golden hour lighting", "soft diffused light", "dramatic shadows"
7. **Define Composition**: "close-up", "wide angle", "from above", "centered"
8. **Include Texture**: "natural skin texture", "fabric weave visible", "metal sheen"
9. **Add Depth**: "shallow depth of field", "soft bokeh", "sharp focus throughout"

### Example Prompts by Use Case

**UI/Frontend:**
- "A modern dashboard UI mockup with dark theme, showing analytics charts"
- "Clean minimalist app icon for a task management app, rounded square shape"
- "Hero image for a SaaS landing page, abstract gradient with geometric shapes"

**Documentation:**
- "Simple architecture diagram showing microservices connected by arrows"
- "Flowchart illustrating user authentication process"

**Placeholders:**
- "Professional headshot placeholder, silhouette style, neutral gray background"
- "Product image placeholder, simple box shape with 'Image Coming Soon' text"

**Marketing/Creative:**
- "Isometric illustration of a modern office workspace"
- "Gradient abstract background suitable for presentation slides"


path: minimax-image/examples.md
content: # MiniMax Image Skill - Usage Examples

## Frontend Development Scenarios

### Hero Image for Landing Page
```
User: "I need a hero image for my fintech startup landing page"

Claude will run:
python scripts/generate_image.py "Modern fintech hero image with abstract flowing gradients in blue and purple, suggesting financial growth and technology, clean minimalist style" "./src/assets/hero.png"
```

### App Icons
```
User: "Generate an app icon for my weather app"

Claude will run:
python scripts/generate_image.py --size 1K --aspect 1:1 "Minimalist weather app icon, stylized sun partially behind a cloud, warm orange and blue gradient, rounded square suitable for iOS/Android" "./assets/icons/weather-icon.png"
```

### Placeholder Images
```
User: "I need placeholder images for my e-commerce product grid"

Claude will run:
python scripts/generate_image.py "E-commerce product placeholder image, neutral gray background, subtle product box outline, professional and clean" "./public/images/placeholder-product.png"
```

### Background Patterns
```
User: "Create a subtle background pattern for my website"

Claude will run:
python scripts/generate_image.py --size 2K --aspect 4:3 "Seamless tileable subtle geometric pattern, very light gray on white, minimalist, suitable for website background" "./assets/bg-pattern.png"
```

## Documentation & Diagrams

### Architecture Diagram
```
User: "Visualize our microservices architecture"

Claude will run:
python scripts/generate_image.py "Clean technical diagram showing microservices architecture, boxes connected by arrows, services labeled API Gateway, Auth Service, User Service, Order Service, white background, professional style" "./docs/images/architecture.png"
```

### Process Flowchart
```
User: "Create a flowchart for user onboarding"

Claude will run:
python scripts/generate_image.py "Flowchart diagram showing user onboarding process, start with signup, branches for email verification, profile setup, tutorial completion, clean business style with blue accents" "./docs/onboarding-flow.png"
```

## Marketing & Creative

### Social Media Graphics
```
User: "I need a banner for our product launch on Twitter"

Claude will run:
python scripts/generate_image.py --size 2K --aspect 16:9 "Modern product launch banner 1200x675, bold typography space for text overlay, dynamic abstract tech background, vibrant gradients purple to blue" "./marketing/twitter-banner.png"
```

### Blog Post Headers
```
User: "Generate a header image for my blog post about AI"

Claude will run:
python scripts/generate_image.py --size 2K --aspect 16:9 "Blog header image about artificial intelligence, abstract neural network visualization, glowing nodes and connections, dark background with blue accent lights, futuristic and professional" "./blog/images/ai-header.png"
```

## Command Line Usage

```bash
# Generate with default settings
python scripts/generate_image.py "A peaceful zen garden"

# Specify output location
python scripts/generate_image.py "Mountain landscape" "./wallpapers/mountains.png"

# High resolution output
python scripts/generate_image.py --size 2K "Detailed cityscape" "./high-res/city.png"

# Wide aspect ratio
python scripts/generate_image.py --aspect 16:9 "Cinematic landscape" "./cinematic.png"

# Portrait aspect ratio
python scripts/generate_image.py --aspect 9:16 "Mobile wallpaper" "./phone-wallpaper.png"
```

### Windows PowerShell

```powershell
# Generate with default settings
python scripts/generate_image.py "A peaceful zen garden"

# With environment variable for size
$env:IMAGE_SIZE = "2K"
python scripts/generate_image.py "Detailed cityscape" "./high-res/city.png"
```

### Batch Generation (via shell)

**macOS/Linux:**
```bash
# Generate multiple variations
for i in 1 2 3; do
    python scripts/generate_image.py "Abstract art variation $i" "./art/abstract-$i.png"
done
```

**Windows PowerShell:**
```powershell
# Generate multiple variations
1..3 | ForEach-Object {
    python scripts/generate_image.py "Abstract art variation $_" "./art/abstract-$_.png"
}
```

## Integration with Frontend Workflow

### React Project
```
User: "Add a loading spinner image to my React components"

Claude will:
1. Generate the image: python scripts/generate_image.py "Minimal loading spinner, circular design, gradient from light to dark blue, clean vector style" "./src/assets/spinner.png"
2. Update component to use the new image
```

### Vue Project
```
User: "Need an empty state illustration for when there's no data"

Claude will:
1. Generate: python scripts/generate_image.py "Friendly empty state illustration, person looking at empty box, soft pastel colors, friendly and approachable, modern SaaS style" "./src/assets/empty-state.png"
2. Add to the component template
```

### Flutter Project
```
User: "Generate an onboarding illustration"

Claude will:
1. Generate: python scripts/generate_image.py --size 2K "Mobile app onboarding illustration, person using smartphone, abstract flowing shapes in background, modern gradient style" "./assets/images/onboarding.png"
2. Add to pubspec.yaml assets
3. Use in the onboarding widget
```

## Tips for Better Results

### Basic Tips
1. **Be Descriptive**: The more detail, the better the output
2. **Mention Style**: "flat design", "3D render", "watercolor", "minimalist"
3. **Specify Colors**: "blue and orange gradient", "monochrome", "pastel colors"
4. **Include Context**: "suitable for dark mode", "web-safe", "mobile app"
5. **Define Purpose**: "for hero section", "app icon", "documentation"

### Advanced Tips
6. **Specify Lighting**: "golden hour lighting", "soft diffused light", "dramatic shadows"
7. **Define Composition**: "close-up", "wide angle", "from above", "centered"
8. **Include Texture**: "natural skin texture", "fabric weave visible", "metal sheen"
9. **Add Depth**: "shallow depth of field", "soft bokeh", "sharp focus throughout"

### Example Prompts by Use Case

**UI/Frontend:**
- "A modern dashboard UI mockup with dark theme, showing analytics charts"
- "Clean minimalist app icon for a task management app, rounded square shape"
- "Hero image for a SaaS landing page, abstract gradient with geometric shapes"

**Documentation:**
- "Simple architecture diagram showing microservices connected by arrows"
- "Flowchart illustrating user authentication process"

**Placeholders:**
- "Professional headshot placeholder, silhouette style, neutral gray background"
- "Product image placeholder, simple box shape with 'Image Coming Soon' text"

**Marketing/Creative:**
- "Isometric illustration of a modern office workspace"
- "Gradient abstract background suitable for presentation slides"


path: minimax-image/reference.md
content: # MiniMax Image Skill Reference

## Setup

### 1. Get a MiniMax API Key

1. Go to MiniMax Dashboard or your Coding Plan settings
2. Find your API key for image generation
3. Copy the API key

### 2. Set Environment Variable

**Windows (PowerShell):**
```powershell
$env:MINIMAX_API_KEY = "your-api-key-here"

# To persist across sessions, add to your PowerShell profile:
Add-Content $PROFILE "`n`$env:MINIMAX_API_KEY = 'your-api-key-here'"
```

**Windows (CMD):**
```cmd
set MINIMAX_API_KEY=your-api-key-here

# To persist, use System Properties > Environment Variables
```

**macOS/Linux:**
```bash
export MINIMAX_API_KEY="your-api-key-here"

# Add to ~/.zshrc or ~/.bashrc to persist
echo 'export MINIMAX_API_KEY="your-api-key-here"' >> ~/.zshrc
```

## API Reference

### Model

- **Model ID**: `image-01` (MiniMax's image generation model)
- **Endpoint**: `https://api.minimaxi.com/v1/image_generation`

### Image Sizes

| Size | Description |
|------|-------------|
| `1K` | 1024x1024 pixels - Default, balanced quality/speed |
| `2K` | 2048x2048 pixels - High resolution |
| `4K` | 4096x4096 pixels - Ultra high resolution |

### Aspect Ratios

| Ratio | Description |
|-------|-------------|
| `1:1` | Square - Default |
| `16:9` | Wide - Suitable for banners, hero images |
| `9:16` | Portrait - Suitable for mobile content |
| `3:4` | Portrait - Standard photo ratio |
| `4:3` | Landscape - Classic photo ratio |

## Script Parameters

### Python Script (Cross-Platform)

```bash
python scripts/generate_image.py <prompt> [output_path] [--size SIZE] [--aspect RATIO]
```

| Parameter | Required | Default | Description |
|-----------|----------|---------|-------------|
| `prompt` | Yes | - | Text description of desired image |
| `output_path` | No | `./generated-image.png` | Where to save the image |
| `--size` | No | `1K` | Image size (1K, 2K, or 4K) |
| `--aspect` | No | `1:1` | Aspect ratio (1:1, 16:9, 9:16, 3:4, 4:3) |

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `MINIMAX_API_KEY` | Yes | - | Your MiniMax API key |
| `IMAGE_SIZE` | No | `1K` | Image size (1K, 2K, or 4K) |
| `IMAGEAspectRatio` | No | `1:1` | Aspect ratio (1:1, 16:9, 9:16, 3:4, 4:3) |

## Usage Examples

### Basic Generation

```bash
python scripts/generate_image.py "A serene mountain landscape at dawn"
```

### Custom Output Path

```bash
python scripts/generate_image.py "Minimalist logo design" "./assets/logo.png"
```

### High Resolution

```bash
python scripts/generate_image.py --size 2K "Detailed portrait" "./high-res.png"
```

### Wide Banner

```bash
python scripts/generate_image.py --size 2K --aspect 16:9 "Product banner" "./banner.png"
```

### Mobile Wallpaper

```bash
python scripts/generate_image.py --size 2K --aspect 9:16 "Mobile wallpaper" "./phone-bg.png"
```

## Prompt Tips

### For Best Results

1. **Be specific**: "A red sports car" vs "A cherry red 1967 Mustang convertible"
2. **Include style**: "in watercolor style", "photorealistic", "minimalist flat design"
3. **Mention lighting**: "golden hour lighting", "soft diffused light", "dramatic shadows"
4. **Specify composition**: "close-up", "wide angle", "from above", "centered"

### Advanced Prompting Techniques

These techniques produce significantly better results:

#### Lighting & Atmosphere
- "golden hour lighting with warm tones"
- "dramatic studio lighting with soft shadows"
- "ethereal glow with cool undertones"

#### Style References
- "in the style of minimalist flat design"
- "photorealistic with shallow depth of field"
- "abstract digital art with geometric shapes"
- "vintage film photography aesthetic"

#### Composition
- "centered subject with symmetric composition"
- "rule of thirds placement"
- "leading lines converging on subject"

## Troubleshooting

### "MINIMAX_API_KEY not set"
Ensure the environment variable is set in your current shell:

**Windows (PowerShell):**
```powershell
echo $env:MINIMAX_API_KEY  # Should show your key
```

**macOS/Linux:**
```bash
echo $MINIMAX_API_KEY  # Should show your key
```

### "API request failed with HTTP status 400"
- Check your prompt for special characters that may break JSON
- Ensure the prompt isn't empty
- Verify API key is valid

### "API request failed with HTTP status 429"
- Rate limited - wait a moment and retry
- Consider upgrading your API quota

### "No image data found in response"
- The model may have refused the prompt (content policy)
- Try rephrasing the prompt
- Check if the model returned an error message in the response

### Image is corrupted/won't open
- Ensure Python 3.6+ is installed
- Check if the full response was received (network issues)
- Verify output path is writable

### Windows-specific issues
- Make sure Python is in your PATH
- Use forward slashes or escaped backslashes in paths

## API Costs

Check MiniMax pricing for your plan. Image generation typically costs more than text generation.

## Limitations

- Maximum prompt length varies
- Some content types may be restricted by content policy
- Generated images are subject to MiniMax's terms of service
- Rate limits apply based on your API tier


path: minimax-image/scripts/generate_image.py
content: #!/usr/bin/env python3
"""
MiniMax Image - MiniMax Image Generation Script

Cross-platform image generation using MiniMax API.
Works on Windows, macOS, and Linux.

Usage:
    python generate_image.py "prompt" [output_path]

Environment variables:
    MINIMAX_API_KEY (required) - Your MiniMax API key
    IMAGE_SIZE (optional) - Image size: "1K" (default), "2K", or "4K"
    IMAGEAspectRatio (optional) - Aspect ratio: "1:1" (default), "16:9", "9:16", "3:4", "4:3"
"""

import argparse
import json
import os
import sys
import requests
from pathlib import Path


# Configuration
DEFAULT_MODEL_ID = "image-01"
API_BASE_URL = "https://api.minimaxi.com"
DEFAULT_IMAGE_SIZE = "1K"
DEFAULT_ASPECT_RATIO = "1:1"
VALID_SIZES = {"1K", "2K", "4K"}
VALID_ASPECTS = {"1:1", "16:9", "9:16", "3:4", "4:3"}
# Default API key (fallback if MINIMAX_API_KEY env var not set)
DEFAULT_API_KEY = "[REDACTED_SECRET]"


def get_api_endpoint() -> str:
    """Build the API endpoint URL."""
    return f"{API_BASE_URL}/v1/image_generation"


def get_api_key() -> str:
    """Get the MiniMax API key from environment variable, or use default."""
    [REDACTED_SECRET]"MINIMAX_API_KEY") or DEFAULT_API_KEY
    if not api_key or api_key == "your-api-key-here":
        print("Error: MINIMAX_API_KEY environment variable not set and no default key available", file=sys.stderr)
        print("\nTo set it:", file=sys.stderr)
        print("  Windows (PowerShell): $env:MINIMAX_API_KEY = 'your-key'", file=sys.stderr)
        print("  Windows (CMD): set MINIMAX_API_KEY=your-key", file=sys.stderr)
        print("  macOS/Linux: export MINIMAX_API_KEY='your-key'", file=sys.stderr)
        print("\nGet your key from MiniMax dashboard:", file=sys.stderr)
        sys.exit(1)
    return api_key


def validate_image_size(size: str) -> str:
    """Validate and return the image size."""
    if size not in VALID_SIZES:
        print(f"Warning: Invalid IMAGE_SIZE '{size}'. Using default '{DEFAULT_IMAGE_SIZE}'", file=sys.stderr)
        return DEFAULT_IMAGE_SIZE
    return size


def validate_aspect_ratio(aspect: str) -> str:
    """Validate and return the aspect ratio."""
    if aspect not in VALID_ASPECTS:
        print(f"Warning: Invalid IMAGEAspectRatio '{aspect}'. Using default '{DEFAULT_ASPECT_RATIO}'", file=sys.stderr)
        return DEFAULT_ASPECT_RATIO
    return aspect


def create_output_dir(output_path: Path) -> None:
    """Create output directory if it doesn't exist."""
    output_dir = output_path.parent
    if output_dir and not output_dir.exists():
        output_dir.mkdir(parents=True, exist_ok=True)


def build_request_body(prompt: str, image_size: str, aspect_ratio: str) -> dict:
    """Build the JSON request body for the API."""
    request_data = {
        "model": DEFAULT_MODEL_ID,
        "prompt": prompt,
        "aspect_ratio": aspect_ratio,
        "n": 1,
        "response_format": "url"
    }
    return request_data


def make_api_request(api_key: str, request_body: dict) -> dict:
    """Make the API request and return the response."""
    endpoint = get_api_endpoint()

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    try:
        response = requests.post(endpoint, headers=headers, json=request_body, timeout=120)
        
        if response.status_code != 200:
            error_detail = response.text
            try:
                error_data = response.json()
                error_detail = error_data.get("base_resp", {}).get("status_msg", error_detail)
            except:
                pass
            
            if response.status_code == 429:
                print("=" * 60, file=sys.stderr)
                print("ERROR: MiniMax API rate limit exceeded", file=sys.stderr)
                print("=" * 60, file=sys.stderr)
                print("\nWhat to do:", file=sys.stderr)
                print("  1. Wait a moment and try again", file=sys.stderr)
                print("  2. Check your API usage limits", file=sys.stderr)
            elif response.status_code == 403:
                print("=" * 60, file=sys.stderr)
                print("ERROR: MiniMax API access denied", file=sys.stderr)
                print("=" * 60, file=sys.stderr)
                print("\nYour API key is invalid or lacks required permissions.", file=sys.stderr)
            elif response.status_code == 400:
                print("=" * 60, file=sys.stderr)
                print("ERROR: Invalid request to MiniMax API", file=sys.stderr)
                print("=" * 60, file=sys.stderr)
                print(f"\nAPI message: {error_detail}", file=sys.stderr)
            else:
                print(f"Error: API request failed with HTTP status {response.status_code}", file=sys.stderr)
                print(f"API message: {error_detail}", file=sys.stderr)
            sys.exit(1)
        
        return response.json()
    except requests.exceptions.RequestException as e:
        print("=" * 60, file=sys.stderr)
        print("ERROR: Failed to connect to MiniMax API", file=sys.stderr)
        print("=" * 60, file=sys.stderr)
        print(f"\nConnection error: {e}", file=sys.stderr)
        print("\nWhat to do:", file=sys.stderr)
        print("  1. Check your internet connection", file=sys.stderr)
        print("  2. Verify the API endpoint is accessible", file=sys.stderr)
        sys.exit(1)


def extract_image_url(response: dict) -> str:
    """Extract image URL from the API response."""
    try:
        # MiniMax response structure
        image_urls = response.get("data", {}).get("image_urls", [])
        if image_urls and len(image_urls) > 0:
            return image_urls[0]

        raise ValueError("No image URL found in response")
    except (KeyError, IndexError, TypeError) as e:
        print(f"Error: Failed to parse response: {e}", file=sys.stderr)
        print(f"Response: {json.dumps(response, indent=2)}", file=sys.stderr)
        sys.exit(1)


def download_and_save_image(url: str, output_path: Path) -> None:
    """Download image from URL and save to file."""
    try:
        response = requests.get(url, timeout=120)
        response.raise_for_status()
        output_path.write_bytes(response.content)
    except Exception as e:
        print(f"Error: Failed to download image: {e}", file=sys.stderr)
        sys.exit(1)


def get_file_size(path: Path) -> str:
    """Get human-readable file size."""
    size = path.stat().st_size
    for unit in ["B", "KB", "MB", "GB"]:
        if size < 1024:
            return f"{size:.1f} {unit}"
        size /= 1024
    return f"{size:.1f} TB"


def main():
    parser = argparse.ArgumentParser(
        description="Generate images using MiniMax AI",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python generate_image.py "A sunset over mountains"
  python generate_image.py "An app icon" ./icons/app.png
  python generate_image.py --size 2K "High-res landscape" ./wallpaper.png
  python generate_image.py --aspect 16:9 "Wide banner" ./banner.png

Environment Variables:
  MINIMAX_API_KEY     Your MiniMax API key (required)
  IMAGE_SIZE          Image size: 1K (default), 2K, or 4K
  IMAGEAspectRatio    Aspect ratio: 1:1 (default), 16:9, 9:16, 3:4, 4:3
        """
    )
    parser.add_argument("prompt", help="Text description of the image to generate")
    parser.add_argument("output", nargs="?", default="./generated-image.png",
                        help="Output file path (default: ./generated-image.png)")
    parser.add_argument("--size", choices=["1K", "2K", "4K"],
                        help="Image size (overrides IMAGE_SIZE env var)")
    parser.add_argument("--aspect", "--aspect-ratio", dest="aspect_ratio",
                        choices=["1:1", "16:9", "9:16", "3:4", "4:3"],
                        help="Aspect ratio (overrides IMAGEAspectRatio env var)")

    args = parser.parse_args()

    # Get configuration
    [REDACTED_SECRET])
    image_size = args.size or os.environ.get("IMAGE_SIZE", DEFAULT_IMAGE_SIZE)
    image_size = validate_image_size(image_size)
    aspect_ratio = args.aspect_ratio or os.environ.get("IMAGEAspectRatio", DEFAULT_ASPECT_RATIO)
    aspect_ratio = validate_aspect_ratio(aspect_ratio)
    output_path = Path(args.output)

    # Create output directory
    create_output_dir(output_path)

    # Display info
    print(f"Generating image with prompt: \"{args.prompt}\"")
    print(f"Model: {DEFAULT_MODEL_ID}")
    print(f"Image size: {image_size}")
    print(f"Aspect ratio: {aspect_ratio}")
    print(f"Output path: {output_path}")
    print()

    # Build and send request
    request_body = build_request_body(args.prompt, image_size, aspect_ratio)
    response = make_api_request(api_key, request_body)

    # Extract and save image
    image_url = extract_image_url(response)
    if not image_url:
        print("Error: No image URL received from API", file=sys.stderr)
        sys.exit(1)

    print(f"\nDownloading image from URL...")
    download_and_save_image(image_url, output_path)

    # Verify and report success
    if output_path.exists() and output_path.stat().st_size > 0:
        file_size = get_file_size(output_path)
        print("Success! Image generated and saved.")
        print(f"File: {output_path}")
        print(f"Size: {file_size}")
    else:
        print(f"Error: Failed to save image to {output_path}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()


path: reference.md
content: # MiniMax Image Skill Reference

## Setup

### 1. Get a MiniMax API Key

1. Go to MiniMax Dashboard or your Coding Plan settings
2. Find your API key for image generation
3. Copy the API key

### 2. Set Environment Variable

**Windows (PowerShell):**
```powershell
$env:MINIMAX_API_KEY = "your-api-key-here"

# To persist across sessions, add to your PowerShell profile:
Add-Content $PROFILE "`n`$env:MINIMAX_API_KEY = 'your-api-key-here'"
```

**Windows (CMD):**
```cmd
set MINIMAX_API_KEY=your-api-key-here

# To persist, use System Properties > Environment Variables
```

**macOS/Linux:**
```bash
export MINIMAX_API_KEY="your-api-key-here"

# Add to ~/.zshrc or ~/.bashrc to persist
echo 'export MINIMAX_API_KEY="your-api-key-here"' >> ~/.zshrc
```

## API Reference

### Model

- **Model ID**: `image-01` (MiniMax's image generation model)
- **Endpoint**: `https://api.minimaxi.com/v1/image_generation`

### Image Sizes

| Size | Description |
|------|-------------|
| `1K` | 1024x1024 pixels - Default, balanced quality/speed |
| `2K` | 2048x2048 pixels - High resolution |
| `4K` | 4096x4096 pixels - Ultra high resolution |

### Aspect Ratios

| Ratio | Description |
|-------|-------------|
| `1:1` | Square - Default |
| `16:9` | Wide - Suitable for banners, hero images |
| `9:16` | Portrait - Suitable for mobile content |
| `3:4` | Portrait - Standard photo ratio |
| `4:3` | Landscape - Classic photo ratio |

## Script Parameters

### Python Script (Cross-Platform)

```bash
python scripts/generate_image.py <prompt> [output_path] [--size SIZE] [--aspect RATIO]
```

| Parameter | Required | Default | Description |
|-----------|----------|---------|-------------|
| `prompt` | Yes | - | Text description of desired image |
| `output_path` | No | `./generated-image.png` | Where to save the image |
| `--size` | No | `1K` | Image size (1K, 2K, or 4K) |
| `--aspect` | No | `1:1` | Aspect ratio (1:1, 16:9, 9:16, 3:4, 4:3) |

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `MINIMAX_API_KEY` | Yes | - | Your MiniMax API key |
| `IMAGE_SIZE` | No | `1K` | Image size (1K, 2K, or 4K) |
| `IMAGEAspectRatio` | No | `1:1` | Aspect ratio (1:1, 16:9, 9:16, 3:4, 4:3) |

## Usage Examples

### Basic Generation

```bash
python scripts/generate_image.py "A serene mountain landscape at dawn"
```

### Custom Output Path

```bash
python scripts/generate_image.py "Minimalist logo design" "./assets/logo.png"
```

### High Resolution

```bash
python scripts/generate_image.py --size 2K "Detailed portrait" "./high-res.png"
```

### Wide Banner

```bash
python scripts/generate_image.py --size 2K --aspect 16:9 "Product banner" "./banner.png"
```

### Mobile Wallpaper

```bash
python scripts/generate_image.py --size 2K --aspect 9:16 "Mobile wallpaper" "./phone-bg.png"
```

## Prompt Tips

### For Best Results

1. **Be specific**: "A red sports car" vs "A cherry red 1967 Mustang convertible"
2. **Include style**: "in watercolor style", "photorealistic", "minimalist flat design"
3. **Mention lighting**: "golden hour lighting", "soft diffused light", "dramatic shadows"
4. **Specify composition**: "close-up", "wide angle", "from above", "centered"

### Advanced Prompting Techniques

These techniques produce significantly better results:

#### Lighting & Atmosphere
- "golden hour lighting with warm tones"
- "dramatic studio lighting with soft shadows"
- "ethereal glow with cool undertones"

#### Style References
- "in the style of minimalist flat design"
- "photorealistic with shallow depth of field"
- "abstract digital art with geometric shapes"
- "vintage film photography aesthetic"

#### Composition
- "centered subject with symmetric composition"
- "rule of thirds placement"
- "leading lines converging on subject"

## Troubleshooting

### "MINIMAX_API_KEY not set"
Ensure the environment variable is set in your current shell:

**Windows (PowerShell):**
```powershell
echo $env:MINIMAX_API_KEY  # Should show your key
```

**macOS/Linux:**
```bash
echo $MINIMAX_API_KEY  # Should show your key
```

### "API request failed with HTTP status 400"
- Check your prompt for special characters that may break JSON
- Ensure the prompt isn't empty
- Verify API key is valid

### "API request failed with HTTP status 429"
- Rate limited - wait a moment and retry
- Consider upgrading your API quota

### "No image data found in response"
- The model may have refused the prompt (content policy)
- Try rephrasing the prompt
- Check if the model returned an error message in the response

### Image is corrupted/won't open
- Ensure Python 3.6+ is installed
- Check if the full response was received (network issues)
- Verify output path is writable

### Windows-specific issues
- Make sure Python is in your PATH
- Use forward slashes or escaped backslashes in paths

## API Costs

Check MiniMax pricing for your plan. Image generation typically costs more than text generation.

## Limitations

- Maximum prompt length varies
- Some content types may be restricted by content policy
- Generated images are subject to MiniMax's terms of service
- Rate limits apply based on your API tier


path: scripts/generate_image.py
content: #!/usr/bin/env python3
"""
MiniMax Image - MiniMax Image Generation Script

Cross-platform image generation using MiniMax API.
Works on Windows, macOS, and Linux.

Usage:
    python generate_image.py "prompt" [output_path]

Environment variables:
    MINIMAX_API_KEY (required) - Your MiniMax API key
    IMAGE_SIZE (optional) - Image size: "1K" (default), "2K", or "4K"
    IMAGEAspectRatio (optional) - Aspect ratio: "1:1" (default), "16:9", "9:16", "3:4", "4:3"
"""

import argparse
import base64
import json
import os
import sys
import urllib.request
import urllib.error
from pathlib import Path


# Configuration
DEFAULT_MODEL_ID = "image-01"
API_BASE_URL = "https://api.minimaxi.com/v1/image_generation"
DEFAULT_IMAGE_SIZE = "1K"
DEFAULT_ASPECT_RATIO = "1:1"
VALID_SIZES = {"1K", "2K", "4K"}
VALID_ASPECTS = {"1:1", "16:9", "9:16", "3:4", "4:3"}
# Default API key (fallback if MINIMAX_API_KEY env var not set)
DEFAULT_API_KEY = "[REDACTED_SECRET]"


def get_api_endpoint() -> str:
    """Build the API endpoint URL."""
    return f"{API_BASE_URL}"


def get_api_key() -> str:
    """Get the MiniMax API key from environment variable, or use default."""
    [REDACTED_SECRET]"MINIMAX_API_KEY") or DEFAULT_API_KEY
    if not api_key or api_key == "your-api-key-here":
        print("Error: MINIMAX_API_KEY environment variable not set and no default key available", file=sys.stderr)
        print("\nTo set it:", file=sys.stderr)
        print("  Windows (PowerShell): $env:MINIMAX_API_KEY = 'your-key'", file=sys.stderr)
        print("  Windows (CMD): set MINIMAX_API_KEY=your-key", file=sys.stderr)
        print("  macOS/Linux: export MINIMAX_API_KEY='your-key'", file=sys.stderr)
        print("\nGet your key from MiniMax dashboard:", file=sys.stderr)
        sys.exit(1)
    return api_key


def validate_image_size(size: str) -> str:
    """Validate and return the image size."""
    if size not in VALID_SIZES:
        print(f"Warning: Invalid IMAGE_SIZE '{size}'. Using default '{DEFAULT_IMAGE_SIZE}'", file=sys.stderr)
        return DEFAULT_IMAGE_SIZE
    return size


def validate_aspect_ratio(aspect: str) -> str:
    """Validate and return the aspect ratio."""
    if aspect not in VALID_ASPECTS:
        print(f"Warning: Invalid IMAGEAspectRatio '{aspect}'. Using default '{DEFAULT_ASPECT_RATIO}'", file=sys.stderr)
        return DEFAULT_ASPECT_RATIO
    return aspect


def create_output_dir(output_path: Path) -> None:
    """Create output directory if it doesn't exist."""
    output_dir = output_path.parent
    if output_dir and not output_dir.exists():
        output_dir.mkdir(parents=True, exist_ok=True)


def build_request_body(prompt: str, image_size: str, aspect_ratio: str) -> bytes:
    """Build the JSON request body for the API."""
    request_data = {
        "model": DEFAULT_MODEL_ID,
        "prompt": prompt,
        "image_size": image_size,
        "aspect_ratio": aspect_ratio
    }
    return json.dumps(request_data).encode("utf-8")


def make_api_request(api_key: str, request_body: bytes) -> dict:
    """Make the API request and return the response."""
    endpoint = get_api_endpoint()

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    req = urllib.request.Request(endpoint, data=request_body, headers=headers, method="POST")

    try:
        with urllib.request.urlopen(req, timeout=120) as response:
            return json.loads(response.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        error_body = e.read().decode("utf-8") if e.fp else ""
        error_detail = ""

        # Try to extract error message from response
        if error_body:
            try:
                error_json = json.loads(error_body)
                error_detail = error_json.get("error", {}).get("message", "")
                if not error_detail:
                    error_detail = error_json.get("message", error_body)
            except json.JSONDecodeError:
                error_detail = error_body

        # Provide user-friendly messages for common errors
        if e.code == 429:
            print("=" * 60, file=sys.stderr)
            print("ERROR: MiniMax API rate limit exceeded", file=sys.stderr)
            print("=" * 60, file=sys.stderr)
            print("\nWhat to do:", file=sys.stderr)
            print("  1. Wait a moment and try again", file=sys.stderr)
            print("  2. Check your API usage limits", file=sys.stderr)
            if error_detail:
                print(f"\nAPI message: {error_detail}", file=sys.stderr)
        elif e.code == 403:
            print("=" * 60, file=sys.stderr)
            print("ERROR: MiniMax API access denied", file=sys.stderr)
            print("=" * 60, file=sys.stderr)
            print("\nYour API key is invalid or lacks required permissions.", file=sys.stderr)
            print("\nWhat to do:", file=sys.stderr)
            print("  1. Verify your API key", file=sys.stderr)
            print("  2. Ensure image generation is enabled for your plan", file=sys.stderr)
            if error_detail:
                print(f"\nAPI message: {error_detail}", file=sys.stderr)
        elif e.code == 400:
            print("=" * 60, file=sys.stderr)
            print("ERROR: Invalid request to MiniMax API", file=sys.stderr)
            print("=" * 60, file=sys.stderr)
            print("\nThe request was rejected by the API.", file=sys.stderr)
            print("\nPossible causes:", file=sys.stderr)
            print("  - Prompt may contain blocked content", file=sys.stderr)
            print("  - Prompt format may be invalid", file=sys.stderr)
            if error_detail:
                print(f"\nAPI message: {error_detail}", file=sys.stderr)
        elif e.code >= 500:
            print("=" * 60, file=sys.stderr)
            print("ERROR: MiniMax API server error", file=sys.stderr)
            print("=" * 60, file=sys.stderr)
            print(f"\nThe API returned a server error (HTTP {e.code}).", file=sys.stderr)
            print("\nWhat to do:", file=sys.stderr)
            print("  1. Wait a few minutes and try again", file=sys.stderr)
            print("  2. Check MiniMax API status if the issue persists", file=sys.stderr)
            if error_detail:
                print(f"\nAPI message: {error_detail}", file=sys.stderr)
        else:
            print(f"Error: API request failed with HTTP status {e.code}", file=sys.stderr)
            if error_detail:
                print(f"API message: {error_detail}", file=sys.stderr)
            elif error_body:
                print(f"Response: {error_body}", file=sys.stderr)

        sys.exit(1)
    except urllib.error.URLError as e:
        print("=" * 60, file=sys.stderr)
        print("ERROR: Failed to connect to MiniMax API", file=sys.stderr)
        print("=" * 60, file=sys.stderr)
        print(f"\nConnection error: {e.reason}", file=sys.stderr)
        print("\nWhat to do:", file=sys.stderr)
        print("  1. Check your internet connection", file=sys.stderr)
        print("  2. Verify the API endpoint is accessible", file=sys.stderr)
        print("  3. Check if a firewall or proxy is blocking the request", file=sys.stderr)
        sys.exit(1)


def extract_image_data(response: dict) -> str:
    """Extract base64 image data from the API response."""
    try:
        # MiniMax response structure
        if "data" in response and len(response["data"]) > 0:
            return response["data"][0].get("base64", "")

        raise ValueError("No image data found in response")
    except (KeyError, IndexError, TypeError) as e:
        print(f"Error: Failed to parse response: {e}", file=sys.stderr)
        print(f"Response: {json.dumps(response, indent=2)}", file=sys.stderr)
        sys.exit(1)


def save_image(image_data: str, output_path: Path) -> None:
    """Decode and save the base64 image data."""
    try:
        image_bytes = base64.b64decode(image_data)
        output_path.write_bytes(image_bytes)
    except Exception as e:
        print(f"Error: Failed to save image: {e}", file=sys.stderr)
        sys.exit(1)


def get_file_size(path: Path) -> str:
    """Get human-readable file size."""
    size = path.stat().st_size
    for unit in ["B", "KB", "MB", "GB"]:
        if size < 1024:
            return f"{size:.1f} {unit}"
        size /= 1024
    return f"{size:.1f} TB"


def main():
    parser = argparse.ArgumentParser(
        description="Generate images using MiniMax AI",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python generate_image.py "A sunset over mountains"
  python generate_image.py "An app icon" ./icons/app.png
  python generate_image.py --size 2K "High-res landscape" ./wallpaper.png
  python generate_image.py --aspect 16:9 "Wide banner" ./banner.png

Environment Variables:
  MINIMAX_API_KEY     Your MiniMax API key (required)
  IMAGE_SIZE          Image size: 1K (default), 2K, or 4K
  IMAGEAspectRatio    Aspect ratio: 1:1 (default), 16:9, 9:16, 3:4, 4:3
        """
    )
    parser.add_argument("prompt", help="Text description of the image to generate")
    parser.add_argument("output", nargs="?", default="./generated-image.png",
                        help="Output file path (default: ./generated-image.png)")
    parser.add_argument("--size", choices=["1K", "2K", "4K"],
                        help="Image size (overrides IMAGE_SIZE env var)")
    parser.add_argument("--aspect", "--aspect-ratio", dest="aspect_ratio",
                        choices=["1:1", "16:9", "9:16", "3:4", "4:3"],
                        help="Aspect ratio (overrides IMAGEAspectRatio env var)")

    args = parser.parse_args()

    # Get configuration
    [REDACTED_SECRET])
    image_size = args.size or os.environ.get("IMAGE_SIZE", DEFAULT_IMAGE_SIZE)
    image_size = validate_image_size(image_size)
    aspect_ratio = args.aspect_ratio or os.environ.get("IMAGEAspectRatio", DEFAULT_ASPECT_RATIO)
    aspect_ratio = validate_aspect_ratio(aspect_ratio)
    output_path = Path(args.output)

    # Create output directory
    create_output_dir(output_path)

    # Display info
    print(f"Generating image with prompt: \"{args.prompt}\"")
    print(f"Model: {DEFAULT_MODEL_ID}")
    print(f"Image size: {image_size}")
    print(f"Aspect ratio: {aspect_ratio}")
    print(f"Output path: {output_path}")
    print()

    # Build and send request
    request_body = build_request_body(args.prompt, image_size, aspect_ratio)
    response = make_api_request(api_key, request_body)

    # Extract and save image
    image_data = extract_image_data(response)
    if not image_data:
        print("Error: No image data received from API", file=sys.stderr)
        sys.exit(1)

    save_image(image_data, output_path)

    # Verify and report success
    if output_path.exists() and output_path.stat().st_size > 0:
        file_size = get_file_size(output_path)
        print("Success! Image generated and saved.")
        print(f"File: {output_path}")
        print(f"Size: {file_size}")
    else:
        print(f"Error: Failed to save image to {output_path}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()


path: scripts/image_gen.py
content: #!/usr/bin/env python3
"""
MiniMax 图像生成脚本
"""

import os
import sys
import time
import argparse
import requests

[REDACTED_SECRET]"MINIMAX_API_KEY")
if not [REDACTED_SECRET]"Error: MINIMAX_API_KEY environment variable not set")
    print("Please set it with: export MINIMAX_API_KEY=\"your-api-key\"")
    sys.exit(1)

HEADERS = {"Authorization": f"Bearer {API_KEY}"}
API_HOST = "https://api.minimaxi.com"


def generate_image(prompt: str, model: str = "image-01",
                   size: str = "1024x1024", n: int = 1,
                   output_path: str = "output.png") -> list:
    """调用 MiniMax 图像生成 API"""
    url = f"{API_HOST}/v1/image_generation"

    # size 映射
    size_map = {
        "1024x1024": "1:1",
        "1024x1792": "9:16",
        "1792x1024": "16:9",
        "1024x1536": "2:3",
        "1536x1024": "3:2",
    }
    aspect_ratio = size_map.get(size, "1:1")

    payload = {
        "model": model,
        "prompt": prompt,
        "aspect_ratio": aspect_ratio,
        "num_images": n,
    }

    print(f"🖼️  正在生成图片...")
    print(f"   模型: {model} | 尺寸: {size} | 数量: {n}")
    print(f"   描述: {prompt[:80]}{'...' if len(prompt) > 80 else ''}")

    resp = requests.post(url, headers=HEADERS, json=payload, timeout=60)
    resp.raise_for_status()
    data = resp.json()

    base_resp = data.get("base_resp", {})
    if base_resp.get("status_code") != 0:
        task_id = data.get("task_id")
        if task_id:
            print(f"⏳ 异步任务 ID: {task_id}，开始轮询...")
            image_urls = poll_image_task(task_id)
            if image_urls:
                download_images(image_urls, output_path)
                return image_urls
        raise Exception(f"API Error: {base_resp.get('status_msg', 'unknown')}")

    # 同步返回图片 URL 列表
    image_urls = data.get("image_urls", [])
    if image_urls:
        download_images(image_urls, output_path)
        return image_urls

    raise Exception("未获取到图片数据")


def poll_image_task(task_id: str, max_wait: int = 300) -> list:
    """轮询图像生成任务状态"""
    url = f"{API_HOST}/v1/query/image_generation"
    params = {"task_id": task_id}

    for i in range(max_wait // 10):
        time.sleep(10)
        resp = requests.get(url, headers=HEADERS, params=params, timeout=30)
        resp.raise_for_status()
        data = resp.json()

        status = data.get("status", "")
        print(f"  状态: {status}")
        if status == "Success":
            return data.get("image_urls", [])
        elif status == "Fail":
            raise Exception(f"图片生成失败: {data.get('error_message', 'unknown')}")
    raise Exception("图片生成任务超时")


def download_images(image_urls: list, output_path: str):
    """下载图片"""
    os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
    base, ext = os.path.splitext(output_path)

    for i, url in enumerate(image_urls):
        path = output_path if len(image_urls) == 1 else f"{base}_{i+1}{ext}"
        print(f"📥 下载图片: {path}")
        resp = requests.get(url, timeout=60)
        resp.raise_for_status()
        with open(path, "wb") as f:
            f.write(resp.content)
        print(f"✅ 已保存: {path}")


def main():
    parser = argparse.ArgumentParser(description="MiniMax 图像生成")
    parser.add_argument("--prompt", required=True, help="图片描述文本")
    parser.add_argument("--model", default="image-01", help="模型名称")
    parser.add_argument("--size", default="1024x1024",
                        help="尺寸: 1024x1024, 1024x1792, 1792x1024, 1024x1536, 1536x1024")
    parser.add_argument("--n", type=int, default=1, help="生成图片数量")
    parser.add_argument("--output", default="output.png", help="输出文件路径")

    args = parser.parse_args()

    try:
        urls = generate_image(
            prompt=args.prompt,
            model=args.model,
            size=args.size,
            n=args.n,
            output_path=args.output,
        )
        print(f"\n📎 输出文件: {args.output}")
    except Exception as e:
        print(f"❌ 错误: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector:  ()