Skip to content
AgenticAIWiki
  1. Learn
  2. Part 2
  3. 14. Structured output
  4. 14.5

Lesson 14.5 · 5 of 8 · 5 min read · Reviewed 24 Nov 2026

Batch extraction at scale

By the end, you can

  • Plan structured extraction over thousands of documents.
  • Use Message Batches, sampling and monitoring at scale.

Extraction at scale adds cost, throughputThroughput: How much work a system completes per unit of time, such as requests per second or tokens per minute. and quality control to the picture.

Use Message Batches

The Message Batches APIMessage Batches: An asynchronous API for submitting many requests at once, processed at a discount, with results collected later. takes many requests at once, processes them asynchronously (most finish well within 24 hours) and costs less than real-time calls. It’s ideal when nobody is waiting for each result. Combine it with prompt cachingPrompt caching: Reusing the processed form of a repeated prompt prefix across requests, which cuts cost and latency. for the shared system promptSystem prompt: Instructions passed in the top-level system field that set the model’s role, rules and context for the whole conversation. and schema.

Pilot first

  1. Take a representative sample, a few hundred documents, including messy ones.
  2. Run the extraction and check results against a hand-labelled set.
  3. Fix the prompt and schema. Repeat until accuracy is good enough.
  4. Only then run the full job.

Monitor the run

  • Validation failure rate, overall and per field. A spike on one field points at a schema or prompt problem.
  • Null rates per field. A sudden jump may mean a new document layout.
  • Spot checks: sample successful items for review too. Valid isn’t the same as correct.

Handle failures

Items that fail after retries go to a review queue with the error. Never drop them silently.

Key points

  • For large jobs that don't need instant answers, the Message Batches API costs less and handles volume.
  • Run a pilot on a sample first and check accuracy before the full run.
  • Track failure rates by field and send failures to review instead of silently dropping them.
Hands-on labRuns in the Playground

Monitor a batch run field by field

Spot a field-level problem in a large extraction run that the overall failure rate hides.

You will have: A per-field report of failure and null rates for a simulated 2,000-document run, with spikes flagged.

Steps

  1. Run the starter: it simulates 2,000 extraction results with a seeded generator, where a new supplier layout appears halfway.
  2. Complete field_rates so it returns the null rate and failure rate for each field, for a slice of results.
  3. Compare the first and second half of the run and flag any field whose null rate rises by more than 10 points.
  4. Print the report and note which field to investigate.

Done when

  • The overall failure rate changes by only a few points between halves.
  • delivery_date is flagged with a null rate jump of well over 10 points.
  • The script prints 'investigate: delivery_date'.

Open in the Playground No API key needed.

Starter code (Python)
import random

rng = random.Random(7)
FIELDS = ["supplier", "total", "delivery_date"]

def simulate(i):
    new_layout = i >= 1000 and rng.random() < 0.35
    row = {}
    for f in FIELDS:
        r = rng.random()
        if f == "delivery_date" and new_layout:
            row[f] = None
        elif r < 0.02:
            row[f] = None
        elif r < 0.04:
            row[f] = "INVALID"
        else:
            row[f] = "ok"
    return row

RESULTS = [simulate(i) for i in range(2000)]

def field_rates(rows):
    # TODO: return {field: (null_rate, fail_rate)} where fail means the value is "INVALID".
    return {f: (0.0, 0.0) for f in FIELDS}

first, second = field_rates(RESULTS[:1000]), field_rates(RESULTS[1000:])
print(f"{'field':14} {'nulls 1st':>9} {'nulls 2nd':>9}")
flagged = []
for f in FIELDS:
    n1, n2 = first[f][0], second[f][0]
    # TODO: flag the field if n2 - n1 > 0.10
    print(f"{f:14} {n1:9.1%} {n2:9.1%}")
print("investigate:", ", ".join(flagged) or "nothing")
Show a solution
import random

rng = random.Random(7)
FIELDS = ["supplier", "total", "delivery_date"]

def simulate(i):
    new_layout = i >= 1000 and rng.random() < 0.35
    row = {}
    for f in FIELDS:
        r = rng.random()
        if f == "delivery_date" and new_layout:
            row[f] = None
        elif r < 0.02:
            row[f] = None
        elif r < 0.04:
            row[f] = "INVALID"
        else:
            row[f] = "ok"
    return row

RESULTS = [simulate(i) for i in range(2000)]

def field_rates(rows):
    out = {}
    for f in FIELDS:
        nulls = sum(1 for r in rows if r[f] is None)
        fails = sum(1 for r in rows if r[f] == "INVALID")
        out[f] = (nulls / len(rows), fails / len(rows))
    return out

def any_fail(rows):
    return sum(1 for r in rows if "INVALID" in r.values()) / len(rows)

first, second = field_rates(RESULTS[:1000]), field_rates(RESULTS[1000:])
print(f"overall failure rate: {any_fail(RESULTS[:1000]):.1%} then {any_fail(RESULTS[1000:]):.1%}")
print(f"{'field':14} {'nulls 1st':>9} {'nulls 2nd':>9}")
flagged = []
for f in FIELDS:
    n1, n2 = first[f][0], second[f][0]
    if n2 - n1 > 0.10:
        flagged.append(f)
    print(f"{f:14} {n1:9.1%} {n2:9.1%}")
print("investigate:", ", ".join(flagged) or "nothing")
Quick checkYou must extract fields from 200,000 invoices by next week. What's the best first step?
How sure are you?
Pick an answer and how sure you are