Lab: An Extraction Pipeline With a Nullable Schema, Validation-Retry, a 100-Request Batch and Human Review
A hands-on lab that joins four stations into one pipeline for supplier documents: a record_document tool schema, a validate-and-retry loop, a 100-request batch matched by custom_id, and confidence routing with accuracy by type and field. Every output comes from running the project with a stand-in model.
What you will learn
- Design one tool schema with required, nullable, enum-with-other and per-field confidence that every later station relies on
- Wire validation and a retry that sends the document, the failed output and the exact errors, and stops on absent information
- Run 100 documents as one batch matched by custom_id, resend only the failures, chunk what was too long and check the SLA sum
- Route weak fields to a person and report accuracy by document type and field
Before you start
- Content boundaries and schema design for Claude
- Validation-retry loops for Claude extraction
- Claude Message Batches or real time
A hundred supplier documents arrive: invoices, emails, receipts. Somebody has to read each one and fill in a record, and you want to be able to trust every record. In this lab we build the whole pipeline, file by file, and run it.
Each station has its own article. Here the focus is how they join: what one station hands to the next, and why a decision made in the schema shows up again in the review queue.
Four stations
The project runs with a stand-in model: the real Anthropic SDK talks to a mock transport that answers like the Messages API, so no API key is needed. It imitates the model; it is not the model. The checks, the batch logic and the routing are real code. All the figures in the data/ folder are made-up sample results, and so are two numbers we'll meet later: the 60-hour promise and the 0.80 threshold.
Station 1: one schema that lets a document say less
Think of a paper form. One version forces an answer in "Due in ___ days", so the clerk writes 30 to fill the gap. A tidy form with an invented answer. Another version has a "not stated" box, and the clerk ticks it. Our schema is the second form, plus a line where the clerk writes how sure they are.
"""The extraction tool: one JSON schema that lets a document say less."""
CATEGORIES = ["office", "cleaning", "food", "equipment", "other"]
FIELDS = ["supplier", "invoice_no", "total", "due_in_days", "category"]
CONFIDENCE = {
"type": "object",
"properties": {f: {"type": "number", "minimum": 0, "maximum": 1}
for f in FIELDS},
"required": FIELDS,
}
EXTRACT_TOOL = {
"name": "record_document",
"description": (
"Record the details of one supplier document. Use null for "
"any detail the document does not state. Never guess a value. "
"Give a confidence from 0 to 1 for every field."),
"input_schema": {
"type": "object",
"properties": {
"supplier": {"type": "string"},
"invoice_no": {"type": ["string", "null"]},
"total": {"type": "number"},
"due_in_days": {"type": ["integer", "null"]},
"category": {"enum": CATEGORIES},
"category_detail": {"type": ["string", "null"]},
"confidence": CONFIDENCE,
},
"required": ["supplier", "total", "category", "confidence"],
},
}
MODEL = "claude-haiku-5-5"
TOOL_CHOICE = {"type": "tool", "name": "record_document"}
- Required: only what every document has. Supplier, total, category, and the confidence object.
- Nullable:
invoice_noanddue_in_daysare "string or null" and "integer or null", and not required. An email with no invoice number can say so. - Enum with other: the category list ends with
other, andcategory_detailsays what "other" means. - Field confidence: a number from 0 to 1 for every field. Station 4 reads it.
Why null matters, and why the enum gets an escape hatch, is covered in content boundaries and schema design. Why a tool schema beats asking for JSON in prose is in defensive parsing of Claude replies.
About the forced tool choice. TOOL_CHOICE forces the model to answer through record_document, and the project runs it on claude-haiku-5-5. Some of the newest models reject a forced tool choice. On those, use "auto" with strict tool use, or structured outputs, as the Claude docs page "Define tools" describes.
The system prompt in prompts/extraction_prompt.txt repeats the rules and adds two examples, one for each shape a document comes in. The second one is the important one:
<example>
document (a narrative email):
"Thanks for your order. The mops come to 40.00 altogether.
Pay when convenient. Clean Co"
answer: supplier Clean Co, invoice_no null, total 40.00,
due_in_days null, category cleaning, confidence 0.5 on due_in_days
because the email gives no number of days
</example>
It shows the pattern including the null and the doubt. The first example is a table invoice with "Due in 14 days" written plainly.
Station 2: validate, then retry only what a retry can fix
The schema guarantees the shape. It can't stop a total from arriving as the text "$110.00". That's the job of validate.py, plain Python with no model:
def problem(field, kind, message):
return {"field": field, "kind": kind, "message": message}
def check(data):
"""Return a list of problems. An empty list means clean."""
errors = []
total = data["total"]
if isinstance(total, bool) or not isinstance(total, (int, float)):
errors.append(problem(
"total", "format", f'total "{total}" must be a number'))
due = data.get("due_in_days")
if due is not None and (isinstance(due, bool)
or not isinstance(due, int)):
errors.append(problem(
"due_in_days", "format",
f'due_in_days "{due}" must be a whole number or null'))
if not data["supplier"].strip():
errors.append(problem(
"supplier", "absent",
"supplier is empty: not in this document"))
return errors
Notice the join with station 1: a None in due_in_days passes. The schema allowed null, so the check treats null as a correct answer, not an error. Every problem has a kind, and extract.py uses it to decide what happens next:
RETRYABLE = ("format",)
def retry_message(doc, failed, errors):
"""The follow-up: document + failed output + specific errors."""
lines = "\n".join(f"- {e['message']}" for e in errors)
return (f"DOCUMENT:\n{doc}\n\n"
f"YOUR LAST EXTRACTION:\n{json.dumps(failed)}\n\n"
f"PROBLEMS FOUND:\n{lines}\n"
"Fix only these problems. Use null if it is not stated.")
def run(client, name, max_tries=3):
doc = (ROOT / "docs" / f"{name}.txt").read_text()
content = doc
for attempt in range(1, max_tries + 1):
data = call(client, content)
errors = check(data)
word = f"{len(errors)} problem" if errors else "clean"
print(f"{name} try {attempt}: {word}"
+ ("s" if len(errors) > 1 else ""))
for e in errors:
print(f" [{e['kind']}] {e['message']}")
if not errors:
kept = [k for k in ("invoice_no", "due_in_days")
if data.get(k) is None]
if kept:
print(" kept as null:", ", ".join(kept))
return "saved"
if any(e["kind"] not in RETRYABLE for e in errors):
print(f"{name} STOP: a retry cannot fix absent "
"information")
return "review"
content = retry_message(doc, data, errors)
return "review"
Four sample documents go through. Running python extract.py from the pipeline folder:
doc_A try 1: clean
doc_B try 1: clean
kept as null: invoice_no, due_in_days
doc_C try 1: 2 problems
[format] total "$110.00" must be a number
[format] due_in_days "30 days" must be a whole number or null
doc_C try 2: clean
doc_D try 1: 1 problem
[absent] supplier is empty: not in this document
doc_D STOP: a retry cannot fix absent information
saved 3, human review 1
- doc_A is a neat invoice. Clean on the first try.
- doc_B is an email from Greenleaf Supplies with no invoice number and no due date. Both stay null, and the check is happy.
- doc_C has a total with a dollar sign and days written as text. One retry with those two exact errors, and it comes back clean.
- doc_D is "Page 2 of 2" with no supplier name. A retry can't invent what the page doesn't say, so it goes to a person.
The reasoning behind the retry message and the stop rule is in validation-retry loops: what a retry cannot fix.
Station 3: a batch of 100, matched by custom_id
Four documents fit in a loop. A hundred that nobody waits on belong in the Message Batches API. Each request is the same call as before, wrapped with a custom_id:
CHUNK = 30
LINES = {"doc-0042": 90, "doc-0063": 50} # the two long documents
def make_request(n, text):
return {"custom_id": f"doc-{n:04d}",
"params": {"model": MODEL, "max_tokens": 1024,
"system": PROMPT, "tools": [EXTRACT_TOOL],
"tool_choice": TOOL_CHOICE,
"messages": [{"role": "user", "content": text}]}}
def failures(rows):
"""custom_id -> why, for every result that did not succeed."""
bad = {}
for row in rows:
res = row["result"]
if res["type"] == "errored":
bad[row["custom_id"]] = res["error"]["error"]["message"]
elif res["type"] != "succeeded":
bad[row["custom_id"]] = res["type"]
return bad
def plan(bad):
"""What to send again: chunk what was too long, resend the rest."""
todo = {}
for cid, why in sorted(bad.items()):
if "too long" in why:
parts = -(-LINES[cid] // CHUNK)
todo[cid] = [f"{cid}-p{k}" for k in range(1, parts + 1)]
else:
todo[cid] = [cid]
return todo
def submit_every(promise, window=24, passes=2):
"""Hours a document may wait for the next batch to be sent."""
return promise - window * passes
The join here: params uses the same EXTRACT_TOOL, PROMPT and TOOL_CHOICE as station 2, so a batched answer has exactly the same shape as a single call and goes through the same checks. The results file doesn't come back in request order (in the sample file, the first line is doc-0031), so everything is found by custom_id. In the project the submit call is a comment; the results are read from data/results_sample.jsonl.
Running python batch.py:
100 requests in one batch
doc-0001 to doc-0100
100 results read, matched by custom_id
96 succeeded, 3 errored, 1 expired
doc-0017 -> internal server error
doc-0042 -> prompt is too long
doc-0063 -> prompt is too long
doc-0088 -> expired
resend 4 documents as 7 requests:
doc-0017 as it was
doc-0042 in 3 chunks: doc-0042-p1 .. doc-0042-p3
doc-0063 in 2 chunks: doc-0063-p1 .. doc-0063-p2
doc-0088 as it was
SLA promise: 60 h
first pass 24 h + resend pass 24 h = 48 h
wait for the next batch: 60 - 48 = 12 h
submit a batch every 12 h
The 96 that worked are not sent again. Of the four failures, the server error and the expired request go again exactly as they were. The two that were too long are split into chunks of 30 lines with new ids: doc-0042 has 90 lines, so three chunks; doc-0063 has 50, so two. That makes 7 requests for 4 documents.
The SLA sum
The 60-hour promise is the project's own made-up number. The 24 hours is from the Claude docs on batch processing: a batch can take up to 24 hours. Planning for two full windows, one for the first pass and one for the resend, leaves 12 hours, so a document should never wait longer than that for the next batch to go out. Choosing batches over real time in the first place is covered in Claude Message Batches or real time.
Station 4: route by confidence, check by segment
The confidence object from station 1 now does its job. review.py reads the 96 successful extractions from the batch results and routes each one:
THRESHOLD = 0.80
FIELDS = ["supplier", "total", "due_in_days", "category"]
def route(data):
"""Save automatically, or send to a person with the weak fields."""
weak = {f: c for f, c in data["confidence"].items()
if c < THRESHOLD}
return ("review", weak) if weak else ("auto", {})
def accuracy(rows):
"""(doc_type, field) -> [correct, checked]."""
cells = defaultdict(lambda: [0, 0])
for r in rows:
cell = cells[(r["doc_type"], r["field"])]
cell[0] += r["correct"]
cell[1] += 1
return cells
If any field is below 0.80, the whole extraction goes to a person with the weak fields attached, so the reviewer knows where to look. The 0.80 is the project's own number; tune it to what a mistake costs you, and pick it from labelled data as shown in human review and confidence calibration. The second function counts a human-checked sample by document type and field.
Running python review.py:
96 extractions read
saved automatically 73, to human review 23
doc-0001 -> review: category 0.78
doc-0007 -> review: due_in_days 0.72
doc-0012 -> review: category 0.77
checked sample: accuracy by type and field
type supplier total due_in_days category
invoice 98% 98% 95% 95%
email 97% 93% 70% 90%
receipt 100% 95% 95% 90%
all together: 93%
weakest: email / due_in_days at 70%
73 saved, 23 to a person, each with its weak field and score. Then the checked sample: 93% all together looks safe to ship. Split by type and field, one cell is at 70%: emails, due_in_days.
That cell connects straight back to station 1. Emails are the narrative documents where the due date hides in a sentence, or isn't there at all. The fix isn't to hide the cell inside the average. Send that cell to review, add a prompt example for the email patterns that go wrong, and measure again.
How the stations depend on each other
| Decided in | Used in | What breaks without it |
|---|---|---|
Schema: nullable due_in_days | Validate: null passes | The model guesses 30, or the check retries a value that isn't there |
Validate: kind on every problem | Extract: retry or stop | doc_D would burn three tries and still have no supplier |
| Same tool, prompt and tool choice | Batch params | Batched answers have a different shape from single calls |
Batch: custom_id | Failures, resend, review | Results arrive out of order and can't be matched |
| Schema: field confidence | Review: route() | No way to say which field a person should check |
Common mistakes
- Making every field required. The model fills the gap with a guess, and validation has nothing to catch.
- Retrying absent information. A format slip can be fixed; a missing supplier can't.
- Matching batch results by position. Always use
custom_id. - Resending the whole batch. Send only the failures, and chunk the ones that were too long instead of resending them unchanged.
- Planning for the typical batch time. Plan for the full window, twice if you resend.
- Trusting one accuracy number. 93% overall hid emails at 70% on due_in_days.
Recap
| Station | File | In the run |
|---|---|---|
| Schema | schema.py | doc_B keeps invoice_no and due_in_days as null |
| Validate and retry | validate.py, extract.py | doc_C fixed on try 2; doc_D stopped: saved 3, human review 1 |
| Batch | batch.py | 96 succeeded; 4 documents resent as 7 requests; submit every 12 h |
| Review | review.py | 73 saved, 23 to review; weakest email / due_in_days at 70% |
On the exam, pick the answer that keeps null honest, retries only what a retry can fix, matches batch results by custom_id, and sends doubt to a person.
Try it yourself
Change CHUNK in batch.py to 25 and predict how many requests the resend needs before you run it. Then raise THRESHOLD in review.py to 0.90 and watch how the split between saved and human review moves.
Related course on Udemy
Claude Certified Architect - Foundations (CCAR-F) Exam Prep
Agentic loops, tools, MCP, Claude Code, prompts, structured output and context.View on Udemy ↗: Claude Certified Architect - Foundations (CCAR-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
