Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Claude
  • Claude.ai Interface Tour: Every Control You Need on One Screen
  • The AI Fluency Model: Delegation, Description, Discernment and Diligence
  • Working With Claude: Pick the Surface, Match the Model, Keep the Context Clear
  • Claude's Four Entry Points: Choose Chat, Projects, Artifacts or Research Before You Type
  • What Claude Can Do: Extended Thinking, Web Search, Artifacts and File Analysis
  • Getting More From a Claude Chat: Steer the Conversation Instead of Starting Over
  • Claude Research Mode End to End: From One Prompt to a Cited Briefing
  • Claude's Capability Layer: When to Use Skills, Code Execution or Memory
  • Code Execution and File Creation in Claude: Calculated Numbers and a Real Excel File
  • Adding and Using Skills in Claude: Let Claude Pick the Skill, Then Teach It Your Format
  • Claude Memory, Curation and Incognito: Keep What Helps, Remove What Has Gone Stale
  • Claude Styles, Preferences and Project Instructions: Three Dials, Three Scopes
  • Claude Projects: Knowledge, Instructions and a Real Workspace You Set Up Once
  • Keeping a Claude Project Current and Connected: Refresh, Prune and Grant the Least
  • Claude Scheduled Tasks: Let Claude Work on a Schedule and Email You the Result
  • Claude Code and Claude for Chrome: What They Are and Who They Are For
  • Anatomy of a Good Prompt: Role, Context, Task, Format and Examples
  • Shaping Claude's Output: Format, Tone and Length in a Few Words
  • Iterating and Refining a Prompt: Read, Diagnose, Adjust, Repeat
  • Five Prompting Patterns for Work: Summarise, Extract, Rewrite, Classify and Draft
  • Why Evaluating AI Output Matters Most: Trust, Then Verify
  • Spotting AI Hallucinations and Fabrications: Four Tells and Where Risk Spikes
  • Fact-Checking Claude's Answers: Four Techniques and a Line-by-Line Claim Log
  • Judging AI Output Quality: Four Questions That Score Any Answer
  • Adapting AI Output for Your Audience: One Answer, Three Readers
  • When a Human Must Review AI Output Before It Ships
  • A Personal Validation Checklist for AI Output: Six Lines, Any Draft
  • Fitting Claude Into Real Work: Where It Helps and Where It Never Should
  • Breaking Big Tasks Into Steps With Claude: Small Asks, Checked Hand-offs
  • Designing a Repeatable Claude Workflow: A Reusable Weekly Report Template
  • Measuring If Claude Is Actually Working: One Number, Before and After
  • Communicating AI Value and Limitations to Stakeholders: The Honest Pitch
  • Data Privacy With Claude: What Never Goes in a Prompt, and How to Redact a Document Before You Paste It
  • Responsible AI Use and Transparency: Helpful, Honest, Harmless, and One Honest Line
  • Troubleshooting a Weak Claude Answer: Name the Cause, Fix One Thing, Then Make It Cheaper
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Claude Code's Built-in Tools: Read, Write, Edit, Bash, Grep and Glob, and When Each One Is the Right Pick
  • The CLAUDE.md Hierarchy: User, Project and Directory Files, How They Stack, and the Team Rule Stuck on One Laptop
  • Split a 600-Line CLAUDE.md: @import Lines, .claude/rules Files and Which One to Pick
  • Path-Specific Rules in Claude Code: paths Globs, When a Rule Loads and the Glob That Matches Nothing
  • Claude Code Slash Commands and Skills: Project vs User Scope, $ARGUMENTS, context: fork and allowed-tools
  • Iterative Refinement with Claude Code: Input/Output Examples, Tests First and the Interview Pattern
  • Claude Code Sessions: Resume by Name, Fork From a Baseline, or Start Fresh With a Summary Card
  • CI Reviews That Don't Repeat Themselves: Prior Findings, Existing Tests and Test Standards in CLAUDE.md
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • Validation-Retry Loops for Claude Extraction: Send Back the Exact Errors, and Stop When a Retry Cannot Help
  • Multi-Pass and Multi-Instance Code Review with Claude: A Fresh Reviewer, Per-File Passes and an Integration Pass
  • When a Claude Support Agent Should Escalate: Three Clear Triggers, Not Mood or a Confidence Score
  • Error Propagation Across Subagents: Retry Locally, Then Report the Failure, the Attempts and What You Found
  • Human Review and Confidence Calibration: Check Accuracy by Type and Field Before You Stop Looking
  • Provenance in Multi-Source Research: Keep Every Claim With Its Source and Date, and Show Conflicts Instead of Settling Them
  • Lab: An Extraction Pipeline With a Nullable Schema, Validation-Retry, a 100-Request Batch and Human Review
  • Lab: A Research Pipeline With Parallel Subagents, a Timeout That Keeps Its Partial Results, and a Report With Its Trail
  • Coordinator and Subagents: Decompose, Delegate, Check Coverage, and Call Only the Spokes You Need
  • Passing Context to Subagents: Nothing Is Inherited, So Put Findings, Goal and Criteria in the Prompt
  • Parallel Subagents: Several Task Calls in One Response, Every Result Back in One User Turn
  • Task Decomposition: a Fixed Prompt Chain With an Integration Pass, or a Dynamic Plan That Adapts
  • Prompt Guidance vs Programmatic Gates: Block the Refund Until the Customer Is Verified, Then Hand Off a Card That Stands Alone
  • Scoped Tools per Agent and tool_choice: Three to Five Tools per Role, a Shared One, and auto, any or a Forced Tool
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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 pipeline: schema, validate, batch, review 1. schema null, other, confidence 2. validate retry format, stop on absent 3. batch 100 by custom_id, resend failures 4. review any field below 0.80? no yes saved human review weak fields listed absent: stop
Shape the answer, check it, scale it, and know when to ask a person.

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_no and due_in_days are "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, and category_detail says 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

Two 24-hour passes inside a 60-hour promise first pass 24 h resend pass 24 h wait 12 h 0 h 24 h 48 h 60 h SLA promise: 60 h (our own number) 60 - 24 - 24 = 12, so submit a batch every 12 hours
Plan for the full window twice: once for the first pass, once for the resend.

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 inUsed inWhat breaks without it
Schema: nullable due_in_daysValidate: null passesThe model guesses 30, or the check retries a value that isn't there
Validate: kind on every problemExtract: retry or stopdoc_D would burn three tries and still have no supplier
Same tool, prompt and tool choiceBatch paramsBatched answers have a different shape from single calls
Batch: custom_idFailures, resend, reviewResults arrive out of order and can't be matched
Schema: field confidenceReview: 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

StationFileIn the run
Schemaschema.pydoc_B keeps invoice_no and due_in_days as null
Validate and retryvalidate.py, extract.pydoc_C fixed on try 2; doc_D stopped: saved 3, human review 1
Batchbatch.py96 succeeded; 4 documents resent as 7 requests; submit every 12 h
Reviewreview.py73 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 116 of 123

Previous
Provenance in Multi-Source Research: Keep Every Claim With Its Source and Date, and Show Conflicts Instead of Settling Them
Next post
Lab: A Research Pipeline With Parallel Subagents, a Timeout That Keeps Its Partial Results, and a Report With Its Trail

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.

On this page

  • Four stations
  • Station 1: one schema that lets a document say less
  • Station 2: validate, then retry only what a retry can fix
  • Station 3: a batch of 100, matched by custom_id
  • The SLA sum
  • Station 4: route by confidence, check by segment
  • How the stations depend on each other
  • Common mistakes
  • Recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.