Gouache painting of an empty coat-check room at night in violet and magenta: a wall of numbered hooks, mostly empty, with three coats and one glowing paper lantern hanging from them, and a service bell and a torn claim ticket on the wooden counter in front
All posts

Async LLM API: queue the request, get an ID, fetch the result later

AIVAX now queues chat, Responses, Messages, extraction, speech and other requests with one async field. What a finished item contains, and a Python pattern that collects results by tag.

A six-minute LLM request has to survive every timeout between the caller and the provider. Load balancers close idle connections, serverless functions have a maximum run time, and SDKs ship with their own limits: OpenAI's background mode guide raises the Ruby client to 30 minutes because an uncapped run "can run beyond the SDK's default ten minutes". A deploy that restarts the worker holding the socket has the same effect. The provider may finish the answer and have nobody left to deliver it to.

The common workaround is a job table. You write the request down, return an ID, let a worker make the call, store the result and let the caller come back for it. Since November 25, 2026, AIVAX keeps that table on its side: a supported request with an async field in its body is queued instead of executed, and its response is stored for 90 days after it finishes.

One field turns a call into a queued item

The request body is the one you already send. Add "async": true, or the object form when you want tags, webhooks or a shorter timeout:

{
  "model": "@openai/gpt-6-luna",
  "messages": [{ "role": "user", "content": "Summarize this report." }],
  "async": {
    "tags": ["nightly-2026-11-25", "doc-1"],
    "webhooks": ["https://example.com/hooks/async-generations"],
    "timeout": 600
  }
}

Nothing is generated while that request is open. AIVAX answers with HTTP 202 and an ID:

{
  "message": "The generation was queued.",
  "data": {
    "async_generation": {
      "id": "01a2141a-3110-761d-98cb-eb4230809d1c",
      "status": "pending"
    }
  }
}

The same field works on /v1/chat/completions, /v1/responses and /v1/messages, and on the extraction, summarization, translation, classification, segmentation, decision, reranking, image, speech, transcription, Agentic Test, web search and web fetch endpoints listed in the async generations docs. We think that breadth matters more than any single option. A Claude call in the Messages format, a PDF extraction and an audio transcription go through one queue, are found with one tag filter and are read back from one endpoint.

An item takes up to 16 tags and 4 webhook URLs. timeout applies to each attempt and accepts 10 to 3,600 seconds, with 3,600 as the default. A request that combines async with stream: true, a timeout below 10 seconds or a webhook URL that is not public is rejected with 400 before anything is queued. Public API keys, which are meant for browser code, cannot queue requests.

A finished item can hold an error

When an item runs, AIVAX sends the original request to the original endpoint and stores what came back: status code, content type, body and cost. GET /api/v1/async-generations/<id>/response returns that body with the original status code and content type. A chat completion comes back as a chat completion, and speech comes back as audio.

So done says the call ended. We queued a chat completion with a model name that does not exist, and the queue accepted it with 202, since the queue validates the async options and leaves the rest of the body to the endpoint. When the item ran, the chat endpoint rejected the model, and the item was marked done with a stored 400 and the usual "Couldn't resolve the model name" body. Read the stored status code before you use any result.

The docs say an attempt that fails with insufficient balance, a rate limit or a server error is retried up to three times before its last error is stored. Other outcomes are stored on the first attempt: 408 when the attempt runs past timeout, 507 when the response is larger than 12 MB, and 401 when the API key that queued the item was deleted before it ran.

Our recommendation is to set timeout near what the work needs. A one-page summary still running after ten minutes is unlikely to return something useful in the next fifty, and a shorter limit puts the 408 in your results earlier.

Unrun items are deleted 15 days after creation, cancelled items an hour after cancellation, and finished items 90 days after completion. You can cancel an item that is pending, retrying, or finished with an error, but not one that is running. Our short test requests started within a few seconds of being queued, so cancellation is mostly for a backlog you no longer want.

Tags are the record, and the webhook is a prompt to look

When an item finishes, each webhook URL receives a POST whose whole body is the ID and the status:

{ "id": "01a21414-85e2-7bed-8465-042deea6ea04", "status": "done" }

It carries no result, and each notice is sent once. We treat the list endpoint as the source of truth and the webhook as a reason to check it now, which also covers any notice your endpoint missed while it was down.

The list endpoint filters by tags and returns only items that carry all of the requested tags. Tag each item with its run and with your own key for the input, such as a document ID. One query then tells you which items in a run are finished, and another tells you whether a given document was already queued.

import os
import time

import requests
from openai import OpenAI

BASE = "https://inference.aivax.net"
KEY = os.environ["AIVAX_API_KEY"]
RUN = "nightly-2026-11-25"

client = OpenAI(base_url=f"{BASE}/v1", api_key=KEY)
api = requests.Session()
api.headers["Authorization"] = f"Bearer {KEY}"


def list_items(**params):
    items, offset = [], 0
    while True:
        page = api.get(
            f"{BASE}/api/v1/async-generations",
            params={**params, "limit": 100, "offset": offset},
        )
        page.raise_for_status()
        batch = page.json()["data"]
        items += batch
        if len(batch) < 100:
            return items
        offset += 100


def queue(doc_id, text):
    tags = f"{RUN},{doc_id}"
    failed = [i for i in list_items(tags=tags, status="done") if i["responseStatusCode"] != 200]
    for item in failed + list_items(tags=tags, status="cancelled"):
        api.delete(f"{BASE}/api/v1/async-generations/{item['id']}")
    if list_items(tags=tags):
        return

    raw = client.chat.completions.with_raw_response.create(
        model="@openai/gpt-6-luna",
        messages=[{"role": "user", "content": f"Summarize in one sentence:\n\n{text}"}],
        extra_body={"async": {"tags": [RUN, doc_id], "timeout": 600}},
    )
    print(doc_id, raw.http_response.status_code, raw.http_response.json()["data"])


def collect(doc_ids, give_up_after=1800):
    results, deadline = {}, time.time() + give_up_after
    while len(results) < len(doc_ids) and time.time() < deadline:
        for item in list_items(tags=RUN, status="done"):
            doc_id = next(tag for tag in item["tags"] if tag != RUN)
            if doc_id in results:
                continue

            stored = api.get(f"{BASE}/api/v1/async-generations/{item['id']}/response")
            if stored.status_code == 200:
                results[doc_id] = stored.json()["choices"][0]["message"]["content"]
            else:
                results[doc_id] = f"failed with {stored.status_code}: {stored.text[:200]}"
        time.sleep(10)
    return results


docs = {
    "doc-1": "The invoice service now retries failed card charges twice before marking an invoice unpaid.",
    "doc-2": "Support tickets tagged billing are routed to the finance queue during business hours.",
    "doc-3": "Exports older than 90 days are removed from storage every Sunday at 03:00 UTC.",
}
for doc_id, text in docs.items():
    queue(doc_id, text)

results = collect(list(docs))
for doc_id in docs:
    print(doc_id, "->", results.get(doc_id, "not finished yet"))

async goes in extra_body because the OpenAI SDK has no parameter for it, and the reply is read from the raw response because a 202 with a queue ID has none of the fields of a chat completion.

Running the script again is safe. queue deletes the document's stored failures and cancelled items, queues the document again, and skips documents that still have a pending, running or successful item. We forced one document to fail on the first run; the second run queued only that document, and a third run queued nothing. The check is a lookup and gives no lock, so two processes starting at the same moment can queue the same document twice. If a duplicate is expensive, claim the document ID in your own database before queuing, as in idempotent tool calls.

To call collect when something finishes instead of on a schedule, add a webhook handler. When the account has a hook key, AIVAX sends X-Request-Nonce, a bcrypt hash you check against that key as described under hook authentication. Set the hook key before you expose the URL. The handler below refuses requests without a valid nonce and fetches the result with its own API key, so a notification never supplies data, only an ID to look up.

import os

import bcrypt
import requests
from flask import Flask, abort, request

BASE = "https://inference.aivax.net"
API_KEY = os.environ["AIVAX_API_KEY"]
HOOK_KEY = os.environ["AIVAX_HOOK_SECRET"].encode()

app = Flask(__name__)


def save_result(generation_id, status_code, body):
    print("saved", generation_id, status_code, body[:120])


@app.post("/hooks/async-generations")
def generation_done():
    nonce = request.headers.get("X-Request-Nonce", "")
    try:
        trusted = bcrypt.checkpw(HOOK_KEY, nonce.encode())
    except ValueError:
        trusted = False
    if not trusted:
        abort(403)

    generation_id = request.get_json()["id"]
    stored = requests.get(
        f"{BASE}/api/v1/async-generations/{generation_id}/response",
        headers={"Authorization": f"Bearer {API_KEY}"},
        timeout=30,
    )
    save_result(generation_id, stored.status_code, stored.content)
    return "", 204

The try exists because bcrypt.checkpw raises ValueError when the header is not a bcrypt hash; without it, a malformed header produces a 500. Keep a slow polling loop next to the handler for notifications that were sent while it was down.

OpenAI, Gemini and Anthropic keep results for very different times

OpenAI and Google offer a background flag on one API each. Anthropic's asynchronous option is a batch API.

Asynchronous request options as documented on November 25, 2026
OptionHow you askWhat it coversHow long the result is keptHow you learn it finished
AIVAX async generationsasync in the bodyChat Completions, Responses, Messages and the data, media and web endpoints, for any model the account can route90 days after completionList by tag, or a webhook with the ID
OpenAI background modebackground: trueResponses APIRoughly 10 minutes on the default completion window, per data controlsPolling by response ID, or signed response.completed webhooks
Gemini background executionbackground: true, requires storeInteractions API55 days on the paid tier, 1 day on the free tierPolling or streaming the interaction
Anthropic Message BatchesA batch of requestsMessages requests submitted together29 days after the batch is createdPolling the batch

OpenAI's background mode is built around a single API. A background response can be streamed and resumed from a sequence number, and the 2h and 8h completion windows, in public beta on four models, trade a fixed wait for lower token prices.

Gemini's background execution targets agent runs and deep research and returns 400 if background is sent with store: false. Message Batches, which Anthropic prices at half the standard rate, is built for volume: most batches finish within an hour, and a batch still unfinished after 24 hours expires.

A queued call costs the same as the synchronous call. For work that can wait, the docs suggest combining the queue with cheaper routing, and each item's summary includes its cost, the same figure the Consumed-Credits header gives a synchronous call.

When to stream or use Batch instead

If someone is waiting on screen, stream. A queued item cannot stream and adds the time it waits to be picked up.

If you are applying one instruction to a list of inputs and want answer validation, retries of invalid answers and an export, a Batch workflow does that work for you. The post on batch admission control explains how it paces items.

Async generations cover independent calls, often of different kinds, from code that cannot hold a connection open: a nightly report, a transcription started from a form, an extraction after an upload. Each plan caps how many items can be queued per hour, from 1,000 on Free to 750,000 on Ultimate, as listed in the limits page.

We ran the examples against the live AIVAX API on November 25, 2026, with @openai/gpt-6-luna on a Max account. Queuing answered 202 in 180 to 500 ms, and a one-sentence chat completion was stored about 8 seconds after it was queued. Chat Completions, Responses, Messages and classification items stored 200 responses; the item with an unknown model stored 400. The collection script and the webhook handler were run against real stored items. Third-party behavior comes from the OpenAI, Google and Anthropic documentation as read the same day.