---
name: kie-ai
effort: medium
description: >
  Generate images, videos, and audio using Kie.ai's unified AI API platform (80+ models).
  Use when: (1) generating images from text or editing images (Nano Banana 2, Imagen 4, Flux Kontext,
  4o Image, Seedream, Grok Imagine, Qwen, Ideogram, Flux-2, GPT Image 1.5, Z-Image),
  (2) generating videos from text/images (Kling 3.0, Sora 2, Veo 3.1, Runway Gen-4, Wan 2.6,
  Hailuo, Bytedance Seedance), (3) upscaling images/videos (Topaz, Recraft),
  (4) generating music/audio (Suno V4, ElevenLabs TTS/SFX), (5) removing backgrounds,
  (6) any task involving "kie", "kie.ai", "genera immagine", "genera video", "crea immagine",
  "crea video", "text to image", "text to video", "image to video", or model names like
  "nano banana", "imagen", "flux", "kling", "sora", "veo", "runway", "seedream", "wan",
  "hailuo", "midjourney", "suno", "elevenlabs".
  Triggers on: /kie, /generate-image, /generate-video, /kie-setup.
---

# Kie.ai — AI Image, Video & Audio Generation

## Project Context

**Reads from `baldart.config.yml`:** `paths.design_system`, `paths.ui_guidelines`, `identity.design_philosophy`, `identity.brand_name`.
**Gated by features:** `features.has_design_system` (when `true`, the design-system reads below are BLOCKING; when `false`, fall back to `paths.ui_guidelines` alone).
**Overlay:** loads `.baldart/overlays/kie-ai.md` if present — project-specific illustration character library, video-prompt motion vocabulary, and forbidden aesthetic patterns.
**On missing/empty keys:** ask the user; do not assume defaults. See `framework/agents/project-context.md` § 3.

## Effort

**Baseline:** `effort: medium` (frontmatter). **Inline override:** pass
`effort=<low|medium|high|xhigh|max>` anywhere in the invocation to scale
reasoning depth for this run — detect it once at kickoff and strip the token
before consuming user input. Level→behavior mapping, parsing contract, and
precedence caveats: `framework/agents/effort-protocol.md`.


## Visual Contract (project-specific)

When generating images, videos, or animation prompts for product illustrations, the project's design-system SSOT is a BLOCKING prerequisite before model selection or prompt writing — but only when the project has one. Reading order:

1. `${paths.design_system}/INDEX.md` — design-system entry point (when `features.has_design_system: true`).
2. `${paths.design_system}/tokens-reference.md` — canonical color and shadow contract (when present).
3. `${paths.ui_guidelines}` — brand visual language and UI constraints.
4. `${paths.design_system}/patterns/illustration-motion.md` — canonical illustration, character, product-variant, and surgical video-prompt rules (when present; otherwise consult `.baldart/overlays/kie-ai.md`).

Every prompt should reflect `identity.design_philosophy` (e.g. "Neo-Brutalism" → bold flat shapes + hard offsets; "Minimalist" → restrained palette + breathing room). Every video prompt should use element-by-element "surgical motion" rules (what moves, what reacts, what stays fixed) rather than leaving motion to implicit model interpretation.

## Setup (First-Time)

If no API key is configured, run setup before any generation:

```bash
bash scripts/setup_api_key.sh
```

Stores key securely in macOS Keychain (or `~/.config/kie-ai/config` on Linux).
Get your key at: <https://kie.ai/api-key>

Check remaining credits:

```bash
bash scripts/kie_api.sh credits
```

## Quick Reference

- **Full model catalog with parameters**: Read [references/models-catalog.md](references/models-catalog.md)
- **API helper script**: `scripts/kie_api.sh` (handles auth, create, poll, download)
- **Base URL**: `https://api.kie.ai`
- **Auth**: `Authorization: Bearer <KEY>` (key retrieved automatically by scripts)
- **Docs**: <https://docs.kie.ai>

## Limits

Max 20 requests / 10 seconds, ~100 concurrent. HTTP 429 = wait and retry.

## How It Works

All Kie.ai APIs are **asynchronous**:
1. **Create task** → get `taskId`
2. **Poll status** until `success` or `fail`
3. **Download** the generated file (URLs valid 14 days, direct downloads 20 min)

## API Patterns

Two patterns exist (Market Unified vs Dedicated). See [models-catalog.md](references/models-catalog.md#two-api-patterns) for details. The helper script handles both — use `create-market` or `create`.

## Generation Workflow

### Step 1: Determine task and model

**Default model for images: `nano-banana-2`** (Nano Banana 2). Use it automatically
unless the user explicitly requests a different model. Do NOT present a model selection
menu — just proceed with nano-banana-2. Mention alternatives only if the user asks
"quale modello?" or names a specific one.

**Default model for videos: `kling-3.0/video`** (Kling 3.0).

If the user needs **maximum fidelity or complex text rendering**, suggest upgrading to
`nano-banana-pro` (Gemini 3.0 Pro, 18-24 cr) — same API pattern, just change model ID.

Alternative models (only when explicitly requested):
- **Images**: Nano Banana Pro, Imagen 4, Flux Kontext, 4o Image, Seedream, Flux-2, Grok Imagine
- **Videos**: Veo 3.1, Sora 2, Runway Gen-4 Turbo, Runway Aleph (V2V/VFX), Wan 2.6, Hailuo, Luma Modify
- **Audio**: Suno V4 (music), ElevenLabs (TTS, SFX, dialogue)
- **Upscale**: Topaz (image/video), Recraft (background removal, upscale)

For model-specific parameters, read [references/models-catalog.md](references/models-catalog.md).

### Step 2: Collect parameters

Ask for the essential parameters only:
- **Prompt** (always required)
- **Aspect ratio** (default `1:1` if not specified)
- **Resolution** for nano-banana-2: default `2K` (good balance quality/cost at 12 credits)

For non-default models, read [references/models-catalog.md](references/models-catalog.md) for exact parameters.

Common parameters across models:
- `prompt` (always required for generation)
- `aspect_ratio` / `size` (varies per model)
- `callBackUrl` (optional, omit for polling)
- Image/video URLs for edit/I2V modes

### Step 2.5: Transparency Check (images only — SKIP for video/audio/upscale)

**This step applies ONLY to image generation.** Skip entirely for video, audio, and upscale tasks.

**HARD GATE.** Before sending ANY image generation request, you MUST
ask the user whether they need a transparent background. Do NOT skip this step. Do NOT
assume the answer.

**Ask explicitly:**

> **Sfondo trasparente?**
> L'immagine deve avere lo sfondo trasparente (PNG con alpha)?
> - **A)** Si, sfondo trasparente
> - **B)** No, sfondo normale

**⛔ STOP.** Wait for the user's answer before proceeding.

**If the user wants transparent background:**

1. **Modify the prompt** — append to the user's prompt:
   ```
   The subject MUST be placed on a perfectly uniform, solid, bright GREEN
   (#00FF00) chroma-key background. The green must be flat, even, with NO
   shadows, NO gradients, NO reflections on the green area. The subject
   must have clean, sharp edges with NO green spill on the subject itself.
   ```
2. **Force PNG output** — set `output_format: "png"` (or equivalent per model).
3. **Set `needs_transparency: true`** in your internal tracking for this request.

**If the user does NOT want transparent background:**
- Proceed normally. Set `needs_transparency: false`.

**Detection from context:** If the user's original request or the calling system
already mentions "transparent", "sfondo trasparente", "no background", "alpha",
"PNG with transparency", or "rimuovi sfondo" → still ask the question to confirm,
but default the recommendation to **A) Si**.

### Output Path Convention

Save all generated files to `/tmp/kie-ai/`. Create the directory if it doesn't exist.
Naming: `<slug>-<timestamp>.<ext>` (e.g., `promo-cityscape-20260404-143022.png`).
For transparency processing: raw file as `<name>-raw-greenscreen.png`, final as `<name>.png`.

### Step 3: Execute

Use the helper script:

```bash
# Market models (most models)
bash scripts/kie_api.sh create-market '{
  "model": "nano-banana-2",
  "input": {
    "prompt": "A futuristic cityscape at sunset",
    "aspect_ratio": "16:9",
    "resolution": "2K"
  }
}'

# Dedicated models (Runway, Veo3, 4o Image, Flux Kontext)
bash scripts/kie_api.sh create "/api/v1/veo/generate" '{
  "prompt": "A cat exploring a magical forest",
  "model": "veo3_fast",
  "aspect_ratio": "16:9"
}'
```

### Step 4: Poll and download

```bash
# Market models
bash scripts/kie_api.sh poll-market "task_12345" 60 10

# Dedicated models
bash scripts/kie_api.sh poll "/api/v1/veo/record-info" "veo_task_abc" 60 10

# Download result
bash scripts/kie_api.sh download "https://tempfile..." "./output.png"
```

### Step 5: Post-process and present result

**If `needs_transparency` is true:**

After downloading the image, remove the green screen and produce a transparent PNG:

```bash
python3 scripts/remove_greenscreen.py "<input_path>" "<output_path>" [--tolerance 60] [--edge-blur 1]
```

The script:
1. Converts green (#00FF00 region) to transparent alpha
2. Applies edge cleanup to remove green fringe/spill
3. Saves as PNG with alpha channel

Parameters:
- `--tolerance` (default 60): how much deviation from pure green to include (0-255).
  Increase if green remnants remain, decrease if subject edges are eaten.
- `--edge-blur` (default 1): pixel radius for edge anti-aliasing. Use 0 for pixel-perfect
  edges, 2-3 for softer blending.

After processing, show the user the **transparent PNG path** (not the raw green screen
version). Keep the raw version as `<name>-raw-greenscreen.png` in case the user wants
to re-process with different tolerance.

**If `needs_transparency` is false:**

Show the user the download URL or local file path. If multiple URLs, list them all.

## Error Handling

| Code | Meaning | Action |
|------|---------|--------|
| 200 | Task created (NOT completed) | Poll for result |
| 401 | Invalid API key | Re-run setup |
| 402 | Insufficient credits | Top up at kie.ai |
| 422 | Invalid parameters | Check model docs |
| 429 | Rate limited | Wait and retry |
| 451 | Image fetch failed | Check image URL |
| 455 | Service maintenance | Wait |
| 500 | Server error | Retry |
| 501 | Generation failed | Retry with different params |

## File Upload (when user has local files)

```bash
# Upload local file
bash scripts/kie_api.sh upload-stream "/path/to/image.png"

# Upload from URL
bash scripts/kie_api.sh upload-url "https://example.com/image.png"
```

Upload response contains `fileUrl` to use as input. Files expire in 3 days.

## Pricing Reference (credits)

**Default models:**

| Model | Cost |
|-------|------|
| Nano Banana 2 (1K) | 8 cr |
| Nano Banana 2 (2K) | 12 cr |
| Nano Banana 2 (4K) | 18 cr |
| Kling 3.0 video | 20-40 cr/s |
| Recraft bg removal | 2 cr |

For other models, see [references/models-catalog.md](references/models-catalog.md).

Check credits: `bash scripts/kie_api.sh credits`
