TokenLab

圖像

建立圖片

根據提示詞建立圖片

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 官方針對文字輸入、圖片輸入、回報的快取輸入以及圖片輸出 token 的用量明細;它並非以每張圖片固定價格計費的模型。

針對 gpt-image-2 圖片生成,支援的公開參數包括 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": "..."}。圖像模型會先繪製一張參考圖像,接著編寫模型(author 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 請求亦會計入編寫模型的 token,回應會在 svg_usage 中報告此用量,並依照模型頁面上顯示的 SVG 編寫價格計費。

模型行為注意事項

Google Gemini 圖片系列模型並未共用相同的選擇器規格約束:

  • gemini-3.1-flash-image、gemini-nano-banana-2.1、gemini-3-pro-image、nano-banana-2.1 與 nano-banana-pro 在其公開的 text-to-image、image-to-image 和 image-edit 操作中支援 aspect_ratio 加上 resolution(1k、2k、4k)。
  • nano-banana-2 在 text-to-image 與 image-to-image 生成中皆支援 aspect_ratio 與 resolution(1k、2k、4k)。
  • gemini-3.1-flash-lite-image 與 nano-banana-2-lite 僅支援 1k 解析度的 text-to-image、image-to-image 和 image-edit。
  • 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 進行 image-to-image 時,請在此端點搭配 operation: "image-to-image" 與參考圖片使用。這些模型的 image-edit 請求請傳送至 /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 的 image-edit 請求亦使用此端點,並設定 operation: "image-edit"。請勿將 Nano Banana 參考圖片請求傳送至 /v1/images/edits。
  • 此端點上的參考圖片可透過 JSON 的 image_url / image_urls 提供,或以 multipart image 檔案提供。/v1/images/generations 不接受 images[] 與 file_id;僅在 /v1/images/edits 模型有明確記載 images[].file_id 時才建立 /v1/files 參照。

針對 Google 圖片系列,建議優先使用 aspect_ratio,且僅在模型明確支援時才傳送 resolution。

xAI Grok Imagine 圖片模型(grok-imagine-image 與 grok-imagine-image-2.0)支援 aspect_ratio 加上 resolution(1k、2k)。Text-to-image 使用此端點。其 image-to-image 與 image-edit 請求則使用 /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

用於 image-to-image 生成的公開圖片 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

用於 image-to-image 生成的 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 模型(如 gpt-image-2)使用 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:每張圖片僅以 Base64 資料形式位於 data[].b64_json。

連結為 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。已完成的 async 圖像任務無論請求的 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,或省略該欄位且模型傳回圖片位元組時提供。
  • revised_prompt (string):選填的修訂後提示詞(當所選模型有傳回時)
usageobject

按 token 計價之模型(如 gpt-image-2)的 Token 數量(input_tokens、output_tokens、total_tokens 及其詳細資訊),於可用時提供。

svg_usageobject

SVG author 模型的使用量計數(model、input_tokens、output_tokens、reasoning_tokens、total_tokens)。僅在輸出為 SVG 時提供。這些 token 不包含在 usage 中,並將按照 SVG authoring 的價格進行計費。

非同步任務回應

在支援的模型上設定 async: true 可建立任務,而非在建立請求中等待最終圖片。回應包含 status: "pending"、task_id 與 poll_url。請輪詢 /v1/tasks/{task_id} 直至任務達到 completed 或 failed。

非同步圖片任務僅傳回最終圖片 URL。若您需要原始 b64_json 圖片資料,請使用同步請求。

計費系統可能會在建立任務時預扣預估金額。已完成的任務將依實際用量計費,失敗或逾時的任務則會解除預扣或退款。

createdinteger

建立時的 Unix 時間戳記。

task_idstring

用於輪詢的唯一任務識別碼。

statusstring

初始狀態:pending。

poll_urlstring

用於輪詢結果的相對 URL,例如 /v1/tasks/{id}。

dataarray

任務處於待處理(pending)狀態時為空。已完成的圖片任務會在 data[].url 中傳回生成的圖片 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_contract模型不支援的 size 或層級,或與 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"]

# Usage
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 金鑰。

位置: header

請求標頭

X-TokenLab-Delivery-Policy?string

單次請求傳遞策略。會覆寫 API key 與 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