Businesses run on documents: invoices, contracts, policies, reports, forms. Finding a payment term in a 40-page contract or pulling totals from hundreds of invoices is slow and error-prone when done by hand. AI can answer questions about documents and extract structured data, but only if the pipeline is designed with care, because errors in a contract or an invoice can be expensive.
Two main tasks
- Question answering: "What is the notice period in this contract?"
- Extraction: "Return the invoice number, date, supplier and total as JSON."
They use similar building blocks but have different quality requirements. Extraction results often flow directly into accounting systems, so validation is crucial.
Step 1: get clean text from documents
Digital PDFs
If the PDF contains real text, extract it with libraries such as pypdf or pdfplumber, which also provide layout and table information.
Scanned PDFs and photos
Use OCR (for example Tesseract or a cloud OCR) to convert images to text. Image quality, skew and language settings affect accuracy. Check the output on a sample.
Tables
Tables are tricky: plain text extraction loses the structure. Use table-aware tools or models that keep rows and columns, or convert the page to an image and use a vision-capable model.
Other formats
Word, Excel and email files can be converted with dedicated libraries. Keep metadata such as file name, page number and section headings for citations.
import pdfplumber
def extract_pages(path):
pages = []
with pdfplumber.open(path) as pdf:
for number, page in enumerate(pdf.pages, start=1):
text = page.extract_text() or ""
pages.append({"page": number, "text": text})
return pages
pages = extract_pages("contract.pdf")
print(f"{len(pages)} pages, first 200 characters of page 1:")
print(pages[0]["text"][:200])
If text is empty for most pages, the PDF is probably scanned and needs OCR.
Step 2: decide how to give text to the model
Small documents
If the whole document fits in the model's context window, you can include it in the prompt. This is simple and keeps all context available.
Large documents or collections
Use retrieval: split the text into chunks (preferably along headings or clauses), create embeddings, retrieve the most relevant chunks for each question and give only those to the model. Keep page numbers with each chunk for citations.
Very structured documents
For fixed-format forms and invoices from a known supplier, templates or rule-based extraction (regular expressions, coordinates) can be faster and more reliable than a language model.
Step 3: write a careful prompt
Ask the model to answer only from the document, cite the page or clause and admit when the information is absent.
import anthropic
client = anthropic.Anthropic()
def ask_document(question: str, pages: list[dict]) -> str:
context = "\n\n".join(f"[Page {p['page']}]\n{p['text']}" for p in pages)
prompt = (
"You are assisting with document review. Answer ONLY from the document below. "
"Quote the exact sentence you rely on and give its page number. "
"If the document does not say, reply: 'Not stated in the document.'\n\n"
f"Document:\n{context}\n\nQuestion: {question}"
)
reply = client.messages.create(
model="claude-sonnet-5-5", max_tokens=500,
messages=[{"role": "user", "content": prompt}],
)
return reply.content[0].text
print(ask_document("What is the termination notice period?", pages))
The quote requirement lets a human verify the answer quickly.
Step 4: structured extraction
For invoices, ask for strict JSON with a fixed schema, then validate it in code.
import json
from datetime import datetime
SCHEMA_HINT = """Return only JSON with these keys:
invoice_number (string), invoice_date (YYYY-MM-DD), supplier_name (string),
currency (string), subtotal (number), tax (number), total (number).
Use null for any value that is not clearly present."""
def validate_invoice(data: dict) -> list[str]:
problems = []
try:
datetime.strptime(data["invoice_date"], "%Y-%m-%d")
except Exception:
problems.append("invoice_date is missing or not in YYYY-MM-DD format")
try:
if abs(float(data["subtotal"]) + float(data["tax"]) - float(data["total"])) > 0.01:
problems.append("subtotal + tax does not equal total")
except (TypeError, ValueError):
problems.append("numbers are missing or not numeric")
return problems
# raw = call_model(SCHEMA_HINT + invoice_text) -> JSON string
raw = '{"invoice_number": "INV-1042", "invoice_date": "2025-03-14", "supplier_name": "ABC Traders", "currency": "NPR", "subtotal": 10000, "tax": 1300, "total": 11300}'
data = json.loads(raw)
print(validate_invoice(data) or "Looks consistent")
Business rules such as "total equals subtotal plus tax" catch many extraction errors automatically. Anything failing validation goes to a person.
Step 5: human review where it matters
- Contracts and legal documents: AI can highlight clauses, summarise obligations and suggest questions, but a qualified person must make decisions. Do not rely on AI as legal advice.
- Finance: route low-confidence or inconsistent invoices to an accountant for confirmation before posting to the ledger.
- Show evidence: display the source page and highlighted text next to each extracted value so reviewers can verify in seconds.
When building ERP and accounting modules, a review screen that shows the PDF page beside the extracted fields, with one-click corrections, has been far more valuable than chasing small gains in model accuracy.
Common failure modes
- OCR errors turning 8 into 3 or 0 into O, changing amounts
- Lost table structure, mixing up columns
- Multi-page tables and totals split across pages
- Similar clauses in different sections leading to the wrong citation
- Hallucinated clauses when the question assumes something the contract lacks
- Dates and number formats (day/month confusion, commas and decimals, BS versus AD dates)
- Mixed languages in the same document
- Prompt injection in documents: hidden text saying "ignore previous instructions" can try to steer the model
Security and privacy
Documents often contain personal data, prices and trade secrets.
- Choose providers with suitable data-protection terms, or run models on your own infrastructure.
- Limit who can query which documents (access control in retrieval).
- Log queries and answers for audit.
- Redact sensitive fields when full detail is not needed.
- Treat document content as untrusted input to the model, never as instructions.
Measuring quality
Create a test set of 30 to 100 documents and questions with known answers. Measure:
- Field-level accuracy for extraction (percentage of fields correct)
- Whether citations point to the right place
- Rate of "Not stated" responses when the information is truly absent
- Time saved versus manual review
Re-run the tests whenever you change prompts, models or OCR settings.
Frequently Asked Questions
Can AI replace a lawyer for contract review?
No. It can speed up reading and flag issues, but legal judgement and responsibility rest with qualified professionals.
How accurate is invoice extraction?
It depends on document quality and variety. With clean digital invoices and validation rules, accuracy can be high; messy scans need more review.
Should I fine-tune a model for my invoices?
Try prompting, templates and validation first. Fine-tuning helps when you have many examples of a stable format and need very consistent output.
Does it work with Nepali documents?
OCR and models support Devanagari to varying degrees. Test on your own documents before depending on it.
Conclusion
Document AI works best as a pipeline: clean text extraction, careful retrieval, strict prompts with citations, structured output with validation and human review for important decisions. Measure on real samples and keep security in mind.