> ## 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 프리뷰(hy-image-v3.5-preview-2k / -4k)를 Codex, Claude Code, Cursor 및 기타 코딩 에이전트에서 바로 사용할 수 있는 에이전트 스킬로 패키징합니다. 하나의 prompt로 2K/4K 이미지를 생성하거나 참조 이미지를 재스타일링합니다.

> [!NOTE]
>
> 이 페이지에서는 **바로 사용할 수 있는 에이전트 스킬**을 제공합니다. 코딩 에이전트에 추가하고 자연어나 명시적 명령으로 APIYI의 **Tencent Hunyuan Hy-Image 3.5 프리뷰**(`hy-image-v3.5-preview-2k` / `hy-image-v3.5-preview-4k`)를 호출할 수 있습니다. 파일은 단 두 개뿐이므로 복사하여 사용하면 됩니다.

> [!TIP]
>
> 이 스킬은 기본적으로 `hy-image-v3.5-preview-2k`(2048×2048, 이미지당 \$0.022)으로 설정되어 있습니다. 4096×4096을 사용하려면 `-m 4k`을 추가합니다. `-i`을 사용하여 로컬 참조 이미지를 전달하면 스크립트가 이를 `images` 배열에서 요구하는 데이터 URI로 변환합니다. 직접 API를 통합하려면 [텍스트-이미지 API](https://docs.apiyi.com/ko/api-capabilities/hunyuan-image/text-to-image.md) 및 [참조 이미지 API](https://docs.apiyi.com/ko/api-capabilities/hunyuan-image/image-edit.md)를 참조하십시오.

## 이 스킬의 기능

참조 이미지가 제공되었는지에 따라 동작을 전환하는 하나의 스크립트입니다:

> [card] 텍스트-이미지 변환
>
> 프롬프트만 입력 → 중국어 텍스트 렌더링이 뛰어난 2048×2048(2K) 또는 4096×4096(4K) 이미지가 생성됩니다.

> [card] 참조 이미지 생성
>
> 로컬 이미지 하나 + 지침 → 스타일 전환, 구도 보존 또는 로컬 편집이 가능합니다.

> [card] 다중 이미지 융합
>
> 여러 이미지 + 하나의 지침 → 단일 장면에 피사체를 결합합니다. 이미지는 “이미지 1 / 이미지 2”로 지칭합니다.

## 사용할 수 있는 에이전트

> [!NOTE]
>
> Skill은 본질적으로 폴더입니다. 에이전트를 위한 `SKILL.md` 지침 파일과 작업을 수행하는 스크립트로 구성됩니다. **로컬 파일을 읽고 셸 명령을 실행할 수 있는 모든 코딩 에이전트가 사용할 수 있습니다** — Codex, Claude Code, Cursor 및 기타 에이전트가 해당됩니다. 필요한 조건은 **Python 3**와 `api.apiyi.com`에 대한 네트워크 액세스뿐입니다.

## 3단계 설정

### ① 폴더를 생성하고 파일 추가

다음 두 파일이 포함된 스킬 폴더를 생성합니다:

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

### ② 키 추가

`api.apiyi.com` 콘솔에서 생성한 **APIYI API 키**를 `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
# 텍스트-이미지(기본 2K, 2048×2048)
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "산과 바다 사이(Between Mountains and Seas)라는 제목의 중국 영화 포스터, 짙은 파란색 밤하늘과 황금빛 산" -o poster.png

# 4K 텍스트-이미지(4096×4096)
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "인쇄 품질의 제품 대표 이미지, 금속 질감, 스튜디오 조명" -m 4k -o hero-4k.png

# 참조 이미지 생성(2K)
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "구도는 유지하면서 참조 이미지를 수채화 그림으로 변환" -i input.png -o edited.png

# 다중 이미지 융합(2K)
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "의상 색상을 유지하면서 이미지 1의 인물을 이미지 2의 장면에 배치" -i person.png -i scene.png -o merged.png

# 동일한 테마의 변형 3개(동시 실행, 최대 5개)
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "중국 풍경 포스터" -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 한 개를 반환합니다 |
| "4K 인쇄 품질의 히어로 이미지를 만들어 주세요" | `-m 4k`을 사용하여 스크립트를 실행하고 4096×4096 이미지를 반환합니다 |
| "ref.png를 수채화로 바꿔 주세요" | `-i ref.png`를 사용하여 스크립트를 실행하고 PNG 한 개를 반환합니다 |
| "이 두 이미지를 합쳐 주세요" | `-i a.png -i b.png`을 사용하여 스크립트를 실행합니다 |
| "이 테마의 변형 세 가지를 만들어 주세요" | `-n 3`를 사용하여 스크립트를 실행하고 PNG 세 개를 반환합니다 |

### 명시적 호출

* 슬래시 명령을 지원하는 에이전트(예: 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/ko/api-capabilities/hunyuan-image/overview.md)
* [텍스트-이미지 API 레퍼런스](https://docs.apiyi.com/ko/api-capabilities/hunyuan-image/text-to-image.md)
* [참조 이미지 API 레퍼런스](https://docs.apiyi.com/ko/api-capabilities/hunyuan-image/image-edit.md)
* [Hunyuan Hy-Image 3.5 FAQ](https://docs.apiyi.com/ko/api-capabilities/hunyuan-image/faq.md)
* [이미지 API 모범 사례](https://docs.apiyi.com/ko/api-capabilities/image-api-best-practices.md)


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