Errors
Every error has the same shape and a matching HTTP status:
{ "error": { "type": "invalid_request_error", "code": "parameter_invalid", "message": "`duration` must be between 4 and 15 seconds.", "param": "input.duration", "doc_url": "https://docs.halationlab.ai/errors/parameter-invalid/", "request_id": "req_01JD3Y5RJ6M3XW6J8K2N4P7Q9T" }}| Field | Meaning |
|---|---|
type |
The kind of error. Use it for broad handling. |
code |
A stable, specific code. It never changes meaning. Each has a page. |
message |
A human-readable explanation, safe to show to a developer. Do not parse it. |
param |
The parameter at fault, such as input.duration, or null. |
doc_url |
The page for this code. |
request_id |
The request’s ID, also sent as the Request-Id header. Quote it to support. |
retry_after |
Seconds to wait before retrying. Present only when retrying can succeed; also the Retry-After header. |
manage_url |
A page where the account owner can fix the cause, such as a spending limit or consent. |
errors |
Every problem, when there was more than one, each with param, code and message. |
details |
Extra facts. max_cost_exceeded carries the quote. |
Types and statuses
Section titled “Types and statuses”| Type | Status | Meaning |
|---|---|---|
invalid_request_error |
400, 405, 413, 415, 422 | Bad JSON (400), wrong method (405), a body over 1 MiB (413), an unsupported file type (415), or validation (422, with param). |
authentication_error |
401 | The credential is missing or not valid. |
payment_required_error |
402 | Money: balance, spending limit or max_cost. |
permission_error |
403, 410 | The credential may not do this, or access was withdrawn. |
not_found_error |
404 | No such object, or the credential cannot see it. The two look the same. |
conflict_error |
409 | The request conflicts with the current state, such as an expired quote. |
idempotency_error |
409 | An Idempotency-Key problem. See Idempotency. |
rate_limit_error |
429 | Too many requests. Only rate limits use 429. |
api_error |
500, 503 | A problem on our side, or a model or service is unavailable. |
The error codes page lists every code.
Handle errors
Section titled “Handle errors”- Branch on
codefor the cases you handle specifically, and ontypefor the rest. - Retry only when the response has
Retry-After(andretry_after), after that many seconds, with the sameIdempotency-Keyand the identical body. - For
402and403refusals with amanage_url, show it to the account owner. Retrying does not help. - For
422, fix the parameter named inparam(and inerrors, when there are several). - Log
request_idfor anything you cannot handle.
// A request helper that handles errors by their stable `code`: it retries only what can succeed later, with the// same Idempotency-Key, after Retry-After. Run it to see a 404 handled: `node handle-errors.ts` or `npx tsx handle-errors.ts`.const API = process.env.HL_API_BASE ?? 'https://api.halationlab.ai/v1';
type ApiError = { type: string; code: string; message: string; param: string | null; doc_url: string; request_id: string; retry_after?: number; manage_url?: string };
export class HalationLabApiError extends Error { constructor(readonly status: number, readonly error: ApiError) { super(`${error.code}: ${error.message}`); }}
export async function call(method: string, path: string, body?: unknown, attempts = 5) { // One key for every attempt, so a retry never starts a second generation. const key = method === 'GET' ? undefined : crypto.randomUUID(); for (let attempt = 1; ; attempt++) { const res = await fetch(`${API}${path}`, { method, headers: { Authorization: `Bearer ${process.env.HALATIONLAB_API_KEY}`, 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}), }, body: body === undefined ? undefined : JSON.stringify(body), }); if (res.ok) return res.json(); const { error } = (await res.json()) as { error: ApiError }; // Retry-After is sent exactly when retrying can succeed: rate limits, in-progress or unknown outcomes, // media still being checked and temporary outages. const retryAfter = Number(res.headers.get('Retry-After') ?? error.retry_after); if (retryAfter > 0 && attempt < attempts) { await new Promise(resolve => setTimeout(resolve, retryAfter * 1000)); continue; } throw new HalationLabApiError(res.status, error); }}
if (import.meta.url === new URL(`file://${process.argv[1]}`).href) { try { await call('GET', '/models/not-a-model'); } catch (e) { if (!(e instanceof HalationLabApiError)) throw e; const { status, error } = e; console.log(status, error.type, error.code, error.doc_url, error.request_id); if (error.code !== 'model_not_found') process.exit(1); }}# A request helper that handles errors by their stable `code`: it retries only what can succeed later, with the# same Idempotency-Key, after Retry-After. Run it to see a 404 handled: python3 handle-errors.pyimport jsonimport osimport timeimport urllib.errorimport urllib.requestimport uuid
API = os.environ.get("HL_API_BASE", "https://api.halationlab.ai/v1")
class HalationLabApiError(Exception): def __init__(self, status: int, error: dict): super().__init__(f"{error['code']}: {error['message']}") self.status = status self.error = error
def call(method: str, path: str, body: dict | None = None, attempts: int = 5) -> dict: # One key for every attempt, so a retry never starts a second generation. headers = {"Authorization": f"Bearer {os.environ.get('HALATIONLAB_API_KEY', '')}", "Content-Type": "application/json"} if method != "GET": headers["Idempotency-Key"] = str(uuid.uuid4()) data = json.dumps(body).encode() if body is not None else None for attempt in range(1, attempts + 1): request = urllib.request.Request(f"{API}{path}", data=data, method=method, headers=headers) try: with urllib.request.urlopen(request, timeout=90) as response: return json.load(response) except urllib.error.HTTPError as e: error = json.load(e)["error"] # Retry-After is sent exactly when retrying can succeed. retry_after = int(e.headers.get("Retry-After") or error.get("retry_after") or 0) if retry_after > 0 and attempt < attempts: time.sleep(retry_after) continue raise HalationLabApiError(e.code, error) from None raise RuntimeError("unreachable")
if __name__ == "__main__": try: call("GET", "/models/not-a-model") except HalationLabApiError as e: print(e.status, e.error["type"], e.error["code"], e.error["doc_url"], e.error["request_id"]) if e.error["code"] != "model_not_found": raise SystemExit(1)Failed generations are not errors
Section titled “Failed generations are not errors”A generation that starts and then fails is not an error response: the start succeeded. The generation’s status becomes failed (or canceled), with error.code one of generation_failed, content_blocked, canceled, expired or input_rejected, and error.message. Failed work is never charged.