API docs · Tasks
Idempotency
How Idempotency-Key works and how to retry safely.
Task creation requires an Idempotency-Key header of up to 128 characters (requests without one, or with a longer one, return 400 invalid_request). Use a unique ID from your own system, such as an order number plus a revision.
- Same key, same body: returns 202 with the task created the first time (in its current state) and the response header
Idempotent-Replayed: true, with no second reservation or charge. - Same key, different body: returns 409
idempotency_conflict. - Keys are kept for 30 days and scoped to the account: all keys in the same account share one idempotency namespace.
On network timeouts, 5xx responses or internal_error, simply retry with the same key. To generate again (for example with a different prompt), use a new key.
Node.js
// Use your own unique business ID as the idempotency key: retries after a timeout never create a duplicate task
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 {
// Network error: retry with the same key
}
await new Promise((r) => setTimeout(r, 2 ** attempt * 1000 + Math.random() * 500));
}
throw new Error("submit failed");
}