Skip to content

图片生成

如何使用 Trinity 生成图片

生图有两条 HTTP 路径:

路径说明文档
POST /v1/images/generations · /images/editsOpenAI Images 兼容形态创建图像(Images) · 编辑图像(Images)
POST /v1/chat/completions统一契约:modalities + image_config创建图像生成(chat)

下文以统一契约为主说明文生图与参考图生图。

生图为同步长耗时请求,须设置 stream: false 或省略 stream(不支持流式生图)。同步超时后可凭 trinity_task.task_id 或响应头 X-Xh-Image-Task-Id 查询,见 查询图像任务

勿与图片输入混淆

文生图 / 参考图生图用本页的 modalities + image_config看图理解messages[].content 里传 image_url Part,见 图片输入


模型发现

以你账号可见列表为准。勿依赖 output_modalities 等第三方专属查询参数。


API 用法

{TRINITY_BASE_URL}/chat/completions 发送 JSON 请求。modalities 取值取决于模型能力:

模型输出建议 modalities
同时输出文本与图片["image", "text"]
仅输出图片["image"]

生图请求 stream 须为 false 或省略(当前不支持流式生图)。

对调用方呈现为一次同步 HTTP 请求,通常需等待 10–300 秒。请设置足够的客户端读超时;网络超时后重试同一笔业务时,保持 X-Idempotency-Key 不变(见 API 概述)。


基础图片生成

python
import json, os, requests

url = f"{os.environ['TRINITY_BASE_URL']}/chat/completions"
headers = {
    "Authorization": f"Bearer {os.environ['TRINITY_API_KEY']}",
    "Content-Type": "application/json",
}
payload = {
    "model": "Hunyuan-3.0",
    "messages": [
        {"role": "user", "content": "生成一幅山峦日落景象,电影感光影"},
    ],
    "modalities": ["image", "text"],
}
r = requests.post(url, headers=headers, data=json.dumps(payload))
result = r.json()

# 生成的图片通常在 assistant 消息中(字段名以实现为准)
if result.get("choices"):
    message = result["choices"][0].get("message", {})
    images = message.get("images") or []
    for i, img in enumerate(images):
        image_url = img.get("image_url", {}).get("url") or img.get("image_url")
        print(f"Generated image {i + 1}: {str(image_url)[:80]}...")
typescript
const res = await fetch(`${process.env.TRINITY_BASE_URL}/chat/completions`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${process.env.TRINITY_API_KEY}`,
  },
  body: JSON.stringify({
    model: "Hunyuan-3.0",
    messages: [{ role: "user", content: "生成一幅山峦日落景象,电影感光影" }],
    modalities: ["image", "text"],
  }),
});
const result = await res.json();

if (result.choices?.[0]?.message) {
  const message = result.choices[0].message;
  const images = message.images ?? [];
  images.forEach((img, index) => {
    const url = img.image_url?.url ?? img.image_url;
    console.log(`Generated image ${index + 1}: ${String(url).slice(0, 80)}...`);
  });
}
bash
curl -sS "${TRINITY_BASE_URL}/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${TRINITY_API_KEY}" \
  -d '{
    "model": "Hunyuan-3.0",
    "messages": [{ "role": "user", "content": "生成一幅山峦日落景象,电影感光影" }],
    "modalities": ["image", "text"]
  }'

image_config 配置项

部分模型支持通过 image_config 控制画幅、分辨率与返回形式。完整字段表见 API · 高级参数 · 生图

宽高比 aspect_ratio

常用取值(是否生效以模型能力为准):

aspect_ratio说明
1:1方形(常见默认)
16:9 / 9:16横屏 / 竖屏
4:3 / 3:4传统横竖
3:2 / 2:3摄影比例
4:5 / 5:4社交竖横
21:9超宽

分辨率档位 image_sizecustom_size

image_size说明
1K标准档位(常见默认)
2K / 4K更高分辨率(按模型支持)

部分模型(如 Hunyuan 3.0、Qwen-0925、SI 系列)不支持 aspect_ratio,须用 custom_size(如 1024x1024)指定像素尺寸。更多码与示例见 图像生成 · 高级参数

返回形式

字段说明
output_format对外返回偏好:url / base64
output_image_format文件格式:png / jpeg

参考图 reference_images(图生图)

image_config.reference_images[] 中传入 URL 参考图(当前项内 type 固定为 url),可选 text 描述参考语义:

json
"reference_images": [
  {
    "type": "url",
    "url": "https://example.com/ref.png",
    "text": "保持主建筑轮廓,不改变几何结构"
  }
]

合规与人物策略(按模型)

字段说明
person_generationallow_adult / disallowed
input_compliance_check / output_compliance_check输入/输出合规检查,true / false

模型专属 model_specific_config

negative_promptenhance_promptseed 等供应商专有参数放在 model_specific_config 对象中,勿与 image_config 混用。全字段见 高级参数 · 生图

同时使用多个配置

json
{
  "model": "Hunyuan-3.0",
  "messages": [
    { "role": "user", "content": "赛博朋克风格未来城市夜景,霓虹灯与雨夜街道" }
  ],
  "modalities": ["image", "text"],
  "image_config": {
    "aspect_ratio": "16:9",
    "image_size": "1K",
    "output_format": "url",
    "output_image_format": "png"
  }
}
python
import json, os, requests

payload = {
    "model": "Hunyuan-3.0",
    "messages": [{"role": "user", "content": "赛博朋克风格未来城市夜景"}],
    "modalities": ["image", "text"],
    "image_config": {"aspect_ratio": "16:9", "image_size": "1K", "output_format": "url"},
}
r = requests.post(
    f"{os.environ['TRINITY_BASE_URL']}/chat/completions",
    headers={
        "Authorization": f"Bearer {os.environ['TRINITY_API_KEY']}",
        "Content-Type": "application/json",
    },
    data=json.dumps(payload),
)
print(r.json())
typescript
const res = await fetch(`${process.env.TRINITY_BASE_URL}/chat/completions`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${process.env.TRINITY_API_KEY}`,
  },
  body: JSON.stringify({
    model: "Hunyuan-3.0",
    messages: [{ role: "user", content: "赛博朋克风格未来城市夜景" }],
    modalities: ["image", "text"],
    image_config: { aspect_ratio: "16:9", image_size: "1K", output_format: "url" },
  }),
});
console.log(await res.json());
bash
curl -sS "${TRINITY_BASE_URL}/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${TRINITY_API_KEY}" \
  -d '{
    "model": "Hunyuan-3.0",
    "messages": [{ "role": "user", "content": "赛博朋克风格未来城市夜景" }],
    "modalities": ["image", "text"],
    "image_config": { "aspect_ratio": "16:9", "image_size": "1K", "output_format": "url" }
  }'

WARNING

trinity_async.* 生图当前不支持,传入会返回 invalid_request


流式生成

生图请求不支持 stream: true,须等待同步 JSON 响应。流式 SSE 仅适用于纯生文,见 流式输出(SSE)


响应格式

成功时,助手消息中通常包含生成的图片(结构对齐 OpenAI 兼容习惯,上游略有差异):

json
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "",
        "images": [
          {
            "type": "image_url",
            "image_url": { "url": "https://..." }
          }
        ]
      }
    }
  ],
  "usage": { "image_count": 1 },
  "trinity_task": {
    "task_id": "imgtsk_xxx",
    "mode": "sync",
    "status": "succeeded"
  }
}

图片字段说明

说明
格式常见为 url 公网地址,或 data:image/png;base64,... Data URL
类型多为 PNG / JPEG(见 output_image_format
多图部分模型单次可返回多张,以响应体为准
尺寸由模型与 image_config 决定

解析前请检查 choices[0].message.images;若为空,再查看 message.content 是否内嵌链接或 base64(以实现为准)。


同步超时与补偿查询

若创建请求返回 408 generation_timeout,表示同步等待超时,但上游任务可能仍在进行。请用响应中的 trinity_task.task_id(形如 imgtsk_xxx)轮询:

GET {TRINITY_BASE_URL}/image/tasks/{taskId}

成功终态时仍会返回图片 URL 并完成结算。详见 创建图像生成高级参数


模型兼容性

  1. model 须为模型广场中的生图模型 ID
  2. 正确设置 modalities:多数模型用 ["image", "text"]
  3. 勿对生图请求开启 stream: true

最佳实践

  • 提示词:描述主体、风格、光线、构图,避免含糊的一句词。
  • 模型选择:在模型广场确认该 ID 支持图像输出。
  • 参考图:图生图时使用 reference_images,并配合 text 说明保留/变更的部分。
  • 错误处理:先判断 HTTP 状态与 error 对象,再解析 images408 时用 trinity_task.task_id 补偿查询。
  • 幂等:重试同一笔生图时保持 X-Idempotency-Key 不变。
  • 存储url 形式注意链接有效期;base64 需自行解码落盘。

故障排除

响应里没有图片?

  • 确认 model 为生图模型,且 modalitiesimage
  • 确认未设置 stream: true
  • 确认 messages 中用户 prompt 明确要求生成图像。

模型不存在或不可用?

与看图混淆?

  • 理解已有图片内容 → 图片输入image_url Part)。
  • 生成新图片 → 本页(modalities + image_config)。

相关

© Trinity AI