图像

生成图片

根据提示词生成图片

POST
/v1/images/generations

概述

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

gpt-image-2 按文本输入、图片输入、缓存输入和图片输出 tokens 计费,不是固定每张收费。

gpt-image-2 支持 prompt、n、size、quality、response_format、async、background、output_format、output_compression / compression、moderation 和 user。background 可以是 auto 或 opaque,暂不支持 transparent。省略 size 或 quality 时使用 auto。

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

不同图片模型的参数

Google Gemini 图片模型并不共用同一套参数选择规则:

  • gemini-3.1-flash-image、gemini-3-pro-image 和 nano-banana-pro 在公开的文生图、图片编辑/图生图操作中支持 aspect_ratio 和 resolution(1k、2k、4k)。
  • nano-banana-2 在文生图和图生图中均支持 aspect_ratio 和 resolution(1k、2k、4k)。
  • gemini-2.5-flash-image、nano-banana 和 nano-banana-edit 支持 aspect_ratio,但不提供公开的 resolution 选择。
  • Nano Banana 参考图请求请在本端点(/v1/images/generations)使用 nano-banana-edit 或 nano-banana-pro,并发送 operation: "image-to-image" 与 image_urls。不要把 Nano Banana 参考图请求发送到 /v1/images/edits。
  • 参考图可以通过 JSON image_url / image_urls 传入,也可以通过 multipart image 直接上传。/v1/images/generations 不接受 images[] 或 file_id;这些字段只用于明确支持它们的 /v1/images/edits 模型。

使用 Google 图片模型时,优先发送 aspect_ratio;只有模型明确支持时才发送 resolution。

xAI Grok Imagine 图片模型(grok-imagine-image、grok-imagine-image-quality 以及 legacy grok-imagine-image-pro)支持 aspect_ratio 和 resolution(1k、2k)。grok-imagine-image-pro 会作为 grok-imagine-image-quality 的兼容 ID 保留。

请求体

请求超时: 同步图片请求可能需要较长时间,建议把 HTTP 超时设为至少 120s。响应包含 pending、task_id 或 poll_url 时,通过 poll_url 查询结果。

modelstring必填

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

promptstring必填

所需图片的文本描述。

image_urlstring

用于图生图的公开 HTTPS 参考图 URL。Nano Banana 参考图请求请设置 operation 为 image-to-image;nano-banana-pro 可以发送 resolution,nano-banana-edit 应省略该参数。

image_urlsstring[]

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

reference_image_urlsstring[]

模型支持时,用于区分主输入图与其他参考图。

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 图片模型,建议直接使用 aspect_ratio;模型支持时也可以填写 resolution。

aspect_ratiostring

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

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

resolutionstring

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

qualitystring

图片质量。gpt-image-2 等 GPT Image 模型使用 auto、low、medium 或 high。其他图片系列可能使用提供者特定取值;发送非默认值前请先查看所选模型的元数据。

response_formatstring默认值: url

响应格式:url 或 b64_json,默认 url。

url 通过 data[].url 返回图片地址;b64_json 通过 data[].b64_json 返回 Base64 图片数据。

asyncboolean默认值: false

对 gpt-image-2 或官方 FLUX/BFL 图片模型设置为 true 时,会先创建任务。完成后的异步图片任务无论请求的 response_format 是什么,都只返回 URL;如果需要 b64_json,请使用同步请求。

stylestring

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

userstring

终端用户的唯一标识符。

响应

直接返回图片

createdinteger

创建时的 Unix 时间戳。

dataarray

生成的图像数组。

每个对象包含:

  • url (string):生成的图像 URL
  • b64_json (string):Base64 编码的图像(如果请求)
  • revised_prompt (string): 所选模型返回的可选提示词改写结果

返回异步任务

支持异步生成的模型设置 async: true 后,会先返回 pending、task_id 和 poll_url。通过 poll_url 查询,直到状态变为 completed 或 failed。

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

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

createdinteger

创建时的 Unix 时间戳。

task_idstring

用于查询状态的任务 ID。

statusstring

初始状态:pending。

poll_urlstring

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

dataarray

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

收到 status: "pending" 后,使用 poll_url 或 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'];

仅支持比例选择的图片系列示例:使用 gemini-2.5-flash-image、nano-banana 或 nano-banana-edit 时,发送 aspect_ratio,不要发送 resolution:

{
  "model": "gemini-2.5-flash-image",
  "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..."
    }
  ]
}

查看当前模型

最新模型、能力和价格以 GET /v1/models?recommended_for=image 与模型页为准。不要假设某个模型永远同步或异步;响应返回 pending 时,按 poll_url 查询即可。

处理异步响应

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

import requests
import time

def generate_image(prompt, model="gpt-image-2"):
    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()

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

        while True:
            status_resp = requests.get(
                f"https://api.tokenlab.sh{poll_url}" if poll_url else 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"]
            if status_data["status"] == "failed":
                raise Exception(status_data.get("error", "Generation failed"))

            time.sleep(3)

    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 可根据文本生成 1024 像素方形图像,并按文字指令编辑参考图,适用于视觉草稿与构图调整。

{
  "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"

请求体

响应

application/json

application/json

application/json

application/json

application/json

application/json

application/json