Skip to content

Waiting and polling

A generation is final when its status is completed, failed or canceled. There are three ways to get there.

Send Prefer: wait=N, with N up to 60, on POST /v1/generations or GET /v1/generations/{id}. The response is held until the generation is final or N seconds pass. Either way the answer is the generation, with Preference-Applied: wait=N.

When the status is not final, poll_after_seconds suggests how long to wait before reading it again. Combine both: read with Prefer: wait=60, and if it is still not final, wait poll_after_seconds and read again.

start-and-poll.ts
// Starts a generation, then reads it until it is final, with fetch only. Spends at most 100 tokens.
// Run it with Node 22.18 or later (`node start-and-poll.ts`) or `npx tsx start-and-poll.ts`.
const API = process.env.HL_API_BASE ?? 'https://api.halationlab.ai/v1';
const auth = { Authorization: `Bearer ${process.env.HALATIONLAB_API_KEY}` };
const FINAL = ['completed', 'failed', 'canceled'];
async function api(path: string, init: RequestInit = {}) {
const res = await fetch(`${API}${path}`, { ...init, headers: { ...auth, 'Content-Type': 'application/json', ...init.headers } });
const body = await res.json();
if (!res.ok) throw new Error(`${res.status} ${body.error.code}: ${body.error.message} (${body.error.request_id})`);
return body;
}
// Prefer: wait=60 holds the response until the generation is final or 60 seconds pass.
let generation = await api('/generations', {
method: 'POST',
headers: { 'Idempotency-Key': crypto.randomUUID(), Prefer: 'wait=60' },
body: JSON.stringify({ model: 'flux.2-pro', input: { prompt: 'A red ceramic mug on a linen tablecloth' }, max_cost: 100 }),
});
// Not final yet: wait the suggested time, then read it again (each read can also wait up to 60 seconds).
while (!FINAL.includes(generation.status)) {
await new Promise(resolve => setTimeout(resolve, (generation.poll_after_seconds ?? 5) * 1000));
generation = await api(`/generations/${generation.id}`, { headers: { Prefer: 'wait=60' } });
}
console.log(generation.id, generation.status, `charged ${generation.cost.charged} of at most ${generation.cost.quoted_max} tokens`);
for (const output of generation.outputs) console.log(output.type, output.url);
export {};

The same loop for an existing generation, in Python with the standard library:

poll.py
# Reads a generation until it is final, using only the standard library. Reading is free.
# Usage: HL_GENERATION_ID=gen_... python3 poll.py
import json
import os
import time
import urllib.request
API = os.environ.get("HL_API_BASE", "https://api.halationlab.ai/v1")
KEY = os.environ["HALATIONLAB_API_KEY"]
FINAL = {"completed", "failed", "canceled"}
def get_generation(generation_id: str) -> dict:
# Prefer: wait=60 holds the response until the generation is final or 60 seconds pass.
request = urllib.request.Request(
f"{API}/generations/{generation_id}",
headers={"Authorization": f"Bearer {KEY}", "Prefer": "wait=60"},
)
with urllib.request.urlopen(request, timeout=90) as response:
return json.load(response)
generation = get_generation(os.environ["HL_GENERATION_ID"])
while generation["status"] not in FINAL:
time.sleep(generation["poll_after_seconds"] or 5)
generation = get_generation(generation["id"])
print(generation["id"], generation["status"], generation["cost"])
for output in generation["outputs"]:
print(output["type"], output["url"])

The SDKs do this for you: hl.generations.run() in TypeScript and client.generations.run() in Python start a generation and return it once it is final.

Register a webhook endpoint and start generations without waiting. A generation.completed event carries the whole generation, outputs included, so no follow-up call is needed.

  • Keep polling slow: use poll_after_seconds, and never poll in a tight loop. Reads count towards the rate limit of 300 a minute.
  • Do not assume a generation failed because a request timed out. Read it again; its ID never changes, also when a failed attempt is retried automatically.
  • A failed generation has error.code and error.message, and is never charged.