图像

生成图片

根据提示词生成图片

POST
/v1/images/generations

概述

通过 GET /v1/models?recommended_for=image 查看当前图片模型,并在请求中明确填写 model。

每个模型接受的操作和字段各不相同。GET /v1/models/{model}(获取模型)在 tokenlab.request_format_summary.request_endpoint_by_operation 中给出各操作对应的端点,在 tokenlab.request_format_details.operation_constraints 中给出各操作接受的字段、取值和限制。模型未列出的字段可能返回 400 unsupported_parameter。把操作发到错误的端点会返回 400 unsupported_endpoint。

图片任务与结果:

  • 在支持的参数中列出 async 的模型可以先创建任务:发送 async: true,再轮询 GET /v1/tasks/{id}。
  • 图片链接保存 30 天,见数据保留。
  • 发送 Idempotency-Key 请求头,可在超时后安全重试创建请求,见用幂等键安全重试。

gpt-image-2 是按 token 计价的 GPT Image 模型。TokenLab 按 OpenAI 官方的用量拆分计费,包括文本输入、图片输入、已报告的缓存输入和图片输出 tokens;它不是固定每张收费的模型。

对于 gpt-image-2 图片生成,TokenLab 支持的公开参数有 prompt、n、size、quality、response_format、async、background、output_format、output_compression 或 compression、moderation 和 user。background 可以是 auto 或 opaque,不支持 transparent。省略 size 或 quality 时,TokenLab 使用 auto;自定义 size 必须符合下文所述的灵活 WIDTHxHEIGHT 格式。

input_fidelity 不属于当前 TokenLab 对 gpt-image-2 支持的字段;请省略该字段,否则请求会返回 400 unsupported_parameter。

SVG 与 GIF 输出

gpt-image-2.6-flare 和 gpt-image-2.6-sunburst 可以返回 SVG 或 GIF 动图,而不是普通位图。其他模型不接受这两种格式。

  • SVG:发送 output_format: "svg" 和 svg: {"model": "..."}。图像模型先画一张参考图,再由作者模型据此写出 SVG。svg.model 必填,可用值见模型详情 parameter_options 里的 svg.model。也可以发送 svg.reasoning.effort。SVG 只能用于本接口,n 必须为 1,不能和 partial_images、output_compression 同用。
  • GIF:发送 output_format: "gif"。frame_count(2 到 16,默认 9)设定帧数,frame_duration_ms(20 到 2000,默认 200)设定每帧时长。size 是单帧尺寸。GIF 不能和 partial_images、output_compression 同用。

结果和其他图片一样在 data[].b64_json 或 data[].url 中。SVG 按 UTF-8 XML 文本解码后存为 .svg;GIF 存为 .gif。

计费:图像 token 按模型的 token 价格计费,GIF 的各帧都计入图像输出 token。SVG 请求还会按模型页上的 SVG 作者模型价格,对响应 svg_usage 里报告的作者模型 token 计费。

模型行为说明

Google Gemini 图片系列模型并不共用同一套选择器规则:

  • gemini-3.1-flash-image、gemini-nano-banana-2.1、gemini-3-pro-image、nano-banana-2.1 和 nano-banana-pro 在其公开的文生图、图生图和图片编辑操作中支持 aspect_ratio 和 resolution(1k、2k、4k)。
  • nano-banana-2 在文生图和图生图中均支持 aspect_ratio 和 resolution(1k、2k、4k)。
  • gemini-3.1-flash-lite-image 和 nano-banana-2-lite 支持文生图、图生图和图片编辑,分辨率仅为 1k。
  • nano-banana 支持 aspect_ratio,但不提供公开的 resolution 选择。
  • gemini-3.1-flash-image、gemini-nano-banana-2.1、gemini-3.1-flash-lite-image 或 gemini-3-pro-image 的图生图请求使用本端点,并发送 operation: "image-to-image" 和参考图。这些模型的图片编辑请求发送到 /v1/images/edits。
  • Nano Banana 参考图请求请在本端点(/v1/images/generations)使用 nano-banana-2、nano-banana-2.1、nano-banana-2-lite 或 nano-banana-pro,并发送 operation: "image-to-image" 与 image_urls。nano-banana-2、nano-banana-2.1、nano-banana-2-lite 和 nano-banana-pro 的图片编辑请求同样使用本端点,并发送 operation: "image-edit"。不要把 Nano Banana 参考图请求发送到 /v1/images/edits。
  • 本端点上的参考图可以通过 JSON image_url / image_urls 传入,也可以通过 multipart image 直接上传。/v1/images/generations 不接受 images[] 和 file_id;只有为文档中声明支持 images[].file_id 的 /v1/images/edits 模型,才需要创建 /v1/files 引用。

对于 Google 图片系列,优先发送 aspect_ratio;只有模型明确支持时才发送 resolution。

xAI Grok Imagine 图片模型(grok-imagine-image 和 grok-imagine-image-2.0)支持 aspect_ratio 和 resolution(1k、2k)。文生图使用本端点;图生图和图片编辑请求使用 /v1/images/edits。

hy-image-v3.5-preview 在本端点根据文本每次生成一张 1024x1024 图片,只支持 response_format: "url";参考图编辑使用 /v1/images/edits。

请求体

同步请求超时: 部分图片请求会等待生成完成后直接返回最终图片。高分辨率或高质量请求可能需要接近一分钟甚至更久,请把 HTTP 客户端超时设为至少 120s。如果创建响应包含 status: "pending"、task_id 或 poll_url,请改为调用 GET /v1/tasks/{task_id} 查询。

modelstring必填

要使用的模型(例如 gpt-image-2、flux-pro-1.1 或 nano-banana-pro)。使用 GET /v1/models?recommended_for=image 获取当前推荐列表。

promptstring必填

所需图片的文本描述,最多 32,000 个字符。模型详情列出 prompt 的模型都必须提供。

operationstring

text-to-image、image-to-image 或 image-edit。省略时,请求带参考图则为 image-to-image,否则为 text-to-image。编辑操作在本端点的模型(如 nano-banana-pro)请设置 image-edit。text-to-image 带参考图会返回 400 invalid_parameter。

image_urlstring

用于图生图的公开图片 URL。Nano Banana 参考图请求请设置 operation 为 image-to-image;nano-banana-pro 可以发送 resolution。

image_urlsstring[]

公开参考图 URL 数组,最多 16 个。JSON 请求中需要一张或多张参考图时使用此字段。本端点不支持 file_id 和 images[]。

reference_image_urlsstring[]

额外的参考图 URL,最多 16 个。模型区分主输入图与其他参考图时使用。

imagefile

用于图生图的 multipart 参考图文件。源图是私有或需要请求头鉴权时使用直接上传。它不同于 /v1/files 的 file_id,本端点不接受 file_id。

ninteger默认值: 1

要生成的图片数量(1-10,取决于模型)。

sizestring

图片尺寸。用于 OpenAI 风格的图片家族,以及接受精确像素尺寸的其他模型。

对于 gpt-image-2,size 接受 auto 或 WIDTHxHEIGHT。自定义宽高必须都是 16 的倍数,最长边不超过 3840px,长边/短边比例不超过 3:1,总像素必须在 655,360 到 8,294,400 之间。aspect_ratio 和 resolution 目前不属于 TokenLab 对 gpt-image-2 的模型详情。

对于有分辨率档位的 Google 图片模型(gemini-3.1-flash-image、gemini-nano-banana-2.1、gemini-3-pro-image、gemini-3.1-flash-lite-image、nano-banana-2、nano-banana-2.1 和 nano-banana-pro),size 接受该模型尺寸表中的输出尺寸,例如 1376x768(1K 的 16:9),或分辨率档位 1K、2K、4K。TokenLab 会把档位作为 resolution 发送,因此请求和价格与直接发送 resolution 相同。模型不支持的档位(例如 gemini-3.1-flash-lite-image 的 2K),或与 resolution 不一致的档位,会返回 400,错误码为 invalid_image_size_contract,并附带该模型的 allowed_resolutions。这些模型推荐使用 aspect_ratio 加 resolution。

aspect_ratiostring

图片宽高比,取值由模型决定。

Google 图片家族常见值包括 1:1、16:9、9:16、3:2、2:3。

resolutionstring

输出分辨率取决于模型。gemini-3.1-flash-image、gemini-nano-banana-2.1、gemini-3-pro-image、nano-banana-2、nano-banana-2.1 和 nano-banana-pro 支持 1k、2k、4k;Grok Imagine 图片模型支持 1k、2k。只有所选模型和操作明确支持时才发送此字段。

qualitystring

图片质量。gpt-image-2 等 GPT Image 模型使用 auto、low、medium 或 high。其他模型可能使用不同的取值;发送非默认值前请先查看模型详情。

output_formatstring

图片文件格式:png、jpeg 或 webp。gpt-image-2.6-flare 和 gpt-image-2.6-sunburst 还接受 svg 和 gif,见 SVG 与 GIF 输出。

svgobject

SVG 设置,只能和 output_format: "svg" 一起使用。model(必填)选择写 SVG 的作者模型;reasoning.effort 可选,设定它的推理强度。

frame_countinteger默认值: 9

GIF 帧数,2 到 16。只能和 output_format: "gif" 一起使用。

frame_duration_msinteger默认值: 200

GIF 每帧时长(毫秒),20 到 2000。只能和 output_format: "gif" 一起使用。

response_formatstring

图片的返回方式:url 或 b64_json。

  • 不传:如果模型返回图片字节,每张图片在 data[].b64_json 中返回;TokenLab 保存成功时也在 data[].url 中返回。如果模型返回链接,每张图片在 data[].url 中返回。
  • url:每张图片只在 data[].url 中返回。
  • b64_json:每张图片只在 data[].b64_json 中以 Base64 数据返回。

链接是 TokenLab 媒体结果 URL,有效期 30 天。参见数据保留。

asyncboolean默认值: false

设置为 true 时先创建任务。只有在支持的参数中列出 async 的模型才接受,例如 gpt-image-2、flux-pro-1.1、nano-banana-pro 和 seedream-5.0-lite;其他模型会返回 400 unsupported_async_mode。完成后的异步图片任务无论请求的 response_format 是什么,都只返回 URL;如果需要 b64_json,请使用同步请求。

stylestring

可选风格选择器。只有所选模型明确文档化支持时才发送;除非模型元数据另有说明,否则 gpt-image-2 请省略该字段。

userstring

终端用户的唯一标识符。

部分模型还接受 negative_prompt、seed、width、height、steps、guidance_scale 或 mask_url 等字段。只有模型详情列出时才发送。不支持 stream: true,会返回 400 unsupported_parameter。

响应

内联响应

createdinteger

创建时的 Unix 时间戳。

dataarray

生成的图像数组。

每个对象包含:

  • url (string):图片的 TokenLab 媒体结果 URL,有效期 30 天。response_format 为 b64_json 时不返回。不传 response_format 时,如果 TokenLab 未能保存图片,则不返回。
  • b64_json (string):Base64 图片数据。response_format 为 b64_json 时返回;不传 response_format 且模型返回图片字节时也返回。
  • revised_prompt (string): 所选模型返回的可选提示词改写结果
usageobject

按 token 计价的模型(如 gpt-image-2)在可用时返回的 token 数量(input_tokens、output_tokens、total_tokens 及其明细)。

svg_usageobject

SVG 作者模型的 token 数量(model、input_tokens、output_tokens、reasoning_tokens、total_tokens)。只在 SVG 输出时返回。这些 token 不在 usage 里,按 SVG 作者模型价格计费。

异步任务响应

在支持的模型上设置 async: true,会创建任务,而不是在创建请求中等待最终图片。响应包含 status: "pending"、task_id 和 poll_url。轮询 /v1/tasks/{task_id},直到任务状态变为 completed 或 failed。

异步图片任务最终只返回图片 URL。如果你需要原始 b64_json 图片数据,请使用同步请求。

任务创建时可能会先预留预计费用。任务完成后按实际用量结算;失败或超时的任务会释放预留费用或退回费用。

createdinteger

创建时的 Unix 时间戳。

task_idstring

用于查询状态的任务 ID。

statusstring

初始状态:pending。

poll_urlstring

状态查询地址,例如 /v1/tasks/{id}。

dataarray

任务处于 pending 状态时为空。图片任务完成后,生成图片的 URL 会出现在 data[].url 中。

收到 status: "pending" 后,调用 GET /v1/tasks/{task_id} 获取结果。

请求

cURL
curl -X POST "https://api.tokenlab.sh/v1/images/generations" \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-pro-image",
    "prompt": "A cinematic portrait of a white cat sitting on a rainy windowsill",
    "aspect_ratio": "16:9",
    "resolution": "2k"
  }'
Python
from openai import OpenAI

client = OpenAI(
    api_key="sk-your-api-key",
    base_url="https://api.tokenlab.sh/v1"
)

response = client.images.generate(
    model="gemini-3-pro-image",
    prompt="A cinematic portrait of a white cat sitting on a rainy windowsill",
    extra_body={"aspect_ratio": "16:9", "resolution": "2k"}
)

print(response.data[0].url)
JavaScript
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'sk-your-api-key',
  baseURL: 'https://api.tokenlab.sh/v1'
});

const response = await client.images.generate({
  model: 'gemini-3-pro-image',
  prompt: 'A cinematic portrait of a white cat sitting on a rainy windowsill',
  aspect_ratio: '16:9',
  resolution: '2k'
});

console.log(response.data[0].url);
PHP
<?php
$ch = curl_init('https://api.tokenlab.sh/v1/images/generations');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer sk-your-api-key'
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'model' => 'gemini-3-pro-image',
        'prompt' => 'A cinematic portrait of a white cat sitting on a rainy windowsill',
        'aspect_ratio' => '16:9',
        'resolution' => '2k'
    ])
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
echo $data['data'][0]['url'];

仅支持比例的图片系列示例:使用 nano-banana 时,发送 aspect_ratio,不要发送 resolution:

{
  "model": "nano-banana",
  "prompt": "A clean editorial product shot of a citrus soda can",
  "aspect_ratio": "16:9"
}

Nano Banana Pro 参考图示例:请求应发送到 /v1/images/generations,不要发送到 /v1/images/edits。resolution 是可选参数,可设为 1k、2k 或 4k:

{
  "model": "nano-banana-pro",
  "prompt": "Create a clean cinematic character image based on the reference images",
  "operation": "image-to-image",
  "image_urls": ["https://example.com/reference-1.png"],
  "aspect_ratio": "1:1",
  "resolution": "2k"
}

私有或本地源图可以用 multipart 直接上传。不要把 file_id 传给 /v1/images/generations:

curl -X POST "https://api.tokenlab.sh/v1/images/generations" \
  -H "Authorization: Bearer sk-your-api-key" \
  -F "model=nano-banana-pro" \
  -F "prompt=Create a clean cinematic character image based on this reference" \
  -F "operation=image-to-image" \
  -F "image=@reference.png" \
  -F "aspect_ratio=1:1" \
  -F "resolution=2k"

响应

{
  "created": 1706000000,
  "data": [
    {
      "url": "https://...",
      "revised_prompt": "A fluffy white cat with bright eyes sitting peacefully on a wooden windowsill, watching raindrops stream down the glass window..."
    }
  ]
}

错误

请求错误返回 400(上传过大返回 413),并带有 error.code。图片请求的常见错误码:

错误码原因
unsupported_parameter模型未列出该字段,或 stream 为 true
unsupported_operation模型没有该 operation
unsupported_endpoint该模型的此操作在另一个端点,例如 /v1/images/edits
unsupported_async_mode模型不支持 async: true
invalid_resolution、invalid_aspect_ratio、invalid_parameter_value、too_many_items取值超出模型接受的范围,错误信息会给出可用值
invalid_image_size_contractsize 或档位模型不支持,或与 resolution 冲突
prompt_too_long提示词超过模型允许的长度
request_too_large、file_too_large上传超过大小限制(单文件 50 MiB,所有输入合计 200 MiB)

余额不足(402)、限流(429)和重试规则见错误处理。

选择模型

通过 GET /v1/models?recommended_for=image 或模型页查看当前可用性、能力和价格。

不要把某个模型写死为始终同步或始终异步。未设置 async: true 的请求也可能返回 status: "pending";只要创建响应带有 status: "pending" 或 status: "processing",就轮询 GET /v1/tasks/{task_id} 直到完成。

处理基于任务的响应

对于图片模型,请始终检查响应是否包含 status: "pending" / status: "processing":

import requests
import time

def generate_image(prompt, model="gpt-image-2"):
    # Create image request
    response = requests.post(
        "https://api.tokenlab.sh/v1/images/generations",
        headers={"Authorization": "Bearer sk-your-api-key"},
        json={"model": model, "prompt": prompt, "async": True},
        timeout=120
    )
    response.raise_for_status()
    data = response.json()

    # Check if task-based
    if data.get("status") in ("pending", "processing"):
        task_id = data["task_id"]
        print(f"Image task started: {task_id}")

        # Poll for result
        deadline = time.time() + 600
        while time.time() < deadline:
            status_resp = requests.get(
                f"https://api.tokenlab.sh/v1/tasks/{task_id}",
                headers={"Authorization": "Bearer sk-your-api-key"},
                timeout=30
            )
            status_resp.raise_for_status()
            status_data = status_resp.json()

            if status_data["status"] == "completed":
                return status_data["data"][0]["url"]
            elif status_data["status"] == "failed":
                raise Exception(status_data.get("error", "Generation failed"))

            time.sleep(3)
        raise TimeoutError(f"Image task {task_id} did not finish in time")
    else:
        # Inline response
        return data["data"][0]["url"]

# 使用示例
url = generate_image("a beautiful sunset over mountains", model="gpt-image-2")
print(f"Generated image: {url}")

Hy Image 3.5 Preview 示例,size 只能为 1024x1024,n 只能为 1:

{
  "model": "hy-image-v3.5-preview",
  "prompt": "A yellow lemon on a white table",
  "size": "1024x1024",
  "n": 1,
  "response_format": "url"
}

授权

BearerAuth
AuthorizationBearer <token>

API Key 身份验证。在 Dashboard > API > API Keys 中创建或管理 API Key。

位置: header

请求头

X-TokenLab-Delivery-Policy?string

单次请求的交付策略。覆盖 API 密钥和 Workspace 的默认设置。自动优先尝试 TokenLab Verified,并在输出、请求接受或持久资源创建之前,可能会切换一次至仅限 Official。

可选值

  • "auto"
  • "verified"
  • "official"
Idempotency-Key?string

可选键,用于确保在请求创建了任务的情况下,图像请求可安全重试。请为每个请求发送一个新的唯一值(如 UUID)。使用相同键和相同请求体的重试将返回该任务,而不会创建、分发或扣除第二个任务。对于直接返回图像的请求,使用相同键的重试可能会返回任务状态而非图像,或返回 409 状态码及 idempotent_response_not_replayable 错误。若使用已接受的键但请求体不同,则会被拒绝;该情况下的状态码和错误代码不作保证。超过 255 个字符的键将被忽略,此时该请求不具备幂等性保护。请参阅 安全地使用幂等键进行重试。

长度1 <= length <= 255

请求体

响应

application/json

application/json

application/json

application/json

application/json

application/json

application/json