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

# 任务系统详解

> 图像与视频生成的异步任务完整流程

## 任务生命周期

```
提交 → 排队(queued) → 处理中(processing) → 完成(completed) / 失败(failed)
                ↓
          可取消(cancelled)，退还配额
```

## 任务状态

| 状态           | 说明               |
| ------------ | ---------------- |
| `queued`     | 任务已提交，等待处理       |
| `processing` | 正在生成中，可查看进度      |
| `completed`  | 生成成功，结果可用        |
| `failed`     | 生成失败，查看 error 信息 |
| `cancelled`  | 用户取消，配额已退还       |

## 提交任务

```python theme={"system"}
import openai

client = openai.OpenAI(
    base_url="https://www.qingbo.dev/v1",
    api_key="your-api-key"
)

# 提交异步任务
response = client.post("/tasks", body={
    "model": "veo3",
    "action": "generate",
    "prompt": "A cat walking on the beach",
    "duration": 5
})

task_id = response["task_id"]
print(f"任务已提交: {task_id}")
```

## 轮询状态

```python theme={"system"}
import time

def wait_for_task(client, task_id, timeout=300):
    start = time.time()
    while time.time() - start < timeout:
        result = client.get(f"/tasks/{task_id}")
        status = result["status"]

        if status == "completed":
            return result["result"]
        elif status == "failed":
            raise Exception(f"任务失败: {result['error']['message']}")

        time.sleep(2)  # 每 2 秒轮询一次
    raise TimeoutError("任务超时")
```

## 请求内等待（Prefer: wait）

不想手动轮询时，提交任务带 `Prefer: wait=N` 请求头（N ≤ 60 秒）：

* 窗口内完成 → 直接返回终态完整结果（含 `result` 与 `cost`）
* 超窗未完成 → 返回当前状态，继续用 `GET /v1/tasks/{task_id}` 轮询

## 计费与退款

| 阶段                     | 字段                  | 说明                  |
| ---------------------- | ------------------- | ------------------- |
| 提交成功                   | `pre_consumed_cost` | 预扣额度（quota），从余额立即扣除 |
| `completed`            | `cost`              | 实际结算额度，对账以此为准       |
| `failed` / `cancelled` | `cost: 0`           | 预扣额度**自动全额退款**      |

价格未配置的模型会在提交时直接拒绝（HTTP 500，`code: price_not_configured`），
不会出现"提交成功但乱扣费"的情况。

## Webhook 回调

提交任务时设置 `callback_url`，任务完成后 清波 API 会主动推送结果：

```json theme={"system"}
{
  "model": "veo3",
  "action": "generate",
  "prompt": "...",
  "callback_url": "https://your-server.com/webhook/task-done"
}
```

## 取消任务

只有 `queued` 状态的任务可以取消，取消后配额自动退还：

```bash theme={"system"}
curl -X POST https://www.qingbo.dev/v1/tasks/{task_id}/cancel \
  -H "Authorization: Bearer YOUR_API_KEY"
```

<Note>
  生成结果中的图片/视频 URL 有有效期，请及时下载保存。
</Note>
