> ## 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": "sora-2",
  "client_business_id": "order_20260428_002",
  "prompt": "海浪拍打着海岸",
  "duration": 15,
  "aspect_ratio": "16:9"
}
```

也兼容放在 `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/videos/generations/{client_business_id}`。業務 ID 會限定在當前 API Key 所屬用戶下查詢。
</Note>

<RequestExample>
  ```bash cURL theme={null}
  curl --request GET \
    --url 'https://toapis.com/v1/videos/generations/task_01K9S419324DREZFBWNSVXYR6H' \
    --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_video_status(task_id):
      response = requests.get(f'{API_BASE}/v1/videos/generations/{task_id}', headers=headers)
      return response.json()

  def wait_for_video(task_id, max_attempts=60, interval=10):
      for _ in range(max_attempts):
          result = get_video_status(task_id)
          status = result.get('status')
          progress = result.get('progress', 0)

          print(f"狀態: {status}, 進度: {progress}%")

          if status == 'completed':
              return result
          elif status == 'failed':
              raise Exception(f"任務失敗: {result}")

          time.sleep(interval)

      raise Exception("任務超時")

  # 使用示例
  task_id = "video_7497f4d5-3a88-44c7-923a-967fa7d941a0"
  result = wait_for_video(task_id)
  print(f"視頻URL: {result['result']['data'][0]['url']}")
  ```

  ```javascript JavaScript theme={null}
  const API_BASE = 'https://toapis.com';
  const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';

  async function getVideoStatus(taskId) {
    const response = await fetch(`${API_BASE}/v1/videos/generations/${taskId}`, {
      headers: {
        'Authorization': `Bearer ${API_KEY}`
      }
    });
    return response.json();
  }

  async function waitForVideo(taskId, maxAttempts = 60, interval = 10000) {
    for (let i = 0; i < maxAttempts; i++) {
      const result = await getVideoStatus(taskId);
      const status = result.status;
      const progress = result.progress || 0;

      console.log(`狀態: ${status}, 進度: ${progress}%`);

      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 = 'video_7497f4d5-3a88-44c7-923a-967fa7d941a0';
  waitForVideo(taskId).then(result => {
    console.log('視頻URL:', result.result.data[0].url);
    console.log('格式:', result.result.data[0].format);
  });
  ```

  ```go Go theme={null}
  package main

  import (
      "encoding/json"
      "fmt"
      "io/ioutil"
      "net/http"
      "time"
  )

  func getVideoStatus(taskId string) (map[string]interface{}, error) {
      url := fmt.Sprintf("https://toapis.com/v1/videos/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 := "video_7497f4d5-3a88-44c7-923a-967fa7d941a0"

      for i := 0; i < 60; i++ {
          result, _ := getVideoStatus(taskId)
          status := result["status"].(string)
          progress := int(result["progress"].(float64))

          fmt.Printf("狀態: %s, 進度: %d%%\n", status, progress)

          if status == "completed" {
              fmt.Println("視頻生成完成!")
              resultData := result["result"].(map[string]interface{})
              dataArray := resultData["data"].([]interface{})
              videoData := dataArray[0].(map[string]interface{})
              fmt.Println("視頻URL:", videoData["url"])
              break
          }

          time.Sleep(10 * time.Second)
      }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200 - 排隊中 theme={null}
  {
    "id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
    "object": "generation.task",
    "model": "sora-2",
    "status": "queued",
    "progress": 0,
    "created_at": 1768380222
  }
  ```

  ```json 200 - 處理中 theme={null}
  {
    "id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
    "object": "generation.task",
    "model": "sora-2",
    "status": "in_progress",
    "progress": 65,
    "created_at": 1768380222
  }
  ```

  ```json 200 - 已完成 theme={null}
  {
    "id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
    "client_business_id": "order_20260428_001",
    "object": "generation.task",
    "model": "sora-2",
    "status": "completed",
    "progress": 100,
    "created_at": 1768380222,
    "completed_at": 1768380514,
    "expires_at": 1768466914,
    "result": {
      "type": "video",
      "data": [
        {
          "url": "https://files.dashlyai.cc/sora/7712af45-ca35-4a15-b800-f20ea623665b.mp4",
          "format": "mp4"
        }
      ]
    }
  }
  ```

  ```json 200 - 失敗 theme={null}
  {
    "id": "video_7497f4d5-3a88-44c7-923a-967fa7d941a0",
    "object": "generation.task",
    "model": "sora-2",
    "status": "failed",
    "progress": 0,
    "created_at": 1768380222,
    "error": {
      "code": "generation_failed",
      "message": "生成失敗: 內容違反了內容政策"
    }
  }
  ```

  ```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">
      結果類型，固定爲 `video`
    </ResponseField>

    <ResponseField name="data" type="array">
      視頻數據數組

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

        <ResponseField name="format" type="string">
          視頻格式（如 `mp4`）
        </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`      | 任務排隊等待處理 | ❌    | 等待 5-10 秒後重試查詢             |
| `in_progress` | 任務正在處理中  | ❌    | 等待 10-15 秒後重試查詢            |
| `completed`   | 任務成功完成   | ✅    | 從 result.data\[0].url 獲取視頻 |
| `failed`      | 任務處理失敗   | ✅    | 檢查 error 信息                |

## 輪詢策略建議

```
初始等待: 5 秒
輪詢間隔: 10 秒
最大等待: 600 秒（10分鐘）
典型耗時: 1-5 分鐘
```

### Python 輪詢示例

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

def poll_video_task(task_id, api_key, max_wait=600):
    """輪詢視頻生成任務直到完成或超時"""
    start_time = time.time()
    interval = 10  # 10秒間隔

    # 首次等待5秒
    time.sleep(5)

    while time.time() - start_time < max_wait:
        response = requests.get(
            f'https://toapis.com/v1/videos/generations/{task_id}',
            headers={'Authorization': f'Bearer {api_key}'}
        )
        data = response.json()

        print(f"狀態: {data['status']}, 進度: {data.get('progress', 0)}%")

        if data['status'] == 'completed':
            return {
                'url': data['result']['data'][0]['url'],
                'format': data['result']['data'][0].get('format'),
                'expires_at': data.get('expires_at')
            }
        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`           | 服務器內部錯誤         |

## 性能建議

<Note>
  視頻生成耗時較長，建議：

  1. **使用 Webhook 回調**：如果平臺支持，配置回調URL可以避免頻繁輪詢
  2. **合理設置輪詢間隔**：建議10秒，過於頻繁會浪費請求配額
  3. **設置超時時間**：長視頻生成可能需要5-10分鐘，請設置合理的超時
  4. **及時下載保存**：視頻24小時後過期，請務必及時保存到自己的存儲
</Note>
