> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apiyi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Hunyuan Hy-Image 3.5 Agent Skill

> Package Tencent Hunyuan Hy-Image 3.5 Preview (hy-image-v3.5-preview-2k / -4k) as a drop-in Agent Skill for Codex, Claude Code, Cursor, and other coding agents. Generate 2K/4K images or restyle reference images with one prompt.

> [!NOTE]
>
> This page provides a **ready-to-use Agent Skill**: drop it into your coding agent and call APIYI's **Tencent Hunyuan Hy-Image 3.5 Preview** (`hy-image-v3.5-preview-2k` / `hy-image-v3.5-preview-4k`) in natural language or with explicit commands. It is just two files; copy and use.

> [!TIP]
>
> The skill defaults to `hy-image-v3.5-preview-2k` (2048×2048, \$0.022 per image). Top-up bonuses bring the effective price to about **83–91% of list**; see [Top-up Bonuses](https://docs.apiyi.com/en/faq/recharge-promotions.md). Add `-m 4k` for 4096×4096. Pass local reference images with `-i`; the script converts them to the data URIs expected by the `images` array. For direct API integration, see the [text-to-image API](https://docs.apiyi.com/en/api-capabilities/hunyuan-image/text-to-image.md) and the [reference-image API](https://docs.apiyi.com/en/api-capabilities/hunyuan-image/image-edit.md).

## What the Skill Does

One script that switches behavior based on whether reference images are supplied:

> [card] Text-to-Image
>
> Prompt only → a 2048×2048 (2K) or 4096×4096 (4K) image, with strong Chinese text rendering.

> [card] Reference-Image Generation
>
> One local image + instruction → style transfer, composition preservation, or local edits.

> [card] Multi-Image Fusion
>
> Multiple images + one instruction → combine subjects in a single scene; refer to them as "image 1 / image 2".

## Which Agents Can Use It

> [!NOTE]
>
> A Skill is essentially a folder: a `SKILL.md` instruction file for the agent and a script that does the work. **Any coding agent that can read local files and run shell commands can use it** — Codex, Claude Code, Cursor, and others. The only requirements are **Python 3** and network access to `api.apiyi.com`.

## Three-Step Setup

### ① Create the folder and add the files

Create a skill folder with these two files:

```
hunyuan-image/
├── SKILL.md
├── scripts/
│   └── hunyuan_image.py
└── .env          # Created in step ②, holds your key
```

### ② Add your key

Write your **APIYI API key** (created in the `api.apiyi.com` console) to `hunyuan-image/.env`:

```bash theme={null}
APIYI_API_KEY=sk-your-api-key
```

The script reads the key from this `.env` automatically.

> [!WARNING]
>
> `.env` contains your secret key. If you share this skill in a project repository, **add `.env` to `.gitignore` and never commit it**.

### ③ Hand it to your agent

* **Agents with skill discovery** (such as Claude Code): put the whole `hunyuan-image/` folder in the skill directory — `~/.claude/skills/` for personal use or `.claude/skills/` for project use.
* **Other agents**: follow their skill/plugin convention, or simply tell the agent to read `SKILL.md` in the folder and follow it.

Then jump to [Usage](#usage).

## SKILL.md

Create `hunyuan-image/SKILL.md` with the following content:

````markdown theme={null}
---
name: hunyuan-image
description: Generate or edit images via APIYI's Tencent Hunyuan Hy-Image 3.5 Preview (hy-image-v3.5-preview-2k / -4k). Use when the user asks to create, draw, render, or generate an image, poster, or illustration, or to restyle, edit, or composite existing images with reference images.
allowed-tools: Bash(python3 *)
---

# Hunyuan Hy-Image 3.5 Image Skill

Generate or edit images through APIYI's Tencent Hunyuan Hy-Image 3.5 Preview (`hy-image-v3.5-preview-2k` / `hy-image-v3.5-preview-4k`). Defaults to 2048×2048; supports 4096×4096. Chinese text rendering is strong.

## Key Configuration

The script reads `APIYI_API_KEY` from the `.env` file in the skill directory (or from the environment).
If it reports a missing key, ask the user to add `APIYI_API_KEY=sk-xxx` to `.env`.

## Usage

Run the script in `scripts/`. The first positional argument is the prompt. Pass local reference images with repeated `-i` flags:

```bash
# Text-to-image (default 2K, 2048×2048)
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "A Chinese movie poster titled Between Mountains and Seas, deep blue night sky and golden mountains" -o poster.png

# 4K text-to-image (4096×4096)
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "Print-quality product hero image, metallic texture, studio lighting" -m 4k -o hero-4k.png

# Reference-image generation (2K)
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "Turn the reference into a watercolor painting while keeping the composition" -i input.png -o edited.png

# Multi-image fusion (2K)
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "Place the person from image 1 into the scene from image 2, keeping the clothing color" -i person.png -i scene.png -o merged.png

# Three variants of the same theme (concurrent, max 5)
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "Chinese landscape poster" -n 3 -o landscape.png
```

Parameters:

- First positional argument: prompt (required).
- `-i / --image`: reference image path, repeatable. No `-i` = text-to-image; with `-i` = reference-image generation.
- `-m / --model`: `2k` (default, 2048×2048) or `4k` (4096×4096).
- `-o / --out`: output filename, default `output.png`.
- `-n / --count`: number of images, **default 1**, max 5. With `-n>1`, filenames get `-1`, `-2`, … suffixes.

## Image Count (Important)

- **Default is 1 image**: unless the user explicitly asks for multiple, keep `-n` at its default.
- **Only generate multiple when asked**: when the user says "give me 3 variants", use `-n`, up to 5 per call. For more, call the skill multiple times.
- Multiple images are concurrent variants of the same prompt (randomness makes each one different).

## Output Location (Important)

- When `-o` is a **bare filename** (such as `poster.png`), images go to the **`hunyuan-output/` folder in the project root**.
- When `-o` includes a directory (relative or absolute), save to that path.
- Do not write images to `/tmp`, a scratchpad, or other temporary directories; the user will not find them.

## When Done

The script prints the full path of every image. Report them exactly. If the script reports a content moderation failure (HTTP 400 `content_safety_violation`), relay the reason and do not retry the same prompt.
````

## scripts/hunyuan\_image.py

Create `hunyuan-image/scripts/hunyuan_image.py` with the following content (standard library only, no `pip install`):

```python theme={null}
#!/usr/bin/env python3
"""Generate images via APIYI Hunyuan Hy-Image 3.5 Preview (2K/4K). Standard library only."""
import argparse
import base64
import json
import os
import sys
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor

MODELS = {
    "2k": "hy-image-v3.5-preview-2k",
    "4k": "hy-image-v3.5-preview-4k",
}
MAX_COUNT = 5
ENDPOINT = "https://api.apiyi.com/v1/images/generations"


def load_api_key():
    """Prefer the environment; otherwise look for .env next to the script or its parent."""
    key = os.environ.get("APIYI_API_KEY")
    if key:
        return key
    here = os.path.dirname(os.path.abspath(__file__))
    for d in (here, os.path.dirname(here)):
        env_path = os.path.join(d, ".env")
        if os.path.exists(env_path):
            with open(env_path, encoding="utf-8") as f:
                for line in f:
                    line = line.strip()
                    if line.startswith("APIYI_API_KEY") and "=" in line:
                        return line.split("=", 1)[1].strip().strip('"').strip("'")
    return None


def project_root():
    """Walk up from the script location to the first .git or .claude directory."""
    d = os.path.dirname(os.path.abspath(__file__))
    while True:
        if os.path.isdir(os.path.join(d, ".git")) or os.path.isdir(os.path.join(d, ".claude")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            return os.getcwd()
        d = parent


def mime_of(path):
    ext = os.path.splitext(path)[1].lower()
    if ext in (".jpg", ".jpeg"):
        return "image/jpeg"
    if ext == ".webp":
        return "image/webp"
    return "image/png"


def to_data_uri(path):
    with open(path, "rb") as f:
        return f"data:{mime_of(path)};base64," + base64.b64encode(f.read()).decode()


def resolve_paths(out, count):
    if os.path.dirname(out):
        base_path = os.path.abspath(out)
    else:
        out_dir = os.path.join(project_root(), "hunyuan-output")
        os.makedirs(out_dir, exist_ok=True)
        base_path = os.path.join(out_dir, out)
    if count == 1:
        return [base_path]
    base, ext = os.path.splitext(base_path)
    return [f"{base}-{i}{ext}" for i in range(1, count + 1)]


def generate(api_key, model_id, prompt, image_paths):
    payload = {
        "model": model_id,
        "prompt": prompt,
        "response_format": "b64_json",
    }
    if image_paths:
        payload["images"] = [to_data_uri(p) for p in image_paths]

    req = urllib.request.Request(
        ENDPOINT,
        data=json.dumps(payload).encode(),
        method="POST",
        headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(req, timeout=360) as r:
            resp = json.loads(r.read())
    except urllib.error.HTTPError as e:
        body = e.read().decode(errors="replace")
        raise RuntimeError(f"HTTP {e.code}: {body[:800]}")
    except urllib.error.URLError as e:
        raise RuntimeError(f"network error: {e}")

    data = resp.get("data") or []
    if not data:
        raise RuntimeError(f"no image returned: {resp}")
    item = data[0]
    if item.get("b64_json"):
        return base64.b64decode(item["b64_json"])
    if item.get("url"):
        with urllib.request.urlopen(item["url"], timeout=360) as r:
            return r.read()
    raise RuntimeError(f"unexpected response: {resp}")


def _safe(fn, arg):
    try:
        return True, fn(arg)
    except Exception as e:  # noqa: BLE001 - one failed image must not stop the others
        return False, str(e)


def main():
    api_key = load_api_key()
    if not api_key:
        sys.exit("No API key found. Add APIYI_API_KEY=sk-xxx to .env in the skill directory.")

    parser = argparse.ArgumentParser(description="Hunyuan Hy-Image 3.5 image generation")
    parser.add_argument("prompt", help="Prompt / edit instruction")
    parser.add_argument("-i", "--image", action="append", default=[], help="Reference image path (repeatable)")
    parser.add_argument("-m", "--model", choices=sorted(MODELS), default="2k", help="2k or 4k; default 2k")
    parser.add_argument("-o", "--out", default="output.png", help="Output filename")
    parser.add_argument("-n", "--count", type=int, default=1, help=f"Number of images, default 1, max {MAX_COUNT} (concurrent)")
    args = parser.parse_args()

    count = max(1, min(args.count, MAX_COUNT))
    if args.count > MAX_COUNT:
        print(f"Note: at most {MAX_COUNT} images per call; using {MAX_COUNT}.", file=sys.stderr)

    paths = resolve_paths(args.out, count)
    model_id = MODELS[args.model]

    def task(path):
        data = generate(api_key, model_id, args.prompt, args.image)
        with open(path, "wb") as f:
            f.write(data)
        return os.path.abspath(path)

    failures = 0
    with ThreadPoolExecutor(max_workers=count) as pool:
        for path, result in zip(paths, pool.map(lambda p: _safe(task, p), paths)):
            ok, value = result
            if ok:
                print(f"Image saved to {value}")
            else:
                failures += 1
                print(f"Image {os.path.basename(path)} failed: {value}", file=sys.stderr)

    if failures == count:
        sys.exit("All images failed.")


if __name__ == "__main__":
    main()
```

> [!TIP]
>
> The default model is `hy-image-v3.5-preview-2k`. Add `-m 4k` for 4096×4096. Resolution cannot be changed with `--size`; both models have fixed output dimensions.

## Usage

### Natural language (implicit invocation)

Once installed, just talk to your agent:

| You say | Skill behavior |
| - | - |
| "Use Hunyuan to make a Chinese movie poster titled Between Mountains and Seas" | Runs the script without `-i`, returns one 2K PNG |
| "Make a 4K print-quality hero image" | Runs the script with `-m 4k`, returns 4096×4096 |
| "Turn ref.png into a watercolor painting" | Runs the script with `-i ref.png`, returns one PNG |
| "Combine these two images" | Runs the script with `-i a.png -i b.png` |
| "Give me three variants of this theme" | Runs the script with `-n 3`, returns three PNGs |

### Explicit invocation

* Agents with slash commands (such as Claude Code):

  ```text theme={null}
  /hunyuan-image A Chinese movie poster titled Between Mountains and Seas --model 2k
  ```

* Any agent / direct script call:

  ```text theme={null}
  python3 hunyuan-image/scripts/hunyuan_image.py "A Chinese movie poster titled Between Mountains and Seas" -o poster.png
  ```

## Where the Images Go

* When `-o` is a **bare filename** (such as `-o poster.png`), images go to the **`hunyuan-output/` folder in the project root** (created automatically).
* "Project root" is the first directory containing `.git` or `.claude` when walking up from the script location. The images always land inside the project, never in a temporary directory.
* The script prints the full absolute path of every image.
* Default is one image; `-n 3` generates three (max 5, automatically capped), with `-1`, `-2`, `-3` suffixes.

> [!NOTE]
>
> Hunyuan Hy-Image 3.5 has content safety controls. If the script reports `HTTP 400` (`content_safety_violation`), the prompt was blocked. Adjust the content; do not retry the same prompt.

## Related Docs

* [Hunyuan Hy-Image 3.5 Overview](https://docs.apiyi.com/en/api-capabilities/hunyuan-image/overview.md)
* [Text-to-Image API Reference](https://docs.apiyi.com/en/api-capabilities/hunyuan-image/text-to-image.md)
* [Reference-Image API Reference](https://docs.apiyi.com/en/api-capabilities/hunyuan-image/image-edit.md)
* [Hunyuan Hy-Image 3.5 FAQ](https://docs.apiyi.com/en/api-capabilities/hunyuan-image/faq.md)
* [Image API Best Practices](https://docs.apiyi.com/en/api-capabilities/image-api-best-practices.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.