跳到正文

API 文档 · 任务

幂等

Idempotency-Key 的语义与重试方式。

创建任务必须带 Idempotency-Key 请求头,最长 128 字符(缺少或超长时返回 400 invalid_request)。建议使用你业务侧的唯一 ID,例如订单号加版本。

  • 同一个键、同样的请求体:返回 202 和第一次创建的任务(当前状态),并带响应头 Idempotent-Replayed: true,不会重复冻结或扣费。
  • 同一个键、不同的请求体:返回 409 idempotency_conflict。
  • 幂等键保留 30 天,按账号隔离:同一账号下不同 Key 共享同一幂等空间。

遇到网络超时、5xx 或 internal_error 时,带同一个键重试即可。想重新生成(例如换提示词),请使用新的键。

Node.js
// 业务侧唯一 ID 作为幂等键:超时重试不会重复建任务
async function submit(order) {
  const key = `order-${order.id}-v${order.revision}`;
  for (let attempt = 0; attempt < 5; attempt++) {
    try {
      const res = await fetch("https://cn-api.aitoken.tools/v1/videos/generations", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.AITOKEN_API_KEY}`,
          "Idempotency-Key": key,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(order.payload),
      });
      if (res.status < 500 && res.status !== 429) return res.json();
    } catch {
      // 网络错误:继续用同一个 key 重试
    }
    await new Promise((r) => setTimeout(r, 2 ** attempt * 1000 + Math.random() * 500));
  }
  throw new Error("submit failed");
}