> ## 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 エージェントスキル

> Tencent Hunyuan Hy-Image 3.5 Preview（hy-image-v3.5-preview-2k / -4k）を、Codex、Claude Code、Cursor、その他のコーディングエージェント向けのそのまま導入できるエージェントスキルとしてパッケージ化します。1つの prompt で2K/4K画像を生成したり、参照画像のスタイルを変更したりできます。

> [!NOTE]
>
> このページでは、**すぐに使えるエージェントスキル**を提供します。コーディングエージェントに組み込むだけで、自然言語または明示的なコマンドから APIYI の **Tencent Hunyuan Hy-Image 3.5 Preview**（`hy-image-v3.5-preview-2k` / `hy-image-v3.5-preview-4k`）を呼び出せます。ファイルは2つだけなので、コピーして使用できます。

> [!TIP]
>
> このスキルはデフォルトで `hy-image-v3.5-preview-2k`（2048×2048、画像1枚あたり \$0.022）を使用します。4096×4096 を使用するには `-m 4k` を追加してください。ローカルの参照画像は `-i` で渡せます。スクリプトが、`images` 配列で必要とされるデータ URI に変換します。API を直接統合する場合は、[テキストから画像への API](https://docs.apiyi.com/ja/api-capabilities/hunyuan-image/text-to-image.md) と [参照画像 API](https://docs.apiyi.com/ja/api-capabilities/hunyuan-image/image-edit.md) を参照してください。

## このスキルでできること

参照画像が提供されているかどうかに応じて動作を切り替える1つのスクリプトです：

> [card] テキストから画像生成
>
> プロンプトのみ → 中国語テキストを高精度に描画した2048×2048（2K）または4096×4096（4K）の画像です。

> [card] 参照画像による生成
>
> ローカル画像1枚 + 指示 → スタイル転送、構図の維持、または部分的な編集です。

> [card] 複数画像の融合
>
> 複数の画像 + 1つの指示 → 1つのシーン内で被写体を組み合わせます。「画像1 / 画像2」として参照してください。

## 使用できるエージェント

> [!NOTE]
>
> スキルは基本的にフォルダーです。エージェント向けの`SKILL.md`指示ファイルと、処理を実行するスクリプトが含まれています。**ローカルファイルの読み取りとシェルコマンドの実行が可能なコーディングエージェントであれば、どれでも使用できます** — Codex、Claude Code、Cursor などです。必要な条件は **Python 3** と`api.apiyi.com`へのネットワークアクセスだけです。

## 3ステップのセットアップ

### ① フォルダーを作成してファイルを追加する

次の2つのファイルを含むスキルフォルダーを作成します。

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

### ② キーを追加する

**APIYI API キー**（`api.apiyi.com` コンソールで作成したもの）を `hunyuan-image/.env` に書き込みます。

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

スクリプトは、この `.env` からキーを自動的に読み取ります。

> [!WARNING]
>
> `.env` にはシークレットキーが含まれています。このスキルをプロジェクトリポジトリで共有する場合は、**`.env` を `.gitignore` に追加し、絶対にコミットしないでください**。

### ③ エージェントに渡す

* **スキル検出機能を備えたエージェント**（Claude Code など）：`hunyuan-image/` フォルダー全体をスキルディレクトリに配置します。個人用の場合は `~/.claude/skills/`、プロジェクト用の場合は `.claude/skills/` です。
* **その他のエージェント**：各エージェントのスキルやプラグインの規約に従うか、フォルダー内の `SKILL.md` を読んでその内容に従うようエージェントに指示します。

続いて、[使い方](#usage)に進みます。

## SKILL.md

次の内容で`hunyuan-image/SKILL.md`を作成します。

````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

次の内容で`hunyuan-image/scripts/hunyuan_image.py`を作成します（標準ライブラリのみ、`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]
>
> デフォルトモデルは`hy-image-v3.5-preview-2k`です。4096×4096には`-m 4k`を追加します。`--size`では解像度を変更できません。どちらのモデルも出力サイズが固定されています。

## 使い方

### 自然言語（暗黙的な呼び出し）

インストール後は、エージェントに話しかけるだけで利用できます：

| 入力する内容 | スキルの動作 |
| - | - |
| 「Hunyuanで『山海のあいだ』というタイトルの中国映画のポスターを作って」 | `-i`なしでスクリプトを実行し、2K PNGを1枚返します |
| 「印刷品質の4Kヒーロー画像を作って」 | `-m 4k`を指定してスクリプトを実行し、4096×4096の画像を返します |
| 「ref.pngを水彩画に変えて」 | `-i ref.png`を指定してスクリプトを実行し、PNGを1枚返します |
| 「この2枚の画像を組み合わせて」 | `-i a.png -i b.png`を指定してスクリプトを実行します |
| 「このテーマで3つのバリエーションを作って」 | `-n 3`を指定してスクリプトを実行し、PNGを3枚返します |

### 明示的な呼び出し

* スラッシュコマンドに対応するエージェント（Claude Codeなど）：

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

* 任意のエージェント / スクリプトの直接呼び出し：

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

## 画像の保存先

* `-o` が**ファイル名のみ**（例：`-o poster.png`）の場合、画像は**プロジェクトルート内の `hunyuan-output/` フォルダー**に保存されます（自動作成されます）。
* 「プロジェクトルート」は、スクリプトの場所から上位にたどったときに、`.git` または `.claude` を含む最初のディレクトリです。画像は常にプロジェクト内に保存され、一時ディレクトリには保存されません。
* スクリプトは各画像の完全な絶対パスを出力します。
* デフォルトでは画像を1枚生成します。`-n 3` では3枚生成します（最大5枚で、自動的に上限が適用されます）。接尾辞は `-1`、`-2`、`-3` です。

> [!NOTE]
>
> Hunyuan Hy-Image 3.5 にはコンテンツの安全性を管理する機能があります。スクリプトが `HTTP 400`（`content_safety_violation`）を報告した場合、prompt がブロックされています。内容を調整し、同じ prompt で再試行しないでください。

## 関連ドキュメント

* [Hunyuan Hy-Image 3.5 の概要](https://docs.apiyi.com/ja/api-capabilities/hunyuan-image/overview.md)
* [テキストから画像を生成する API リファレンス](https://docs.apiyi.com/ja/api-capabilities/hunyuan-image/text-to-image.md)
* [参照画像 API リファレンス](https://docs.apiyi.com/ja/api-capabilities/hunyuan-image/image-edit.md)
* [Hunyuan Hy-Image 3.5 のよくある質問](https://docs.apiyi.com/ja/api-capabilities/hunyuan-image/faq.md)
* [画像 API のベストプラクティス](https://docs.apiyi.com/ja/api-capabilities/image-api-best-practices.md)


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