> ## Documentation Index
> Fetch the complete documentation index at: https://docs.toapis.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 獲取圖片任務狀態

> 查詢圖片生成任務的狀態和結果

* 查詢異步圖片生成任務的執行狀態和結果
* 實時狀態更新和進度跟蹤
* 任務完成時獲取生成的圖片
* 支持多語言返回（zh/en/ko/ja）

所有圖片生成任務都是異步執行的。提交任務後，您需要通過查詢接口獲取任務狀態和結果。

## 創建任務時傳入業務 ID

創建圖片任務時，可以在請求體頂層傳入 `client_business_id`。該字段用於保存您系統內的訂單號、流水號或業務任務 ID，方便後續按業務 ID 查詢生成結果。

```json theme={null}
{
  "model": "gpt-4o-image",
  "client_business_id": "order_20260428_001",
  "prompt": "一隻可愛的熊貓",
  "size": "1:1",
  "n": 1
}
```

也兼容放在 `metadata.client_business_id` 中，但推薦使用頂層字段。

## Authorizations

<ParamField header="Authorization" type="string" required>
  所有接口均需要使用 Bearer Token 進行認證

  獲取 API Key：

  訪問 [API Key 管理頁面](https://toapis.com/console/token) 獲取您的 API Key

  使用時在請求頭中添加：

  ```
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

## Path Parameters

<ParamField path="task_id" type="string" required>
  圖片生成 API 返回的任務 ID。也可以傳創建任務時提交的 `client_business_id`，用於按客戶側業務 ID 查詢任務狀態和結果。
</ParamField>

<Note>
  如果創建圖片任務時傳入 `client_business_id`，可直接使用同一個狀態查詢接口：
  `GET /v1/images/generations/{client_business_id}`。業務 ID 會限定在當前 API Key 所屬用戶下查詢。
</Note>

<RequestExample>
  ```bash cURL theme={null}
  curl --request GET \
    --url 'https://toapis.com/v1/images/generations/task_01KA040M0HP1GJWBJYZMKX1XS1' \
    --header 'Authorization: Bearer <token>'
  ```

  ```python Python theme={null}
  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']}")
  ```

  ```javascript JavaScript theme={null}
  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);
  });
  ```

  ```go Go theme={null}
  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)
      }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200 - 處理中 theme={null}
  {
    "id": "img_5b8b19afe5c24ab3a92df996f1a33931",
    "object": "generation.task",
    "model": "gemini-3-pro-image-preview",
    "status": "in_progress",
    "progress": 50,
    "created_at": 1768381010
  }
  ```

  ```json 200 - 已完成 theme={null}
  {
    "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.dashlyai.cc/generated/1768381061_c55c1bbb.jpg"
        }
      ]
    }
  }
  ```

  ```json 200 - 失敗 theme={null}
  {
    "id": "img_73c450923a9a43e4aabf426e1c681d64",
    "object": "generation.task",
    "model": "gemini-3-pro-image-preview",
    "status": "failed",
    "progress": 0,
    "created_at": 1768215312,
    "error": {
      "code": "generation_failed",
      "message": "call upstream API failed: upstream returned status 422"
    }
  }
  ```

  ```json 404 theme={null}
  {
    "error": {
      "code": 404,
      "message": "任務不存在",
      "type": "not_found_error"
    }
  }
  ```

  ```json 401 theme={null}
  {
    "error": {
      "code": 401,
      "message": "身份驗證失敗，請檢查您的API密鑰",
      "type": "authentication_error"
    }
  }
  ```
</ResponseExample>

## Response

<ResponseField name="id" type="string">
  任務唯一標識符
</ResponseField>

<ResponseField name="client_business_id" type="string">
  客戶側業務 ID。僅當創建任務時傳入 `client_business_id` 時返回。
</ResponseField>

<ResponseField name="object" type="string">
  對象類型，固定爲 `generation.task`
</ResponseField>

<ResponseField name="model" type="string">
  使用的圖片生成模型
</ResponseField>

<ResponseField name="status" type="string">
  任務狀態

  * `queued` - 排隊等待處理
  * `in_progress` - 處理中
  * `completed` - 成功完成
  * `failed` - 失敗
</ResponseField>

<ResponseField name="progress" type="integer">
  任務進度百分比（0-100）
</ResponseField>

<ResponseField name="created_at" type="integer">
  任務創建時間（Unix 時間戳）
</ResponseField>

<ResponseField name="completed_at" type="integer">
  任務完成時間（Unix 時間戳，僅完成時返回）
</ResponseField>

<ResponseField name="expires_at" type="integer">
  圖片 URL 過期時間（Unix 時間戳，僅完成時返回）
</ResponseField>

<ResponseField name="result" type="object">
  任務結果（僅成功時返回）

  <Expandable title="屬性">
    <ResponseField name="type" type="string">
      結果類型，固定爲 `image`
    </ResponseField>

    <ResponseField name="data" type="array">
      圖片數據數組

      <Expandable title="數組元素">
        <ResponseField name="url" type="string">
          生成的圖片 URL
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="error" type="object">
  錯誤信息（僅失敗時返回）

  <Expandable title="屬性">
    <ResponseField name="code" type="string">
      錯誤代碼
    </ResponseField>

    <ResponseField name="message" type="string">
      錯誤描述
    </ResponseField>
  </Expandable>
</ResponseField>

## 任務狀態說明

| 狀態            | 說明       | 是否終態 | 建議操作                       |
| ------------- | -------- | ---- | -------------------------- |
| `queued`      | 任務排隊等待處理 | ❌    | 等待 2-3 秒後重試查詢              |
| `in_progress` | 任務正在處理中  | ❌    | 等待 3-5 秒後重試查詢              |
| `completed`   | 任務成功完成   | ✅    | 從 result.data\[0].url 獲取圖片 |
| `failed`      | 任務處理失敗   | ✅    | 檢查 error 信息                |

## 輪詢策略建議

```
初始等待: 2 秒
輪詢間隔: 3 秒
最大等待: 120 秒
典型耗時: 5-30 秒
```

### Python 輪詢示例

```python theme={null}
import time
import requests

def poll_image_task(task_id, api_key, max_wait=120):
    """輪詢圖片生成任務直到完成或超時"""
    start_time = time.time()
    interval = 3  # 3秒間隔

    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}'}
        )
        data = response.json()

        if data['status'] == 'completed':
            return data['url']
        elif data['status'] == 'failed':
            raise Exception(f"生成失敗: {data['error']['message']}")

        time.sleep(interval)

    raise TimeoutError("任務超時")
```

## 圖片資源有效期

<Warning>
  生成的圖片 URL 有效期爲 **24 小時**

  * 請在有效期內下載保存圖片
  * `expires_at` 字段標識圖片過期時間（Unix 時間戳）
  * 圖片過期後無法訪問，如需重新獲取，需要重新提交生成任務
</Warning>

## 常見錯誤

| 錯誤碼 | 錯誤類型                       | 說明              |
| --- | -------------------------- | --------------- |
| 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`           | 服務器內部錯誤         |
