Zero Labs
Industry News / AI

Architecting a Production-Grade PDF Document Summarisation Agent

Source · Towards AI By Beau32

From the publisher’s feed, collected in the ZeroLabs newsroom.

A layered approach to extracting structured, verifiable insight from unstructured documents.The ability to extract reliable, structured information from arbitrary PDF documents represents one of the more technically demanding problems in applied natural language processing. On the surface, the task appears tractable: retrieve text, issue a prompt, receive a summary. In practice, however, the gap between a functional prototype and a system that can be trusted on real-world documents — scanned, multi-hundred pages, domain-specific — spans a series of non-trivial engineering decisions.This article presents a principled, layered architecture for building such a system. The reference implementation uses the following stack: pypdf and Docling for text extraction, OpenAI GPT-4o vision for scanned or image-heavy pages, OpenAI Embeddings for dense vector retrieval, DuckDB (with SQLite and PostgreSQL also supported) for persisting chunks and embeddings, LangChain for model routing, LangGraph for expressing the agent control flow as a typed state machine, and LangSmith for distributed tracing and observability. The system is exposed as a Python CLI accepting a document path, a natural-language query, and an output profile, producing a structured report.The architecture is domain-agnostic. The same pipeline processes legal contracts, financial statements, and medical records with only the terminal prompt schema and domain profile changing between runs.The Foundational ProblemThe Portable Document Format is a presentation-oriented specification, not a document interchange format. Content is encoded as a sequence of positioned drawing operators — glyphs, paths, images, and form annotations — with no intrinsic notion of reading order, paragraph structure, or semantic hierarchy. Recovering meaningful, well-ordered text from this representation is a non-trivial extraction problem; the fidelity of every downstream component depends on solving it correctly.ReAct ArchitectureCompounding this, transformer-based language models impose finite context windows. Feeding an entire multi-hundred-page document into a single inference call is not feasible even where token budgets would permit it, as attention dilution and positional degradation measurably reduce output quality on long contexts. A principled retrieval strategy — determining precisely what to send, when to send it, and how to synthesise evidence across multiple inference calls — is therefore a first-class architectural concern, not an optimisation.Layer 1: Document ExtractionThe extraction layer is responsible for converting raw PDF bytes into clean, page-scoped text. Three backend strategies address the different populations of documents encountered in practice.Embedded-text extraction (pypdf / pdfplumber)Digitally authored PDFs — those produced by word-processing or typesetting software — encode Unicode glyph streams that can be lifted directly from the file structure without rendering.Strengths: deterministic output, zero inference cost, negligible latency, no external dependencies.Applicability: restricted to documents with embedded text layers; unsuitable for scanned or raster-image content.Multimodal vision extraction (OpenAI Vision API / GPT-4o)Each page is rendered to a raster image and submitted to a multimodal language model, which transcribes the visual content and produces a structured textual representation.Strengths: effective on scanned documents, handwritten annotations, mixed-layout pages, and embedded figures or charts.Trade-offs: per-page inference cost, API latency, and rate-limit considerations at scale.Document intelligence libraries (Docling, Azure Document Intelligence)Purpose-built document understanding models infer the logical structure of a page — detecting paragraph boundaries, table cells, reading order, and section headings — and produce layout-aware output.Strengths: high-fidelity table extraction, robust reading-order reconstruction, moderate cost relative to vision APIs.Trade-offs: substantial runtime dependency, first-run model initialisation overhead.Design recommendation: expose all three backends behind a unified interface, selected at runtime. The appropriate backend can then be chosen per document type without modifying the downstream pipeline. The embedded-text backend is suitable for the majority of programmatically generated documents; the heavier backends should be reserved for scanned or visually complex content.Layer 2: ChunkingExtracted text must be segmented into retrievable units — chunks — prior to indexing. Chunk boundary placement has a measurable impact on both retrieval precision and synthesis quality, and should be treated as a deliberate design parameter rather than an implementation detail.Properties of well-formed chunksSemantic completeness — each chunk should encode a coherent unit of meaning; partial sentences or truncated clauses introduce ambiguity in synthesis.Bounded token length — chunks must fit within the context budget of the retrieval prompt alongside several co-retrieved neighbours; a target range of 300 to 600 tokens per chunk is a practical default.Boundary overlap — a one-to-two sentence overlap between adjacent chunks ensures that information near a boundary is represented in at least one complete chunk.Source provenance — every chunk must carry its originating document name and page range as indexed metadata, enabling citations in the final output.Sentence-aware sliding windowThe recommended general-purpose segmentation strategy proceeds as follows: normalise whitespace and segment the page text into sentences using punctuation-aware splitting; accumulate sentences into a sliding window until the target token budget is reached, then advance the window by a stride shorter than the window size to produce overlap; assign each chunk a composite identifier comprising the document name, page start, page end, and chunk index.Fixed-character or fixed-byte segmentation is inadvisable, as it introduces arbitrary cuts at linguistically incoherent positions.Layer 3: The Retrieval IndexThe retrieval index maps a natural-language query to the subset of chunks most likely to contain relevant evidence. Three retrieval paradigms are in common use; the optimal configuration combines all three.Lexical searchTerm-frequency-based retrieval (BM25 or analogous scoring functions) operates over tokenised chunk text. It is computationally efficient, entirely deterministic, and well-suited to queries involving specific named entities, dates, citations, or numerical values.Semantic searchDense vector retrieval embeds both the query and all document chunks into a shared latent space using a pre-trained embedding model. Cosine similarity between query and chunk embeddings provides a relevance signal that generalises across paraphrase and terminological variation.Hybrid retrieval with score fusionExecuting both retrieval strategies and merging the ranked result lists via Reciprocal Rank Fusion consistently outperforms either strategy in isolation, particularly on queries that combine specific entity lookup with conceptual reasoning.Index persistence: chunk text and computed embeddings are persisted to a local analytical database — DuckDB by default, with SQLite and PostgreSQL also supported — keyed by a deterministic hash of the document path, file size, modification time, and chunking parameters. This ensures that the embedding computation is incurred only once per document per configuration. A rebuild flag is exposed to invalidate the cache when necessary.Layer 4: The Agent LoopThe agent loop is the central orchestration component and has the greatest influence on output quality. A single-pass pipeline issues one retrieval query, passes the results to the model, and returns whatever is produced. A well-designed iterative agent loop decomposes the query into sub-goals, retrieves evidence incrementally, synthesises with citation tracking, reflects on coverage and confidence, and iterates until a termination criterion is met.The control flow proceeds through five stages: Plan (decompose the query into targeted sub-steps), Retrieve (execute retrieval for each sub-step), Synthesise (extract structured claims from each evidence batch), Reflect (assess coverage confidence and identify remaining gaps), and Answer (produce the final structured output, returning to Retrieve while confidence remains below the threshold).Step 1: Query decompositionThe model is prompted to decompose the user’s query into two to six concrete, independently addressable sub-questions. The response is constrained to a typed schema, ensuring the output is always machine-parseable and never freeform text. For a financial report query, the system would produce a structured plan containing a stated goal alongside discrete steps such as locating revenue and profit figures, extracting balance sheet totals, identifying cash flow from operations, surfacing significant one-off items, and locating the auditor’s opinion. Each step is handled independently in the retrieval phase that follows.Step 2: Selective retrievalFor each planned sub-step, a retrieval query is issued against the indexed chunk store. The model selects the retrieval modality — lexical, semantic, or hybrid — via a constrained structured output that also records the reasoning behind the choice. This makes every retrieval decision explicit and auditable: a sub-step that combines a specific figure lookup with surrounding narrative context would select hybrid mode, with that rationale preserved in the run trace.Step 3: Batch synthesis with claim extractionRetrieved chunks are presented to the model in configurable batches. Rather than producing unstructured narrative, the model is instructed to extract discrete, citable claims — each accompanied by a page citation, a verbatim supporting excerpt from the source document, and an importance weight between zero and one. A batch-level summary and a list of identified evidence gaps are also produced alongside the claims.Expressing synthesis output as a typed structure enables programmatic operations on the results: deduplication of repeated findings across batches, importance-weighted ranking of claims, and gap-driven generation of follow-up retrieval queries.Step 4: Confidence-based reflectionAfter each synthesis round, the model performs a structured self-assessment, producing a plain-language observation summary (for example, “revenue and profitability sufficiently covered; cash flow and audit opinion outstanding”), a numeric confidence score between zero and one, and two flags indicating whether the system is ready to produce a final answer and whether a deeper targeted search is warranted.When the confidence score falls below a configurable threshold — typically 0.75 — the loop returns to retrieval, issuing targeted queries against the identified gaps. The loop is bounded by a maximum iteration count to ensure termination. If the threshold is not reached after the maximum iterations, the system raises a human-input request rather than returning a low-confidence result without disclosure.Step 5: Domain-specific final synthesisWhen the reflection stage signals readiness, the accumulated claims are synthesised into the final output using a domain-specific prompt and output schema. For financial documents this covers the income statement, balance sheet, cash flow, key performance indicators, significant items, auditor’s opinion, risk disclosures, and forward guidance. For legal documents: parties, jurisdiction, material findings, precedents cited, and relief or orders granted. For medical and underwriting documents: diagnoses, procedures, clinical chronology, condition associations, and risk indicators.Layer 5: State Machine Orchestration with LangGraphExpressing the agent loop as a formal directed graph, rather than as imperative procedural code, provides significant engineering advantages: individual nodes can be unit-tested in isolation, the control flow is visually inspectable, and new nodes — such as a human-review gate — can be inserted without modifying existing wiring.LangGraph provides a typed state graph abstraction well-suited to this pattern. Each stage of the loop becomes a discrete node; conditional edges route between them based on the reflection outcome, directing the flow to continue iterating, proceed to the final answer, or pause for human review.The state object serves as the canonical data carrier across all nodes, holding the original query, accumulated claim set, iteration counter, current confidence estimate, outstanding evidence gaps, and the in-progress or finalised answer.Checkpointing: LangGraph supports serialising the agent state to a persistent store between node transitions. This enables mid-run resumption following process interruption — particularly important when processing documents whose extraction and indexing phases may take several minutes.Layer 6: Output VerificationLanguage model outputs exhibit well-documented inconsistency properties; production systems must include verification mechanisms to enforce output contracts and maintain result quality.Schema validation: each model response is validated against the declared output schema; responses that do not conform are rejected and the model is re-prompted with a targeted repair instruction.Citation grounding: for each extracted claim, the supporting excerpt is verified against the source chunk text via substring matching; claims whose excerpts cannot be grounded are flagged for downstream review.Structural verification: when the output format is a structured document, it is parsed to confirm section completeness and the absence of malformed constructs.Completeness scoring: a quality score is computed as the proportion of required output fields that are populated; this score is emitted alongside the result payload.These mechanisms do not constitute a semantic correctness guarantee, but they substantially raise the quality floor of outputs reaching the end consumer.Layer 7: Observability and Distributed TracingOperational visibility into agent behaviour is a prerequisite for systematic quality improvement and cost management.LangSmith integrates natively with LangGraph to capture a complete execution trace for every run — each node invocation, model call, prompt content, token usage, and wall-clock duration is recorded and queryable. Per-stage token accounting enables attribution of inference cost to specific pipeline components, informing optimisation priorities. Structured run statistics are emitted at the conclusion of each run: total token consumption, end-to-end wall time, iteration count, final confidence, and terminal state (completed, timed out, or escalated to human review).Complete System Data FlowA document enters the pipeline as a raw PDF file. The extraction layer converts it to normalised page text and metadata using the appropriate backend. The chunking engine segments that text into overlapping, page-scoped units, each assigned a composite identifier. Those chunks are embedded and persisted to the retrieval index, keyed by a deterministic document hash and rebuilt only when the source changes. The agent loop — implemented as a LangGraph state machine — then plans, retrieves, synthesises, and reflects iteratively until a confidence threshold is met, at which point a final structured result is produced.ConclusionConstructing a document summarisation agent that operates reliably across document types, scales, and domains requires treating each architectural layer as a first-class engineering concern. Extraction fidelity determines the quality of the evidence available to all subsequent components. Chunking precision determines the resolution of retrieval. Hybrid retrieval maximises recall across query types. The iterative agent loop — with structured decomposition, evidence batching, and confidence-based reflection — produces outputs of materially higher quality than single-pass inference. LangGraph provides a testable, extensible substrate for expressing that loop. Output verification enforces structural contracts on every result. Observability enables continuous measurement and improvement.The unifying principle across all layers is the same: enforce structure at every model boundary. Define typed input and output schemas for each inference call, validate conformance, and treat any deviation as a first-class event requiring remediation. This discipline transforms the language model from an opaque text generator into a dependable reasoning component whose outputs can be grounded, cited, and audited.The cumulative effect is a agentic system whose architecture is composable by design. Extraction backends, domain schemas, output destinations, and retrieval strategies can each be extended or replaced without modifying the remaining components. That composability reflects sound software engineering principles — and it is what makes the difference between a research prototype and a system that can be deployed with confidence.Architecting a Production-Grade PDF Document Summarisation Agent was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.