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

# 异步任务

> 视频和音频生成是异步的。本文介绍如何获取结果。

## 同步与异步

| Endpoint                      | Mode                                          |
| ----------------------------- | --------------------------------------------- |
| `POST /v1/chat/completions`   | **同步** — 响应中直接包含结果。                           |
| `POST /v1/images/generations` | **同步** — 连接会保持到图片就绪（通常 5–30 秒）。               |
| `POST /v1/videos/generations` | **异步** — 返回 `{id, status:"pending"}`；轮询或使用回调。 |
| `POST /v1/audio/speech`       | **异步** — 结构与视频相同。                             |
| `POST /v1/audio/generations`  | **异步** — 结构与视频相同。                             |

本页介绍视频和音频所使用的**异步流程**。

## 提交 → 轮询模式

1. `POST /v1/videos/generations`（或 `/v1/audio/*`）会立即返回 `{ id, status: "pending" }`。
2. `GET /v1/videos/generations/{id}`（或 `/v1/audio/generations/{id}`）返回同一对象，并带有更新后的 `status`。当 `status == "success"` 时，`data[].url` 会被填充。

```
pending  ──►  success
         ╲
          ╲►  failed
```

| `status`  | Meaning               |
| --------- | --------------------- |
| `pending` | 任务正在排队或生成中            |
| `success` | 生成完成；`data[].url` 已填充 |
| `failed`  | 生成失败                  |

## 方案 1 — 轮询

反复调用 GET 端点，直到状态进入终态。

<CodeGroup>
  ```bash cURL theme={null}
  curl https://vibetoken.cn/v1/videos/generations/f47ac10b-58cc-4372-a567-0e02b2c3d479 \
    -H "Authorization: Bearer sk-rb-xxxxxxxxxxxx"
  ```

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

  def wait_for_video(gen_id, api_key, interval=3, timeout=600):
      headers = {"Authorization": f"Bearer {api_key}"}
      url = f"https://vibetoken.cn/v1/videos/generations/{gen_id}"
      elapsed = 0
      while elapsed < timeout:
          s = requests.get(url, headers=headers).json()
          if s["status"] == "success":
              return s["data"][0]["url"]
          if s["status"] == "failed":
              raise RuntimeError("Generation failed")
          time.sleep(interval)
          elapsed += interval
      raise TimeoutError("Generation timed out")
  ```

  ```javascript JavaScript theme={null}
  async function waitForVideo(genId, apiKey, { interval = 3000, timeout = 600000 } = {}) {
    const url = `https://vibetoken.cn/v1/videos/generations/${genId}`;
    const start = Date.now();
    while (Date.now() - start < timeout) {
      const r = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } });
      const s = await r.json();
      if (s.status === "success") return s.data[0].url;
      if (s.status === "failed") throw new Error("Generation failed");
      await new Promise((r) => setTimeout(r, interval));
    }
    throw new Error("Generation timed out");
  }
  ```
</CodeGroup>

**推荐轮询频率：** 每 3–5 秒一次。大多数视频生成会在 1–5 分钟内完成。

## 方案 2 — 回调 URL

在你的 `POST` 请求中包含 `callback_url`，即可跳过轮询。任务完成后，VibeToken 会将最终结果 `POST` 到该 URL。

```bash theme={null}
curl -X POST https://vibetoken.cn/v1/videos/generations \
  -H "Authorization: Bearer sk-rb-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "bytedance/seedance-2-0",
    "prompt": "A sunset over the ocean",
    "callback_url": "https://your-app.example.com/webhooks/routerbase"
  }'
```

### 回调请求体

成功：

```json theme={null}
{
  "task_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "status": "success",
  "result_urls": ["https://media.vibetoken.cn/media/<user>/<gen>/0.mp4"],
  "error_message": null
}
```

失败：

```json theme={null}
{
  "task_id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "status": "fail",
  "result_urls": [],
  "error_message": "Generation failed: …"
}
```

### 回调安全

* 在生产环境中，你的 `callback_url` **必须使用 HTTPS**。
* 内部 / 私有网络 URL（`localhost`、`127.0.0.1`、`10.0.0.0/8`、`192.168.0.0/16`、`172.16.0.0/12`、云元数据 IP）会被阻止，以防止 SSRF。
* 回调采用 fire-and-forget 方式：目前没有自动重试，因此请确保你的 webhook 处理程序具有幂等性。

<Tip>
  回调可以省去轮询的需要，并降低视频生成这类长耗时任务（通常 1–5 分钟）的延迟。
</Tip>

## 结果 URL

当配置了 R2 存储时，VibeToken 会将上游 provider 的 URL 重新托管在自己的 CDN 上——链接不会过期。当未配置 R2 时，你会直接收到上游 provider 的临时 URL（这类 URL 会过期，通常在 24 小时内失效）。

## 典型生成耗时

| Modality | Typical Time |
| -------- | ------------ |
| 对话 / LLM | 2–30 秒（同步）   |
| 图片生成     | 10–60 秒（同步）  |
| 视频生成     | 1–5 分钟（异步）   |
| 音频 TTS   | 5–30 秒（异步）   |

耗时因模型和 provider 负载而异。
