HiAPI
博客

教程

imagen-4.0-ultra API:一个可用的文生图请求

2026年11月3日
imagen-4.0-ultra API:一个可用的文生图请求
模型
imagen-4

Imagen 4 Ultra 是 Google Imagen 4 系列中细节层级最高的版本,在 hiapi 上,它和其他所有图像模型一样,通过同一套统一的异步任务 API 执行文生图。本指南给出一个真正能跑通的请求——真实的 curl 调用、Python 轮询循环、服务器实际接受的参数,以及经过真实请求验证的错误情况。以下所有内容在发布前均已在生产端点运行验证;示例 taskId 和输出 URL 均来自那次运行。

你将构建的内容

一次调用即可把文本提示词变成成品图像:向 POST /v1/tasks 提交任务,轮询直到完成,然后从 output[0].url 读取图像 URL。你需要一个 hiapi API key——从你的仪表盘获取并导出:

export HIAPI_API_KEY="your-hiapi-key"

最小可运行示例(curl)

该模型接受 prompt 和可选的 aspect_ratio。创建任务:

curl -X POST "https://api.hiapi.ai/v1/tasks" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "imagen-4.0-ultra",
    "input": {
      "prompt": "Macro product photo of a matte ceramic coffee mug on a pale oak table, soft window light from the left, shallow depth of field, a few coffee beans in the foreground, no text, no logos",
      "aspect_ratio": "4:3"
    }
  }'

创建调用会立即返回一个任务 id——生成在后台继续进行:

{"code":200,"data":{"taskId":"tk-hiapi-01M5CVC8R62M0Z7CCM8WB38B61"},"message":"success"}

用返回的 id 轮询任务:

curl "https://api.hiapi.ai/v1/tasks/tk-hiapi-01M5CVC8R62M0Z7CCM8WB38B61" \
  -H "Authorization: Bearer $HIAPI_API_KEY"

当 status 为 success 时,图像位于 output[0].url:

{
  "code": 200,
  "data": {
    "taskId": "tk-hiapi-01M5CVC8R62M0Z7CCM8WB38B61",
    "model": "imagen-4.0-ultra",
    "status": "success",
    "storage": "temp",
    "created": 1792506471,
    "completed": 1792506479,
    "output": [
      {
        "artifactId": "279760",
        "type": "image",
        "url": "https://temp.hiapi.ai/7c6ttvrbpt/01M5CVC8R62M0Z7CCM8WB38B61-0.webp",
        "expireAt": 1793111279
      }
    ]
  },
  "message": "success"
}

那次运行大约在 8 秒内完成,并返回一张 WebP(不是 PNG/JPEG)。URL 位于临时存储上("storage": "temp"),expireAt 设置为 7 天后——请及时下载,不要热链接。

生产环境:带轮询循环的 Python

创建响应不包含图像——只有 taskId。真实的集成会先提交,然后轮询(或使用回调)。此脚本完成完整往返并立即下载结果,因为 URL 是临时的:

import os, time, requests

API = "https://api.hiapi.ai/v1/tasks"
HEADERS = {"Authorization": f"Bearer {os.environ['HIAPI_API_KEY']}"}

def generate(prompt, aspect_ratio="1:1", negative_prompt=None, seed=None):
    body = {"model": "imagen-4.0-ultra", "input": {"prompt": prompt, "aspect_ratio": aspect_ratio}}
    if negative_prompt:
        body["input"]["negative_prompt"] = negative_prompt
    if seed is not None:
        body["input"]["seed"] = str(seed)  # seed is a STRING, not a number

    r = requests.post(API, headers=HEADERS, json=body, timeout=60)
    r.raise_for_status()
    created = r.json()
    if created.get("code") != 200:
        raise RuntimeError(f"create rejected: {created}")
    task_id = created["data"]["taskId"]

    # Poll. Statuses other than success/fail (e.g. queued, running, archiving) mean "keep waiting".
    for _ in range(60):
        time.sleep(3)
        try:
            d = requests.get(f"{API}/{task_id}", headers=HEADERS, timeout=30).json()["data"]
        except requests.RequestException:
            continue  # tolerate a transient read; re-poll the same id
        status = d.get("status")
        if status == "success":
            return d["output"][0]["url"]
        if status in ("fail", "failed", "error"):
            raise RuntimeError(f"task failed: {d}")
    raise TimeoutError(f"task {task_id} did not finish in time")

url = generate(
    "A high-detail aerial landscape of terraced rice fields at golden hour, long shadows",
    aspect_ratio="16:9",
)
img = requests.get(url, timeout=60).content
open("out.webp", "wb").write(img)
print(f"saved {len(img)} bytes from {url}")

生产环境中重要的注意事项:

  • 轮询 vs 回调。 上面展示的是轮询。要避免轮询,可附加一个顶层 callback 对象({"url": "...", "when": "final"}),当任务达到终态时 hiapi 会向你发送 POST 请求。回调契约见 统一异步 API 文档。
  • 重新轮询已保存的 id,不要重新创建。 读取任务是幂等的;连接断开时应对 GET /v1/tasks/<id> 重试,绝不要再次 POST(那会再计费一张图像)。
  • 成功即下载。 output[0].url 是临时的(本次运行中 TTL 为 7 天)。抓取字节并推送到你自己的存储。

此模型实际接受的参数

imagen-4.0-ultra 仅支持文生图——不支持参考图(已在模型页面确认;本次运行仅测试了文生图)。输入 schema 是封闭的:未知字段会被拒绝,因此无法偷偷传入额外参数。

字段 类型 必填 说明
prompt string 是 1–5,000 个字符。空字符串会失败(minLength: got 0, want 1)。
aspect_ratio enum 否 1:1、16:9、9:16、3:4、4:3、auto 之一。默认为 1:1。
negative_prompt string 否 最多 5,000 个字符;描述要排除的内容。
seed string 否 最多 500 个字符。它是字符串——传数字会被拒绝。

一个请求恰好生成一张图像。

已验证的错误情况

这些都是在真实端点上产生的,因此你的错误处理可以依赖它们。被拒绝的请求返回 HTTP 400,采用扁平信封,且没有 taskId:

{"code":400,"data":null,"error_code":"INVALID_REQUEST","message":"invalid input: aspect_ratio: value must be one of '1:1', '16:9', '9:16', '3:4', '4:3', 'auto'"}

一些值得在代码中考虑的行为:

  • 校验器会一次报告所有字段错误,用 ; 连接。给 seed 传数字且 aspect_ratio 非法,你会在一条消息中同时得到两者:invalid input: seed: got number, want string; aspect_ratio: value must be one of ...。不要假设每个响应只有一个错误。
  • 未知字段会导致整个请求失败,报错为 <root>: additional properties '<name>' not allowed。schema 是封闭的。
  • 空提示词会失败,报错为 prompt: minLength: got 0, want 1。
  • 成功的 create 是 code: 200 且带 data.taskId;被拒绝则是 data: null。在尝试读取任务 id 之前先据此分支。

应该调用哪个 Imagen 4 层级?

imagen-4.0-ultra 是三个层级中的最高档;按任务选择,而不是按习惯(宽高比、负向提示词和种子不影响你支付的费用——见定价):

  • Imagen 4 Fast —— 最便宜,适合草稿扫图和批量探索方向。
  • Imagen 4 —— 日常中间档,适合产品、生活方式和内容图像。
  • Imagen 4 Ultra(本模型)—— 三者中最贵,定位于成品级细节:宏纹理、材质渲染和文字排版,适用于最终图像必须经得起推敲的场景。当输出可直接交付时选 Ultra;迭代时用 Fast 或基础档。

相关链接

常见问题

一个请求返回多少张图像? 一张。在已验证的运行中,output 数组只包含一个条目。

输出是什么格式? WebP。返回的文件是 temp.hiapi.ai 上的 .webp。

输出 URL 有效期多久? 约 7 天——expireAt 设置为完成后 7 天。将其视为临时资源并立即下载。

可以发送参考图吗? 不可以。imagen-4.0-ultra 仅支持文生图;模型页面将参考图列为不支持。

为什么我的请求报错 "additional properties not allowed"? 输入 schema 是封闭的。只发送 prompt、aspect_ratio、negative_prompt 和 seed;任何其他键都会导致整个请求失败。

负向提示词、种子或宽高比会改变价格吗? 不会。按图像计费;这些参数不影响成本。

立即开始构建持久 AI 产物

获取 API 密钥,通过一个基于任务(task)的 API 调用图像、视频和音频模型。

阅读 API 文档