> ## 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/张）；充值加赠后实际到手价约 **83–91 折**，详见 [充值活动说明](https://docs.apiyi.com/faq/recharge-promotions.md)。需要 4K 时加 `-m 4k`。参考图用 `-i` 传入本地文件，脚本会自动转成 `images` 数组所需的 data URI。纯 API 接入见 [文生图 API](https://docs.apiyi.com/api-capabilities/hunyuan-image/text-to-image.md) 与 [参考图生图 API](https://docs.apiyi.com/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/api-capabilities/hunyuan-image/overview.md)
* [文生图 API 参考](https://docs.apiyi.com/api-capabilities/hunyuan-image/text-to-image.md)
* [参考图生图 API 参考](https://docs.apiyi.com/api-capabilities/hunyuan-image/image-edit.md)
* [混元 Hy-Image 3.5 常见问题](https://docs.apiyi.com/api-capabilities/hunyuan-image/faq.md)
* [图片 API 调用须知与最佳实践](https://docs.apiyi.com/api-capabilities/image-api-best-practices.md)


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