orq.aiAdvent of RoutingDocs

Door 16 · still sealed

Hands off the wax, elf. This door opens on Dec 16.

-days--hours--min--sec

Rudolph is still polishing this one. Back to the calendar

Door 16 · Dec 16 Batches

Overnight letter sorting

Stop paying real-time prices for work nobody is waiting on: send thousands of requests as one JSONL file, run them at the provider's batch rates in a 24-hour window, and match every answer back to its request.

The late post has buried the sorting room to the rafters. Sprocket's sorter answers one letter per request, and the night shift can hear the pile growing.

  1. Sprocket

    The wishes come in by the sackful and my sorter answers them one by one. Now the provider is sending back 429s!

  2. Ledger

    And every one of them at real-time prices. I've been counting. Does any child read the reply before morning?

  3. Sprocket

    Well, no. So I'll open a thousand threads and get it over with!

  4. Ledger

    Threads are first-class postage, and you still get 429s. Send the sack as one JSONL file at batch rates, name-tagging each letter with a custom_id.

fileletters.jsonlcustom_id per lineupload/v2/filespurpose: batchorq.ai/v3/router/batchescompletion_window: 24hproviderProvider batch APIoutputresults.jsonlerrorserrors.jsonluploadfile IDrunsoutputerrors
  1. fileletters.jsonlcustom_id per line
  2. upload/v2/filespurpose: batch
  3. orq.ai/v3/router/batchescompletion_window: 24h
  4. providerProvider batch API
  5. outputresults.jsonl
    errorserrors.jsonl
The whole sack goes up as one file, runs on the provider's batch service, and comes back as two piles: answers in results, strays in errors.

How it works

Ledger’s fix is one file and one batch instead of thousands of calls. Batches run without the throughput limits of real-time requests, at the provider’s batch rates.

  1. Write a JSONL file. One request per line, each with a unique custom_id, "method": "POST", a url that matches the batch endpoint, and the request itself as body.
  2. Upload it. Send the file to the Files API with purpose set to FILE_PURPOSE_BATCH. The file ID it returns is your input_file_id.
  3. Create the batch. Your API key needs the batches permission. POST /v3/router/batches with the file ID, the endpoint, and completion_window: "24h". Every line is validated first. An invalid line rejects the whole file with 400 and names the line.
  4. Poll, then download. Retrieve the batch until status is completed, failed, cancelled or expired, then download the output file and, if you want it, the errors file.

The API is OpenAI-compatible: requests, batch objects, statuses and result files follow the OpenAI batch format.

Try it with curl

n=0
for wish in "A red bicycle" "A bag of candy canes"; do
  n=$((n + 1))
  jq -nc --arg id "letter-$n" --arg w "$wish" '{
    custom_id: $id, method: "POST",
    url: "/v1/chat/completions",
    body: {model: "openai/gpt-6-luna",
      messages: [{role: "user",
        content: ("Toys, books or sweets? One word: " + $w)}]}}'
done > letters.jsonl

FILE_ID=$(curl -s -X POST https://my.orq.ai/v2/files \
  -H "Authorization: Bearer $ORQ_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"filename\": \"letters.jsonl\",
    \"content\": \"$(base64 < letters.jsonl | tr -d '\n')\",
    \"content_type\": \"application/jsonl\",
    \"purpose\": \"FILE_PURPOSE_BATCH\"
  }" | jq -er '.file.file_id')
export FILE_ID
echo "$FILE_ID"

The upload answers with the file object under file; file.file_id is your input_file_id. Then start the batch:

BATCH_ID=$(curl -s -X POST https://my.orq.ai/v3/router/batches \
  -H "Authorization: Bearer $ORQ_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "input_file_id": "'"$FILE_ID"'",
    "endpoint": "/v1/chat/completions",
    "completion_window": "24h"
  }' | jq -r .id)

Poll until status is completed, failed, cancelled or expired, then download the results, and the errors if request_counts.failed is above zero:

curl https://my.orq.ai/v3/router/batches/$BATCH_ID \
  -H "Authorization: Bearer $ORQ_API_KEY"

curl https://my.orq.ai/v3/router/batches/$BATCH_ID/results \
  -H "Authorization: Bearer $ORQ_API_KEY" -o results.jsonl

curl "https://my.orq.ai/v3/router/batches/$BATCH_ID/results?file=errors" \
  -H "Authorization: Bearer $ORQ_API_KEY" -o errors.jsonl

A batch with no failed lines has no errors file: that second call answers 409 output_unavailable.

From the terminal: orq batches create --input-file-id "$FILE_ID" --endpoint /v1/chat/completions --completion-window 24h, then orq batches retrieve <batch-id>.

Or from the OpenAI SDK

Upload with the Orq Files API as above, then create and poll with the OpenAI SDK:

import os
import time
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["ORQ_API_KEY"],
    base_url="https://my.orq.ai/v3/router",
)

batch = client.batches.create(
    input_file_id=os.environ["FILE_ID"],
    endpoint="/v1/chat/completions",
    completion_window="24h",
)
done = ("completed", "failed", "cancelled", "expired")
while batch.status not in done:
    time.sleep(60)
    batch = client.batches.retrieve(batch.id)
print(batch.status, batch.request_counts)

Download with GET /v3/router/batches/{batch_id}/results. Add ?file=errors for the failed and unexecuted lines.

Limits

Limit Value
File size 100 MiB
Lines per batch 99,999
Line size 20 MiB
Completion window 24h

Supported endpoints are /v1/responses, /v1/chat/completions, /v1/embeddings, /v1/completions, /v1/moderations and /v3/router/decisions. Send the last two with the HTTP API: the OpenAI SDK types do not declare them. Each model must declare batch support for the endpoint. /v3/router/decisions batches run on Orq.ai workers instead of a provider batch API: each line is traced and billed like a single request, and budgets are checked per line.

Expired and cancelled batches

Lines that ran are kept in the output file. Lines that did not run within the 24-hour window appear in the errors file with batch_expired. After a cancel, lines that had not started appear there too. You are billed for the lines the provider reports as run.

Nice list

  • A unique custom_id on every line. It is echoed on each result line, so join your answers on it.
  • A model that declares batch support for your endpoint. openai/gpt-6-luna, anthropic/claude-sonnet-5-5 and google/gemini-4-neon all do.
  • Check request_counts.failed even when the status is completed. Lines that fail on their own leave the batch completed.
  • Batches for work nobody is waiting on: a backlog, a nightly job, embeddings for a whole collection.

Naughty list

  • Putting azure/gpt-6-sol in a batch line. Azure is not a batch provider and the model does not declare batch support, so the create fails with model does not support batch API.
  • Mixing openai/ and anthropic/ models in one file. The create fails with 400: mixed providers in one batch are not supported.
  • Downloading results while the batch is still in_progress. Downloads open at a terminal state; earlier requests get 409 invalid_request.
  • Batching a request a user is waiting on. The only completion window is 24h, so make a real-time call instead.

Elf's challenge

Give two letters the same name tag: upload a two-line file where both lines use the custom_id letter-1, then create a batch from it. What status comes back, and what does the error say?

Stuck? Ask Ledger for a hint

Every line is checked before the batch is created. Expect 400 and the message duplicate custom_id "letter-1" at line 2.

Christmas crackerWhat does a letter that misses the 24-hour window say?Pull it for the punchline

Return to sender: batch_expired.