GuidesAI development
Tutorial: extracting data from PDF invoices with Claude
1. The schema
const tool = {
name: 'save_invoice',
description: 'Saves the data read from the invoice. null when a value is missing.',
input_schema: {
type: 'object',
properties: {
supplier: { type: 'string' },
number: { type: ['string', 'null'] },
date: { type: ['string', 'null'], description: 'YYYY-MM-DD' },
net: { type: ['number', 'null'] },
vat: { type: ['number', 'null'] },
total: { type: ['number', 'null'] },
},
required: ['supplier', 'number', 'date', 'net', 'vat', 'total'],
},
};
2. The call
import Anthropic from '@anthropic-ai/sdk';
import { readFile } from 'node:fs/promises';
const client = new Anthropic();
const pdf = (await readFile('invoice.pdf')).toString('base64');
const res = await client.messages.create({
model: process.env.CLAUDE_MODEL!,
max_tokens: 1024,
tools: [tool],
tool_choice: { type: 'tool', name: 'save_invoice' },
messages: [{
role: 'user',
content: [
{ type: 'document', source: { type: 'base64', media_type: 'application/pdf', data: pdf } },
{ type: 'text', text: 'Read this invoice. Amounts in euros, dot as decimal separator.' },
],
}],
});
const data = res.content.find((b) => b.type === 'tool_use')?.input;
3. The check
const ok = Math.abs(data.net + data.vat - data.total) < 0.02;
if (!ok || !data.date) await reviewQueue.add({ file, data });
else await accounting.save(data);
4. The full flow
- 1IntakeA dedicated mailbox or a drop folder.
- 2ExtractionThe model fills the schema.
- 3CheckTotals, date, duplicate number.
- 4OutputAccounting, or human review.
API basics: calling the Claude API from Node.js. Reliable JSON: reliable JSON from an LLM.
Frequently asked questions
- Do I need to convert the PDF to text first?
- No: the Claude API accepts PDFs and reads both the text and the layout. For a poor-quality scan, an OCR step can still help.
- Which model should I pick?
- A fast, low-cost model is often enough for standard invoices. Test on a batch of your real invoices before choosing.
- What about personal data?
- Invoices contain some. Check the AI provider's data processing terms and only send the documents you need to.