> ## 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.

# 混元 Hy-Image 3.5 Agent 技能

> 把騰訊混元 Hy-Image 3.5 Preview（hy-image-v3.5-preview-2k / -4k）封裝成開箱即用的 Agent Skill，丟進 Codex、Claude Code、Cursor 等編碼 Agent，一句話即可完成 2K/4K 文生圖與參考圖生圖。

> [!NOTE]
>
> 本頁提供一個**開箱即用的 Agent 技能（Skill）**：把它放進你正在用的編碼 Agent，就能用自然語言（或顯式命令）直接呼叫 API易 平臺的 **騰訊混元 Hy-Image 3.5 Preview**（`hy-image-v3.5-preview-2k` / `hy-image-v3.5-preview-4k`）完成文生圖與參考圖生圖。整套東西就兩個檔案，複製即用。

> [!TIP]
>
> 技能預設用 `hy-image-v3.5-preview-2k`（2048×2048，\$0.022/張）；需要 4K 時加 `-m 4k`。參考圖用 `-i` 傳入本地檔案，指令碼會自動轉成 `images` 陣列所需的 data URI。純 API 接入見 [文生圖 API](https://docs.apiyi.com/zh-Hant/api-capabilities/hunyuan-image/text-to-image.md) 與 [參考圖生圖 API](https://docs.apiyi.com/zh-Hant/api-capabilities/hunyuan-image/image-edit.md)。

## 這個技能能做什麼

一個指令碼，根據**是否傳入參考圖**自動切換：

> [card] 文生圖
>
> 只給提示詞 → 生成 2048×2048（2K）或 4096×4096（4K）圖片，支援中文文字。

> [card] 參考圖生圖
>
> 傳 1 張本地圖 + 指令 → 風格遷移、構圖保留、局部重繪等。

> [card] 多圖融合
>
> 傳多張圖 + 一條指令 → 把多個主體放進同一張畫面，prompt 裡用「圖1 / 圖2」指代。

## 能用在哪些 Agent

> [!NOTE]
>
> 一個 Skill 本質上就是一個資料夾：一份寫給 Agent 看的說明（`SKILL.md`）+ 一個幹活的指令碼。所以**凡是能讀取本地檔案、執行命令列的編碼 Agent 都能用**——Codex、Claude Code、Cursor 等。唯一要求：跑 Agent 的機器裝了 **Python 3** 並且能聯網（指令碼直連 `api.apiyi.com`）。

## 三步裝好

### ① 建目錄、貼檔案

新建一個技能資料夾，放入下面兩個檔案：

```
hunyuan-image/
├── SKILL.md
├── scripts/
│   └── hunyuan_image.py
└── .env          # 第②步建立，放你的 Key
```

### ② 同目錄寫 Key

在 `hunyuan-image/.env` 裡寫上你的 **API易 API Key**（在 `api.apiyi.com` 控制台建立）：

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

指令碼會自動從這個 `.env` 讀取 Key，無需額外配置。

> [!WARNING]
>
> `.env` 裡是你的金鑰。如果這個技能要隨專案倉庫共享，**務必把 `.env` 加進 `.gitignore`，不要提交到 git**。

### ③ 交給 Agent

* **支援技能自動發現的 Agent**（如 Claude Code）：把整個 `hunyuan-image/` 目錄放進它的技能目錄——個人級 `~/.claude/skills/`，或專案級 `.claude/skills/`。
* **其他 Agent**：按它各自的技能/外掛約定放置；或者最簡單——直接讓 Agent「讀一下這個資料夾裡的 SKILL.md，並照著執行」。

裝好後跳到 [怎麼用](#怎麼用)。

## 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 *)
---

# 混元 Hy-Image 3.5 出圖技能

通過 API易 平臺呼叫騰訊混元 Hy-Image 3.5 Preview（`hy-image-v3.5-preview-2k` / `hy-image-v3.5-preview-4k`）生成或編輯圖片。預設 2048×2048，支援 4096×4096；中文文字渲染準確。

## Key 配置

指令碼會自動讀取技能目錄下 `.env` 檔案裡的 `APIYI_API_KEY`（也支援同名環境變數）。
若指令碼報「未找到 Key」，提示使用者在 `.env` 裡寫一行 `APIYI_API_KEY=sk-xxx`。

## 用法

呼叫同目錄下的指令碼，第一個引數是提示詞；參考圖用 `-i` 傳入一張或多張本地圖片路徑：

```bash
# 文生圖（預設 2K，2048×2048）
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "一張中文電影海報，主標題「山海之間」，深藍夜色與金色山巒" -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的場景，保留圖1的服裝顏色" -i person.png -i scene.png -o merged.png

# 一次出 3 張同主題變體（併發生成，最多 5 張）
python3 ${CLAUDE_SKILL_DIR}/scripts/hunyuan_image.py "國風山水海報" -n 3 -o shanshui.png
```

引數說明：

- 第 1 個位置引數：提示詞（必填）。
- `-i / --image`：參考圖路徑，可重複多次；不傳 = 文生圖，傳 = 參考圖生圖。
- `-m / --model`：`2k`（預設，2048×2048）或 `4k`（4096×4096）。
- `-o / --out`：輸出檔名，預設 `output.png`。
- `-n / --count`：一次出幾張，**預設 1**，最多 5；`-n>1` 時檔名自動加 `-1` `-2`… 字尾。

## 出圖張數（重要）

- **預設只出 1 張**：使用者沒有明確要求多張時，`-n` 保持預設。
- **指定多張才出多張**：使用者說「出 3 張 / 來幾個版本」時才用 `-n`，且一次不超過 5 張。需要更多時分多次呼叫。
- 多張是同一提示詞的併發變體（模型有隨機性，結果各不相同）。

## 輸出位置（重要）

- `-o` 傳**純檔名**（如 `poster.png`）時，圖片統一儲存到**專案根目錄下的 `hunyuan-output/` 資料夾**。
- `-o` 傳**帶目錄的路徑**（相對或絕對）時，按給定路徑儲存。
- 不要把圖片寫到 `/tmp`、scratchpad 等臨時目錄，使用者會找不到。

## 完成後

指令碼會為每張圖列印一行完整路徑，把它們如實回報給使用者。若指令碼報告內容稽核失敗（HTTP 400 `content_safety_violation`），把原因如實轉達，不要重試同一提示詞。
````

## scripts/hunyuan\_image.py

新建 `hunyuan-image/scripts/hunyuan_image.py`，完整內容如下（純 Python 標準庫，無需 `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("未找到 API Key：請在技能目錄的 .env 寫一行 APIYI_API_KEY=sk-xxx")

    parser = argparse.ArgumentParser(description="混元 Hy-Image 3.5 出圖")
    parser.add_argument("prompt", help="提示詞 / 編輯指令")
    parser.add_argument("-i", "--image", action="append", default=[], help="參考圖路徑（可重複）")
    parser.add_argument("-m", "--model", choices=sorted(MODELS), default="2k", help="2k 或 4k，預設 2k")
    parser.add_argument("-o", "--out", default="output.png", help="輸出檔名")
    parser.add_argument("-n", "--count", type=int, default=1, help=f"一次出幾張，預設 1，最多 {MAX_COUNT}（併發生成）")
    args = parser.parse_args()

    count = max(1, min(args.count, MAX_COUNT))
    if args.count > MAX_COUNT:
        print(f"提示：一次最多 {MAX_COUNT} 張，已限制為 {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"圖片已儲存至 {value}")
            else:
                failures += 1
                print(f"第 {os.path.basename(path)} 張生成失敗：{value}", file=sys.stderr)

    if failures == count:
        sys.exit("全部生成失敗。")


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

> [!TIP]
>
> 模型名預設 `hy-image-v3.5-preview-2k`。需要 4K 時加 `-m 4k`；不支援通過 `--size` 切換解析度（兩個型號的輸出尺寸都是固定的）。

## 怎麼用

### 自然語言（隱式觸發）

裝好後直接對 Agent 說話即可：

| 你說 | 技能行為 |
| - | - |
| "用混元畫一張中文電影海報，主標題山海之間" | 調指令碼（無 `-i`），預設 2K 出 1 張 png |
| "來一張 4K 的印刷級主視覺" | 調指令碼 `-m 4k`，出 4096×4096 png |
| "把 ref.png 變成水彩畫風格" | 調指令碼 `-i ref.png`，出 1 張 png |
| "把這兩張圖合成一張" | 調指令碼 `-i a.png -i b.png`，多圖參考 |
| "同一主題來 3 個版本" | 調指令碼 `-n 3`，併發出 3 張 png |

### 顯性呼叫（更可控）

* 支援斜槓命令的 Agent（如 Claude Code）：

  ```text theme={null}
  /hunyuan-image 一張中文電影海報，主標題「山海之間」 --model 2k
  ```

* 任意 Agent / 直接命令它跑指令碼：

  ```text theme={null}
  python3 hunyuan-image/scripts/hunyuan_image.py "一張中文電影海報，主標題「山海之間」" -o poster.png
  ```

## 生成的圖片在哪裡

* `-o` 只傳**檔名**（如 `-o poster.png`）時，圖片統一存到**專案根目錄下的 `hunyuan-output/` 資料夾**（指令碼自動建立）。
* 「專案根目錄」= 指令碼從自身位置向上找到的第一個含 `.git` 或 `.claude` 的目錄——不管 Agent 在哪個目錄執行，圖都落在專案裡，不會跑進臨時目錄。
* 指令碼會為每張圖列印一行完整絕對路徑，例如 `圖片已儲存至 /Users/you/project/hunyuan-output/poster.png`。
* 預設只出 1 張；`-n 3` 一次出 3 張（最多 5，超過自動截到 5），檔名自動加 `-1`、`-2`、`-3` 字尾。

> [!NOTE]
>
> 混元 Hy-Image 3.5 有內容安全管控。若指令碼提示 `HTTP 400`（`content_safety_violation`），說明提示詞被稽核攔截；請調整內容，不要對同一違規提示詞反覆重試。

## 相關文件

* [混元 Hy-Image 3.5 概覽](https://docs.apiyi.com/zh-Hant/api-capabilities/hunyuan-image/overview.md)
* [文生圖 API 參考](https://docs.apiyi.com/zh-Hant/api-capabilities/hunyuan-image/text-to-image.md)
* [參考圖生圖 API 參考](https://docs.apiyi.com/zh-Hant/api-capabilities/hunyuan-image/image-edit.md)
* [混元 Hy-Image 3.5 常見問題](https://docs.apiyi.com/zh-Hant/api-capabilities/hunyuan-image/faq.md)
* [圖片 API 呼叫須知與最佳實踐](https://docs.apiyi.com/zh-Hant/api-capabilities/image-api-best-practices.md)


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