Sub topic 17
Assembling the end-to-end pipeline
This chapter connects the pieces from earlier chapters into one working flow. It assumes you can write basic Python, read JSON, call an LLM API, and use the pypdf and pydantic code from earlier chapters.
The flow
Each step has one job. Each step passes a clear result to the next one, so you can test and replace steps one at a time.
Choosing the path
The text-extraction check from the first code example decides the route. A near-empty result means a scan, so the page goes to OCR. Long documents are split into chunks, each chunk goes through the same steps, and the per-chunk results are merged.
The pipeline function
The function below reuses Invoice, PROMPT_TEMPLATE, extract_invoice and is_grounded from earlier chapters. The ocr_pdf function is your own OCR wrapper, and call_llm is your own LLM call.
from pypdf import PdfReader
def read_text(path):
reader = PdfReader(path)
pages = [page.extract_text() or "" for page in reader.pages]
return "\n\n".join(pages)
def process_document(path, call_llm, ocr_pdf):
text = read_text(path)
if len(text.strip()) < 50:
text = ocr_pdf(path)
try:
invoice = extract_invoice(text, call_llm, max_attempts=3)
except ValueError as exc:
return {"status": "review", "reason": f"validation: {exc}", "data": None}
suspect = [name for name in ("vendor", "invoice_number")
if not is_grounded(getattr(invoice, name), text)]
if suspect:
return {"status": "review", "reason": f"ungrounded: {suspect}",
"data": invoice.model_dump()}
return {"status": "accepted", "reason": None, "data": invoice.model_dump()}Every result carries a status and a reason. A reviewer can see why a document was flagged without rereading logs.
Batch processing and logging
Run the function over a folder and keep the outcomes together:
from pathlib import Path
def run_batch(folder, call_llm, ocr_pdf):
results = {}
for path in sorted(Path(folder).glob("*.pdf")):
results[path.name] = process_document(str(path), call_llm, ocr_pdf)
return resultsLog at least the file name, the route (text or OCR), the number of attempts, and the final status. These logs let you find which step causes most failures.
Common errors
- One failing document stops the batch. Catch errors per document and send that document to review.
- Retries with no limit. Always cap attempts, as
max_attemptsdoes, to control cost. - Skipping evaluation after changes. A new prompt or model can lower accuracy. Rerun
field_accuracyon your labeled test set after every change. - Logging sensitive text. Log identifiers and statuses, not full document content.
Exercise
A document passes schema validation, but the grounding check finds that the invoice number does not appear in the source text. What should the pipeline do, and why not accept it?
Show answer
It should return a "review" status with the reason and the extracted data, so a person can check it. Passing validation only shows the output has the right shape. A value missing from the source is probably invented by the model, so accepting it would put a wrong value into your data.