How to Build a Self-Correcting Multi-Agent System for Enterprise Data Extraction

A practical guide to building a self-correcting multi-agent system for enterprise data extraction: validation loops, confidence routing and human review.

Kumar NihalDecember 4, 20265 min read
On this page

A self-correcting multi-agent system for enterprise data extraction does not trust a single model call. It splits the job across small agents, checks every result against rules the model cannot argue with, and sends failures back for another try or to a human. Done right, it turns "usually correct" into "correct, or flagged".

This guide walks through the architecture I would use for a document-to-database data pipeline, with working code for the validation loop. It applies to invoices, contracts, claims, loss runs, or any messy input that must end up as clean rows.

Why a single extraction agent breaks at scale#

One prompt that reads a document and returns JSON looks great on five samples. At five thousand documents the quiet failures show up: a table row dropped, a total copied from the wrong line, a date read in the wrong format, a field invented because the schema asked for it.

The dangerous part is that these errors look fine. The JSON is valid, the types are right, and the pipeline keeps running. Nobody notices until a number is wrong in a report.

Two things make this worse in enterprise data extraction. Documents vary by vendor, so no single prompt fits all of them. And the cost of a silent error is far higher than the cost of a slow one.

The key idea: correction needs an outside check#

"Self-correcting" is easy to misread. Asking a model "are you sure? check again" is not a correction loop. Research from Google DeepMind and the University of Illinois found that LLMs struggle to fix their own reasoning without external feedback, and sometimes make a correct answer worse.

So the loop must be fed by something that is not the model's opinion: a schema, a business rule, a calculation, a lookup in your database, or a human. Every check you can express as code is worth more than another paragraph of prompt.

An insurance-document team described the same lesson. They raised row-count accuracy from about 80% to 95% by giving the agent a validation tool to check and fix its own output, not by swapping the extraction model.

Architecture of a self-correcting multi-agent system#

Keep each agent small, with one job:

  • Parser agent: turns the file into clean text, tables and layout, using OCR where needed.
  • Extractor agent: reads the parsed content and fills your schema.
  • Validator: not an LLM. Plain code that checks schema, types and business rules.
  • Corrector agent: receives the validator's exact errors and retries only what failed.
  • Judge: scores confidence per field and decides accept, review or reject.
  • Review queue: where humans confirm what the system could not.

The validator being plain code is the most important design choice. It is cheap, fast, and it does not hallucinate.

Step 1: Define the schema before the prompt#

Start with the output you need, as typed structure. Pydantic validation gives you types, required fields and custom rules in one place, and most agent frameworks can use it as the structured output contract.

python
from datetime import date
from decimal import Decimal
from pydantic import BaseModel, model_validator


class LineItem(BaseModel):
    description: str
    quantity: Decimal
    unit_price: Decimal
    amount: Decimal


class Invoice(BaseModel):
    invoice_number: str
    invoice_date: date
    currency: str
    line_items: list[LineItem]
    subtotal: Decimal
    tax: Decimal
    total: Decimal

    @model_validator(mode="after")
    def totals_add_up(self):
        line_sum = sum(item.amount for item in self.line_items)
        if abs(line_sum - self.subtotal) > Decimal("0.01"):
            raise ValueError(
                f"Line items add up to {line_sum}, but subtotal is {self.subtotal}"
            )
        if abs(self.subtotal + self.tax - self.total) > Decimal("0.01"):
            raise ValueError(
                f"Subtotal plus tax is {self.subtotal + self.tax}, but total is {self.total}"
            )
        return self

Look at the last validator. It encodes something a model cannot be trusted with: arithmetic. If the line items do not add up to the subtotal, the extraction is wrong no matter how confident the model sounded.

Step 2: Turn validator errors into feedback#

When validation fails, send the exact error back to the extractor. Specific feedback ("line items add up to 1,240.00 but subtotal is 1,420.00") fixes problems. Vague feedback ("try again") does not. This is the heart of a validation loop.

Frameworks make it a built-in pattern. Pydantic AI, for example, lets a validator raise a retry signal that returns the message to the model, and it enforces a retry budget. Here is the same idea in plain Python:

python
from pydantic import ValidationError

MAX_ATTEMPTS = 3


def extract_with_correction(document_text: str) -> dict:
    feedback = None
    for attempt in range(1, MAX_ATTEMPTS + 1):
        raw_json = extractor_agent(document_text, feedback=feedback)
        try:
            invoice = Invoice.model_validate_json(raw_json)
            return {"status": "valid", "invoice": invoice, "attempts": attempt}
        except ValidationError as err:
            feedback = (
                f"Attempt {attempt} failed validation:\n{err}\n"
                "Re-read the source and fix only the fields named above."
            )
    return {"status": "needs_review", "last_error": feedback, "attempts": MAX_ATTEMPTS}

Three details matter. Cap the attempts. Feed back only the errors, not the whole conversation. And keep the final failure, because a failed document is useful information, not something to hide.

Step 3: Wire it as a graph#

Once you have more than one loop, a state graph is easier to reason about than nested functions. In LangGraph, a conditional edge sends the run back to the extractor, forward to acceptance, or out to a person.

python
from typing import TypedDict
from langgraph.graph import StateGraph, START, END


class State(TypedDict):
    document: str
    result: dict | None
    errors: str | None
    attempts: int


def route(state: State) -> str:
    if state["errors"] is None:
        return "accept"
    if state["attempts"] >= 3:
        return "human_review"
    return "extract"


graph = StateGraph(State)
graph.add_node("extract", extract_node)
graph.add_node("validate", validate_node)
graph.add_node("human_review", review_node)

graph.add_edge(START, "extract")
graph.add_edge("extract", "validate")
graph.add_conditional_edges(
    "validate", route, {"accept": END, "extract": "extract", "human_review": "human_review"}
)
graph.add_edge("human_review", END)

app = graph.compile(checkpointer=checkpointer)

For the human step, LangGraph's interrupt function pauses the run and saves its state, so a reviewer can answer hours later. The human-in-the-loop docs recommend one interrupt per node and looping with a conditional edge, rather than a while loop inside the node.

Step 4: Route by confidence and keep a human in the loop#

Not every field deserves the same trust. Have the extractor, or a separate judge, return a confidence score per field, then route by tier:

Confidence scoring tierExample thresholdWhat happens
Auto-accept0.92 or higherWrite straight to the database
Review0.70 to 0.92Pre-fill the value, a person confirms or fixes it
Manual entryBelow 0.70A person enters it from the source document

These numbers are starting points. Tune them from your own error data, and set the bar higher for money, dates and identifiers than for free-text notes.

Two tricks raise confidence cheaply. Run two different models on the same document and compare: agreement raises confidence, disagreement flags a review. And learn from corrections: store every human fix next to the original value, because that becomes your best test set.

Step 5: Make the data pipeline safe to re-run#

A reliable data pipeline assumes things fail halfway. Use a hash of the document as an idempotency key, so a retry never inserts duplicates. Store every attempt, validator error and final status. Send documents that use up their retries to a dead-letter queue instead of dropping them. And log one correlation ID across all agents, so you can replay a bad extraction end to end.

Common failure modes to design against#

UC Berkeley researchers studied more than 200 traces from seven frameworks and grouped 14 failure modes into three families: unclear specifications, misalignment between agents, and weak or missing verification. Their conclusion is that many failures come from system design, not only from model limits.

That maps to a short checklist:

  • Specification: give each agent one role and a typed input and output.
  • Misalignment: pass structured state between agents, not free-form chat.
  • Verification: never accept an output without a check that can fail.

How to know it works#

Build a small labelled set of 50 to 100 real documents before you tune anything. Track field-level accuracy, the share of documents that reach a human, retries per document, and cost per document. A good multi-agent data extraction setup improves the first number and pushes the second down over time, as corrections feed back in.

If you want help designing agentic data extraction for your own documents, see how Causly builds custom AI automation, or browse more build notes in the Lab.

Frequently asked questions

What is a self-correcting multi-agent system?

It is a set of small specialised agents (extract, validate, correct, judge) connected by a loop where every result is checked by outside rules, and failures are retried or sent to a human.

Can an LLM correct its own extraction errors?

Not reliably on its own. Research shows models struggle to fix their reasoning without external feedback, so use schema checks, business rules, tool results or a human to provide it.

How many retries should the correction loop allow?

Two or three is a common starting point. Beyond that, retries mostly add cost, so route the document to human review. Tune the number with your own data.

When should a document go to human review?

When validation still fails after the retry budget, when field confidence is below your threshold, or when two models disagree. Use stricter thresholds for money, dates and identifiers.

Which framework should I use?

There is no single best choice. Pydantic or Instructor works well for validated structured output, and a graph library such as LangGraph helps when you need loops, branching and human pauses. You can also start with plain Python.

Share
Kumar Nihal

Written by

Kumar Nihal

AI-first software engineer and founder of Causly. I build software, SaaS and AI systems, and write about it here. More about me

Get new posts by email

High-signal notes on AI, automation and building systems. No spam.

Keep reading

Insight

Why I Built PCSKit: Solving Context Loss in AI Coding Sessions

AI coding agents are productive, but their work can lose continuity when a context window fills up, a session gets interrupted, or developers switch between tools. I built PCSKit to solve this problem with local-first project continuity, evidence-based handoffs, and verifiable development history—so the next AI agent can continue from the actual project state instead of relying on an unreliable summary.

Nov 24, 2026
Insight

AI Coding Agent Handoffs: Why HANDOFF.md Needs Verifiable Evidence

Learn how to preserve context across AI coding agent sessions with reliable handoffs. Explore the limitations of traditional HANDOFF.md files, why task summaries aren't enough, and how Git state, test results, file changes, and verifiable evidence help agents resume development work with greater confidence.

Nov 24, 2026
Insight

MCP Tool Annotations Explained: Practical Examples, Defaults, and Security Best Practices

Understand MCP Tool Annotations and how they influence AI agent interactions with tools. Learn the four core annotations — readOnlyHint, destructiveHint, idempotentHint, and openWorldHint — with practical JSON examples, default behaviors, security considerations, common mistakes, and testing strategies for building reliable Model Context Protocol servers.

Nov 24, 2026