curl --request GET \
--url 'https://toapis.com/v1/images/generations/task_01KA040M0HP1GJWBJYZMKX1XS1' \
--header 'Authorization: Bearer <token>'
import requests
import time
API_BASE = 'https://toapis.com'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'
headers = {
'Authorization': f'Bearer {API_KEY}'
}
def get_image_status(task_id):
response = requests.get(f'{API_BASE}/v1/images/generations/{task_id}', headers=headers)
return response.json()
def wait_for_image(task_id, max_attempts=60, interval=3):
for _ in range(max_attempts):
result = get_image_status(task_id)
status = result.get('status')
print(f"狀態: {status}")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"任務失敗: {result}")
time.sleep(interval)
raise Exception("任務超時")
# 使用示例
task_id = "task_01KA040M0HP1GJWBJYZMKX1XS1"
result = wait_for_image(task_id)
print(f"圖片URL: {result['url']}")
const API_BASE = 'https://toapis.com';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';
async function getImageStatus(taskId) {
const response = await fetch(`${API_BASE}/v1/images/generations/${taskId}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.json();
}
async function waitForImage(taskId, maxAttempts = 60, interval = 3000) {
for (let i = 0; i < maxAttempts; i++) {
const result = await getImageStatus(taskId);
const status = result.status;
console.log(`狀態: ${status}`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`任務失敗: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('任務超時');
}
// 使用示例
const taskId = 'task_01KA040M0HP1GJWBJYZMKX1XS1';
waitForImage(taskId).then(result => {
console.log('圖片URL:', result.url);
});
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func getImageStatus(taskId string) (map[string]interface{}, error) {
url := fmt.Sprintf("https://toapis.com/v1/images/generations/%s", taskId)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer <token>")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
func main() {
taskId := "task_01KA040M0HP1GJWBJYZMKX1XS1"
for i := 0; i < 60; i++ {
result, _ := getImageStatus(taskId)
status := result["status"].(string)
fmt.Printf("狀態: %s\n", status)
if status == "completed" {
fmt.Println("圖片生成完成!")
fmt.Println("圖片URL:", result["url"])
break
}
time.Sleep(3 * time.Second)
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "in_progress",
"progress": 50,
"created_at": 1768381010,
"billing": {
"status": "pending"
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"client_business_id": "order_20260428_001",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "completed",
"progress": 100,
"created_at": 1768381010,
"completed_at": 1768381063,
"expires_at": 1768467463,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/1768381061_c55c1bbb.jpg"
}
]
}
}
{
"id": "img_73c450923a9a43e4aabf426e1c681d64",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "failed",
"progress": 0,
"created_at": 1768215312,
"billing": {
"status": "refunded",
"credits": "0",
"cost_usd": "0"
},
"error": {
"code": "generation_failed",
"message": "call upstream API failed: upstream returned status 422"
}
}
{
"id": "tsk_img_example",
"object": "generation.task",
"model": "gpt-image-2.5-flare-official",
"status": "completed",
"progress": 100,
"created_at": 1789099098,
"completed_at": 1789099158,
"expires_at": 1789185558,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/example.png"
}
]
},
"usage": {
"input_tokens": 100,
"output_tokens": 900,
"total_tokens": 1000,
"input_tokens_details": {
"text_tokens": 20,
"image_tokens": 80,
"cached_tokens": 30,
"cached_tokens_details": {
"text_tokens": 10,
"image_tokens": 20
}
},
"output_tokens_details": {
"text_tokens": 0,
"image_tokens": 900
}
},
"billing": {
"status": "settled",
"credits": "0",
"cost_usd": "0"
}
}
{
"error": {
"code": 404,
"message": "任務不存在",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "身份驗證失敗,請檢查您的API密鑰",
"type": "authentication_error"
}
}
獲取圖片任務狀態
獲取圖片任務狀態
查詢圖片生成任務的狀態和結果
GET
/
v1
/
images
/
generations
/
{task_id}
curl --request GET \
--url 'https://toapis.com/v1/images/generations/task_01KA040M0HP1GJWBJYZMKX1XS1' \
--header 'Authorization: Bearer <token>'
import requests
import time
API_BASE = 'https://toapis.com'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'
headers = {
'Authorization': f'Bearer {API_KEY}'
}
def get_image_status(task_id):
response = requests.get(f'{API_BASE}/v1/images/generations/{task_id}', headers=headers)
return response.json()
def wait_for_image(task_id, max_attempts=60, interval=3):
for _ in range(max_attempts):
result = get_image_status(task_id)
status = result.get('status')
print(f"狀態: {status}")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"任務失敗: {result}")
time.sleep(interval)
raise Exception("任務超時")
# 使用示例
task_id = "task_01KA040M0HP1GJWBJYZMKX1XS1"
result = wait_for_image(task_id)
print(f"圖片URL: {result['url']}")
const API_BASE = 'https://toapis.com';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';
async function getImageStatus(taskId) {
const response = await fetch(`${API_BASE}/v1/images/generations/${taskId}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.json();
}
async function waitForImage(taskId, maxAttempts = 60, interval = 3000) {
for (let i = 0; i < maxAttempts; i++) {
const result = await getImageStatus(taskId);
const status = result.status;
console.log(`狀態: ${status}`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`任務失敗: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('任務超時');
}
// 使用示例
const taskId = 'task_01KA040M0HP1GJWBJYZMKX1XS1';
waitForImage(taskId).then(result => {
console.log('圖片URL:', result.url);
});
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func getImageStatus(taskId string) (map[string]interface{}, error) {
url := fmt.Sprintf("https://toapis.com/v1/images/generations/%s", taskId)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer <token>")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
func main() {
taskId := "task_01KA040M0HP1GJWBJYZMKX1XS1"
for i := 0; i < 60; i++ {
result, _ := getImageStatus(taskId)
status := result["status"].(string)
fmt.Printf("狀態: %s\n", status)
if status == "completed" {
fmt.Println("圖片生成完成!")
fmt.Println("圖片URL:", result["url"])
break
}
time.Sleep(3 * time.Second)
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "in_progress",
"progress": 50,
"created_at": 1768381010,
"billing": {
"status": "pending"
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"client_business_id": "order_20260428_001",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "completed",
"progress": 100,
"created_at": 1768381010,
"completed_at": 1768381063,
"expires_at": 1768467463,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/1768381061_c55c1bbb.jpg"
}
]
}
}
{
"id": "img_73c450923a9a43e4aabf426e1c681d64",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "failed",
"progress": 0,
"created_at": 1768215312,
"billing": {
"status": "refunded",
"credits": "0",
"cost_usd": "0"
},
"error": {
"code": "generation_failed",
"message": "call upstream API failed: upstream returned status 422"
}
}
{
"id": "tsk_img_example",
"object": "generation.task",
"model": "gpt-image-2.5-flare-official",
"status": "completed",
"progress": 100,
"created_at": 1789099098,
"completed_at": 1789099158,
"expires_at": 1789185558,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/example.png"
}
]
},
"usage": {
"input_tokens": 100,
"output_tokens": 900,
"total_tokens": 1000,
"input_tokens_details": {
"text_tokens": 20,
"image_tokens": 80,
"cached_tokens": 30,
"cached_tokens_details": {
"text_tokens": 10,
"image_tokens": 20
}
},
"output_tokens_details": {
"text_tokens": 0,
"image_tokens": 900
}
},
"billing": {
"status": "settled",
"credits": "0",
"cost_usd": "0"
}
}
{
"error": {
"code": 404,
"message": "任務不存在",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "身份驗證失敗,請檢查您的API密鑰",
"type": "authentication_error"
}
}
中國大陸用戶請注意: 中國大陸用戶請使用
https://toapis.cn 作為接口地址(Base URL)。文檔示例中的 https://toapis.com 請替換為 https://toapis.cn。- 查詢異步圖片生成任務的執行狀態和結果
- 實時狀態更新和進度跟蹤
- 任務完成時獲取生成的圖片
- 支持多語言返回(zh/en/ko/ja)
創建任務時傳入業務 ID
創建圖片任務時,可以在請求體頂層傳入client_business_id。該字段用於保存您系統內的訂單號、流水號或業務任務 ID,方便後續按業務 ID 查詢生成結果。
{
"model": "gpt-4o-image",
"client_business_id": "order_20260428_001",
"prompt": "一隻可愛的熊貓",
"size": "1:1",
"n": 1
}
metadata.client_business_id 中,但推薦使用頂層字段。
Authorizations
string
必填
所有接口均需要使用 Bearer Token 進行認證獲取 API Key:訪問 API Key 管理頁面 獲取您的 API Key使用時在請求頭中添加:
Authorization: Bearer YOUR_API_KEY
Path Parameters
string
必填
圖片生成 API 返回的任務 ID。也可以傳創建任務時提交的
client_business_id,用於按客戶側業務 ID 查詢任務狀態和結果。如果創建圖片任務時傳入
client_business_id,可直接使用同一個狀態查詢接口:
GET /v1/images/generations/{client_business_id}。業務 ID 會限定在當前 API Key 所屬用戶下查詢。curl --request GET \
--url 'https://toapis.com/v1/images/generations/task_01KA040M0HP1GJWBJYZMKX1XS1' \
--header 'Authorization: Bearer <token>'
import requests
import time
API_BASE = 'https://toapis.com'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'
headers = {
'Authorization': f'Bearer {API_KEY}'
}
def get_image_status(task_id):
response = requests.get(f'{API_BASE}/v1/images/generations/{task_id}', headers=headers)
return response.json()
def wait_for_image(task_id, max_attempts=60, interval=3):
for _ in range(max_attempts):
result = get_image_status(task_id)
status = result.get('status')
print(f"狀態: {status}")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"任務失敗: {result}")
time.sleep(interval)
raise Exception("任務超時")
# 使用示例
task_id = "task_01KA040M0HP1GJWBJYZMKX1XS1"
result = wait_for_image(task_id)
print(f"圖片URL: {result['url']}")
const API_BASE = 'https://toapis.com';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';
async function getImageStatus(taskId) {
const response = await fetch(`${API_BASE}/v1/images/generations/${taskId}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.json();
}
async function waitForImage(taskId, maxAttempts = 60, interval = 3000) {
for (let i = 0; i < maxAttempts; i++) {
const result = await getImageStatus(taskId);
const status = result.status;
console.log(`狀態: ${status}`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`任務失敗: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('任務超時');
}
// 使用示例
const taskId = 'task_01KA040M0HP1GJWBJYZMKX1XS1';
waitForImage(taskId).then(result => {
console.log('圖片URL:', result.url);
});
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func getImageStatus(taskId string) (map[string]interface{}, error) {
url := fmt.Sprintf("https://toapis.com/v1/images/generations/%s", taskId)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer <token>")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
func main() {
taskId := "task_01KA040M0HP1GJWBJYZMKX1XS1"
for i := 0; i < 60; i++ {
result, _ := getImageStatus(taskId)
status := result["status"].(string)
fmt.Printf("狀態: %s\n", status)
if status == "completed" {
fmt.Println("圖片生成完成!")
fmt.Println("圖片URL:", result["url"])
break
}
time.Sleep(3 * time.Second)
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "in_progress",
"progress": 50,
"created_at": 1768381010,
"billing": {
"status": "pending"
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"client_business_id": "order_20260428_001",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "completed",
"progress": 100,
"created_at": 1768381010,
"completed_at": 1768381063,
"expires_at": 1768467463,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/1768381061_c55c1bbb.jpg"
}
]
}
}
{
"id": "img_73c450923a9a43e4aabf426e1c681d64",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "failed",
"progress": 0,
"created_at": 1768215312,
"billing": {
"status": "refunded",
"credits": "0",
"cost_usd": "0"
},
"error": {
"code": "generation_failed",
"message": "call upstream API failed: upstream returned status 422"
}
}
{
"id": "tsk_img_example",
"object": "generation.task",
"model": "gpt-image-2.5-flare-official",
"status": "completed",
"progress": 100,
"created_at": 1789099098,
"completed_at": 1789099158,
"expires_at": 1789185558,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/example.png"
}
]
},
"usage": {
"input_tokens": 100,
"output_tokens": 900,
"total_tokens": 1000,
"input_tokens_details": {
"text_tokens": 20,
"image_tokens": 80,
"cached_tokens": 30,
"cached_tokens_details": {
"text_tokens": 10,
"image_tokens": 20
}
},
"output_tokens_details": {
"text_tokens": 0,
"image_tokens": 900
}
},
"billing": {
"status": "settled",
"credits": "0",
"cost_usd": "0"
}
}
{
"error": {
"code": 404,
"message": "任務不存在",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "身份驗證失敗,請檢查您的API密鑰",
"type": "authentication_error"
}
}
Response
string
任務唯一標識符
string
客戶側業務 ID。僅當創建任務時傳入
client_business_id 時返回。string
對象類型,固定爲
generation.taskstring
使用的圖片生成模型
string
任務狀態
queued- 排隊等待處理in_progress- 處理中completed- 成功完成failed- 失敗
integer
任務進度百分比(0-100)
integer
任務創建時間(Unix 時間戳)
integer
任務完成時間(Unix 時間戳,僅完成時返回)
integer
圖片 URL 過期時間(Unix 時間戳,僅完成時返回)
object
選填的圖片任務計費資訊. 計費狀態獨立於生成狀態,
completed 不保證已經結算. 無法確認計費資料時會省略整個 billing, 不回傳 null, 也不代表免費.object
選填的已結算圖片 token 用量. 僅在
所有 token 數均為非負 JSON 整數. 快取 token 是輸入 token 的子集, 不能重複相加.
billing.status 為 settled, 且已儲存的用量有效並與最終扣款一致時回傳圖片 token 欄位. 缺少或無法驗證時省略, 不估算, 不用零值代替; 已確認的金額和圖片結果仍可正常回傳.| 欄位 | 類型 | 說明 |
|---|---|---|
input_tokens | integer | 輸入 token 總數, 包含文字和圖片 |
output_tokens | integer | 輸出 token 總數 |
total_tokens | integer | input_tokens + output_tokens |
input_tokens_details.text_tokens | integer | 文字輸入 token 數 |
input_tokens_details.image_tokens | integer | 圖片輸入 token 數 |
input_tokens_details.cached_tokens | integer | 已快取的輸入 token 數, 已包含在輸入總數中 |
input_tokens_details.cached_tokens_details.text_tokens | integer | 已快取的文字輸入 token 數 |
input_tokens_details.cached_tokens_details.image_tokens | integer | 已快取的圖片輸入 token 數 |
output_tokens_details.text_tokens | integer | 文字輸出 token 數, 僅在有輸出明細時回傳 |
output_tokens_details.image_tokens | integer | 圖片輸出 token 數, 僅在有輸出明細時回傳 |
output_tokens_details 在未提供明細時整體省略. usage.tool_usage.web_search 可獨立回傳, 也可與圖片 token 並存.計費狀態與費用統計
上述計費規則適用於圖片任務查詢, 不限制模型或管道. GPT-Image-2.5 的 Sunburst 和 Flare VIP / Official 型號已支援 token 用量, 其他模型是否回傳取決於既有結算資料. 範例金額僅用於說明回應格式, 不是固定單價.| billing.status | 意義 | 金額與圖片 token |
|---|---|---|
pending | 生成中, 待結算, 或退款尚未確認 | 省略金額和圖片 token; 預扣不代表最終費用 |
settled | 已確認最終結算 | 回傳金額, 有有效用量時回傳圖片 token; 免費任務金額也可為 "0" |
refunded | 已退款或失敗後已確認無淨扣款 | credits 和 cost_usd 均為 "0", 省略圖片 token |
- 金額來自任務已確認的最終扣款, 查詢不會觸發扣款, 補扣或退款, 也不會按最新模型價格重新計算. 統計時直接使用回傳金額, 不要用 token 乘目前單價替代.
- 依任務
id去除重複紀錄並更新金額, 不要累加每次輪詢的回傳值. 使用十進位計算;pending或欄位缺少不能視為零費用. - 金額使用十進位字串, 不保證固定小數位數.
- 計費紀錄缺少或不一致時可能省略
billing. 圖片尚無法交付而暫時顯示為in_progress時, 也可能同時省略billing和usage. - 成功 Webhook 的
data.usage可包含相同的圖片 token 欄位,data.billing也可能包含已確認費用。任一欄位缺少時,可查詢此介面作為後備。詳見價格與實際費用。
任務狀態說明
| 狀態 | 說明 | 是否終態 | 建議操作 |
|---|---|---|---|
queued | 任務排隊等待處理 | ❌ | 等待至少 5-10 秒並加入抖動後查詢 |
in_progress | 任務正在處理中 | ❌ | 等待至少 5-10 秒並加入抖動後查詢 |
completed | 任務成功完成 | ✅ | 從 result.data[0].url 獲取圖片 |
failed | 任務處理失敗 | ✅ | 檢查 error 信息 |
輪詢策略建議
初始等待: 5 秒
輪詢間隔: 至少 5-10 秒並加入隨機抖動
最大等待: 120 秒
典型耗時: 5-30 秒
Python 輪詢示例
import time
import random
import requests
def poll_image_task(task_id, api_key, max_wait=120):
"""輪詢圖片生成任務直到完成或超時"""
start_time = time.time()
interval = 5
while time.time() - start_time < max_wait:
response = requests.get(
f'https://toapis.com/v1/images/generations/{task_id}',
headers={'Authorization': f'Bearer {api_key}'}
)
if response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', interval))
time.sleep(retry_after + random.uniform(0, 1))
interval = min(interval * 2, 60)
continue
response.raise_for_status()
data = response.json()
if data['status'] == 'completed':
return data['url']
elif data['status'] == 'failed':
raise Exception(f"生成失敗: {data['error']['message']}")
time.sleep(interval + random.uniform(0, 1))
raise TimeoutError("任務超時")
圖片資源有效期
生成的圖片 URL 有效期爲 24 小時
- 請在有效期內下載保存圖片
expires_at字段標識圖片過期時間(Unix 時間戳)- 圖片過期後無法訪問,如需重新獲取,需要重新提交生成任務
常見錯誤
| 錯誤碼 | 錯誤類型 | 說明 |
|---|---|---|
| 400 | invalid_request | 請求參數無效 |
| 401 | unauthorized | 認證失敗,檢查 API Key |
| 402 | insufficient_quota | 餘額不足 |
| 404 | task_not_found | 任務不存在 |
| 422 | content_policy_violation | 內容違規 |
| 429 | rate_limit_exceeded | 請求頻率超限 |
| 500 | internal_error | 服務器內部錯誤 |