Anatomy of a Production Agentic Pipeline
“Agentic AI” has become the most inflated phrase in the industry, so let me deflate it with specifics. The invoice pipeline I work on involves no swarm of autonomous agents debating strategy. It’s a multi-step document workflow where every step is typed, every step is traced, and every step is allowed to fail loudly. PDFs go in, and validated, compliance-checked structured data comes out, with humans seeing only the cases the system knows it’s unsure about. It runs on AWS Bedrock and Lambda, with PyMuPDF for parsing, Pydantic v2 for validation and Claude for the language understanding. Out of seven stages, the model does real work in two. That ratio is deliberate, and it’s the most important thing about the design.
Before the model touches anything
The first stage is plain parsing with PyMuPDF, with no model involved. It also does triage. A page with almost no extractable text and one large image is a scan, which needs a different path entirely, and catching that early prevents the most confident nonsense a model can produce: a detailed extraction from an empty string. The rule I’ve taken from this is never to spend a model call on something a library can do deterministically.
What surprised me is how much the parsing affects accuracy downstream. Naive text extraction returns words in whatever order the PDF stores them internally, which for a two-column invoice means the invoice number, the customer’s address and the date end up interleaved into one incoherent line. Hand that to a model and it will cheerfully invent a structure that explains the mess. Rebuilding the reading order from the coordinates of each word, and preserving spatial hints such as the wide horizontal gaps that signal table columns, improved accuracy more than several rounds of prompt editing combined. It’s a direct echo of my multimodal survey. How you represent the input constrains what any model can do with it.
The second stage routes each document before extraction. Different clients’ invoices differ in their fields, layouts and conventions, so a lightweight classification step identifies the type and picks a matching Pydantic schema from a registry. That sounds like a minor detail and turns out to be load-bearing. A single universal schema that covers every invoice type ends up vague everywhere, while a per-client schema is precise, and precision in the schema becomes precision in the extraction because the schema is exactly what the model is shown. It does triple duty: its JSON Schema goes straight into the prompt, so the contract shown to the model and the contract enforced on the output are literally the same object and can’t drift apart; it acts as the validation contract; and it’s the clearest documentation of what the system handles.
Valid is not the same as correct
The extraction call itself runs through Bedrock inside the company’s cloud boundary and returns JSON shaped by the routed schema. Then Pydantic validates it, and this is where I’d push back on how most teams use validation. A successful json.loads tells you almost nothing. Our models encode business meaning: money is stored as Decimal and never as a float, because floats corrupt financial figures quietly; currencies are an enum, so an invented value like “EURO (approx)” becomes impossible rather than merely unlucky; dates have plausibility bounds. The validator that earns its keep most often is a cross-field check.
python
model_validator(mode="after")def totals_reconcile(self): computed = sum(item.total for item in self.line_items) if abs(computed - self.grand_total) > Decimal("0.01"): raise ValueError(f"line items sum to {computed}, invoice says {self.grand_total}") return self
It matters because an extraction can be perfectly valid and completely wrong. Every field has the right type, every enum value is legal, every required field is present, and the model has still misread 2,050 as 2,500, so the line items don’t add up to the stated total. Syntax checks catch formatting mistakes. Only business rules catch grounding mistakes, where the output is well formed but disagrees with the document. You need both, and the second kind is the one almost nobody builds. If your only quality gate is “does it parse,” you’re shipping confident errors downstream and calling it a green build.
Validated data then runs through the compliance checks: totals reconciliation, date sanity, currency and formatting rules, and, at the heart of the system for fraud prevention, matching bank details against trusted reference data. The checks are independent, so they run in parallel, and the latency of the whole stage becomes that of the slowest check rather than the sum of all of them. That’s the latency budgeting from my 2024 voice assistant applied to an entirely different domain. Almost all of the checks are ordinary code, and every one I could express in Python became fast, free, testable and incapable of hallucinating.
The rest is plumbing, and plumbing is the point
The final output is rendered from validated objects with Jinja2 templates rather than by asking the model to format things nicely, because templates can be diffed, tested and audited, and they are physically incapable of inventing a number. Anything that exhausts its repair attempts or trips a compliance rule goes to a human review queue with its complete trace attached: every stage’s inputs and outputs, how many attempts it took, which validations failed, the token counts and the timings.
Two smaller rules have proven themselves repeatedly. The first is to extract verbatim and transform in code. The more the model copies and the less it calculates, the more accurate it is, so we never ask it to add up line items. We extract them, sum them in Python and treat any disagreement with the printed total as a signal. The second is that locale is a minefield. “1.234,56” and “1,234.56” mean the same amount in different countries, and “03/04/2026” is either March or April depending on who wrote it. We stopped asking the model to normalise these. It now returns the string exactly as printed along with the locale it inferred, and deterministic code does the conversion, which turned a fuzzy model behaviour into a function with unit tests. When I pooled validation failures in AgentAudit last spring, locale formatting came out on top and I didn’t quite believe it. Here, it’s on top again.
If I had to compress the whole design into one sentence, it would be this: let the model propose, and let deterministic systems dispose. The pipeline earns the word “agentic” in one specific sense, which is that it reacts to its own intermediate results by validating, retrying, routing and escalating instead of firing one blind prompt and hoping. But that autonomy is fenced in everywhere by structure. The intelligence is stochastic, and the architecture around it must not be. I’ve deliberately skipped the most interesting stage, which is what happens when validation fails, because it’s where the research I spent last term arguing about finally met a system with money attached.
Leave a Reply