Invoice Processor
Extract structured data from invoices with AI, validate totals via a deterministic tool agent, and output auditable JSON with retry support.
connic init my-project --templates=invoice- Difficulty
- Beginner
- Works with
- HTTP Webhook, AWS S3, Email
- Source
- GitHub
- Publisher
- By connic
What the template does
A sequential pipeline that extracts structured data from raw invoice text or images using an LLM agent with calculator tools, then validates totals with a deterministic tool agent at zero token cost. Middleware adds audit trails with request IDs and cost tracking. Supports retry on transient failures.
- AP automation
- Process incoming supplier invoices, extract line items and totals, and validate before posting to ERP.
- Receipt ingestion
- Parse receipts from photos or PDFs into structured data for expense reporting and reconciliation.
- Invoice auditing
- Check each invoice for discrepancies between stated and calculated totals with a full audit trail.
Every file lands in your project
connic init copies these files into your codebase, where you change them like the rest of your code.
LLM agent with its model, prompt and tools.
version: "1.0"
name: invoice-extractor
type: llm
model: connic/gemini-3.7-flash
description: "Extracts structured line items, totals, and metadata from raw invoice text or images"
system_prompt: |
You are a senior accountant processing invoices. Your job is to extract every
billable detail from the provided invoice into a clean, machine-readable format.
Extraction rules:
- Identify the vendor name, invoice number, issue date, and due date.
- Extract every line item with description, quantity, unit price, and line total.
- Use the calculator tools to independently verify that line items sum to the
stated subtotal and that tax is applied correctly.
- If the invoice contains multiple tax rates, break them out separately.
- Flag discrepancies between your calculated totals and the stated totals.
- For multi-page invoices, ensure no line items are missed.
- Currency should be the ISO 4217 code (EUR, USD, GBP, etc.).
When calculations don't match, still output the vendor-stated values but set
the "discrepancy" field to true with an explanation.
temperature: 0.1
output_schema: invoice
timeout: 45
retry_options:
attempts: 5
max_delay: 60
tools:
- invoice_tools.add
- invoice_tools.multiply
- invoice_tools.calculate_taxRuns its agents in order, each on the output of the one before.
version: "1.0"
name: invoice-pipeline
type: sequential
description: "Extract structured invoice data, then validate totals automatically"
agents:
- invoice-extractor
- invoice-validatorTool agent that calls one function, with no model tokens.
version: "1.0"
name: invoice-validator
type: tool
description: "Deterministic validation of invoice math without LLM - zero token cost"
tool_name: invoice_tools.validate_totalsFunctions the agents call as tools.
"""Invoice processing tools for extraction and validation."""
from typing import Any
def add(a: float, b: float) -> float:
"""Add two numbers together.
Args:
a: The first number
b: The second number
Returns:
The sum of a and b
"""
return a + b
def multiply(a: float, b: float) -> float:
"""Multiply two numbers.
Args:
a: The first number
b: The second number
Returns:
The product of a and b
"""
return a * b
def calculate_tax(amount: float, rate: float = 0.19) -> dict[str, float]:
"""Calculate tax for a given amount.
Args:
amount: The base amount to calculate tax on
rate: The tax rate as a decimal (default: 0.19 for 19% VAT)
Returns:
Dict with net, tax, and gross amounts
"""
tax = round(amount * rate, 2)
return {"net": amount, "tax": tax, "gross": round(amount + tax, 2)}
def validate_totals(
payload: dict[str, Any] | None = None,
context: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Validate that invoice totals are mathematically correct.
Runs as a tool agent after invoice-extractor, so it receives the extracted
invoice as its payload.
Args:
payload: The extracted invoice, with keys: subtotal, tax_amount, total,
and optional tax_rate (default 0.19) and tolerance (default 0.02).
context: Auto-injected run context.
Returns:
Dict with valid (bool), checks performed, and any discrepancies
"""
payload = payload or {}
subtotal = payload.get("subtotal", 0.0)
tax_amount = payload.get("tax_amount", 0.0)
total = payload.get("total", 0.0)
tax_rate = payload.get("tax_rate", 0.19)
tolerance = payload.get("tolerance", 0.02)
expected_tax = round(subtotal * tax_rate, 2)
expected_total = round(subtotal + expected_tax, 2)
tax_ok = abs(tax_amount - expected_tax) <= tolerance
total_ok = abs(total - expected_total) <= tolerance
line_total_ok = abs(total - (subtotal + tax_amount)) <= tolerance
checks = {
"tax_matches_rate": tax_ok,
"total_matches_calculation": total_ok,
"line_total_consistent": line_total_ok,
}
if all(checks.values()):
return {"valid": True, "checks": checks, "message": "All totals verified"}
discrepancies = []
if not tax_ok:
discrepancies.append(
f"Tax: expected {expected_tax} at {tax_rate*100}%, got {tax_amount}"
)
if not total_ok:
discrepancies.append(
f"Total: expected {expected_total}, got {total}"
)
if not line_total_ok:
discrepancies.append(
f"Subtotal + tax ({subtotal + tax_amount}) != total ({total})"
)
return {"valid": False, "checks": checks, "discrepancies": discrepancies}Runs before and after the agent with the same name.
"""Middleware for the invoice-extractor agent.
Adds audit metadata and enforces basic input validation.
"""
import uuid
from typing import Any
async def before(content: dict[str, Any], context: dict[str, Any]) -> dict[str, Any]:
"""Attach a unique request ID and audit timestamp for traceability."""
context["request_id"] = str(uuid.uuid4())
context["source"] = "invoice-pipeline"
return content
async def after(response: str, context: dict[str, Any]) -> str:
"""Log extraction cost for billing reconciliation."""
token_usage = context.get("token_usage", {})
duration = context.get("duration_ms", 0)
context["audit_log"] = {
"request_id": context.get("request_id"),
"tokens_used": token_usage.get("output_tokens", 0) + token_usage.get("input_tokens", 0),
"duration_ms": duration,
}
return responseJSON schema for an agent's structured output.
{
"type": "object",
"description": "Structured invoice extraction result",
"properties": {
"vendor": {
"type": "string",
"description": "Vendor or company name"
},
"invoice_number": {
"type": "string",
"description": "Invoice reference number"
},
"issue_date": {
"type": "string",
"description": "Invoice date (YYYY-MM-DD)"
},
"due_date": {
"type": "string",
"description": "Payment due date (YYYY-MM-DD)"
},
"currency": {
"type": "string",
"description": "ISO 4217 currency code"
},
"line_items": {
"type": "array",
"description": "Itemized charges",
"items": {
"type": "object",
"properties": {
"description": {"type": "string"},
"quantity": {"type": "number"},
"unit_price": {"type": "number"},
"amount": {"type": "number"}
},
"required": ["description", "amount"]
}
},
"subtotal": {
"type": "number",
"description": "Sum of line items before tax"
},
"tax_rate": {
"type": "number",
"description": "Tax rate as decimal (e.g. 0.19)"
},
"tax_amount": {
"type": "number",
"description": "Total tax charged"
},
"total": {
"type": "number",
"description": "Grand total including tax"
},
"discrepancy": {
"type": "boolean",
"description": "True if calculated totals don't match stated totals"
},
"discrepancy_note": {
"type": "string",
"description": "Explanation of any calculation mismatches"
}
},
"required": ["vendor", "total", "currency", "line_items"]
}2 test cases for connic test.
version: "1.0"
# The calculator tools (add, multiply, calculate_tax) are pure math with no
# side effects, so they run for real and deterministically - no mocks needed.
defaults:
runs: 1
timeout_s: 90
tests:
- name: extracts_single_line_invoice
payload: '{"text":"Invoice from Acme GmbH. Number INV-001. 3 widgets at 10.00 EUR each. VAT 19%. Total 35.70 EUR. Verify the tax with the calculator tools."}'
expected_result: output.total > 0 and output.vendor != ""
expected_tool_calls:
- invoice_tools.calculate_tax
- name: extracts_multi_line_invoice
payload: '{"text":"Invoice from Globex Ltd. Number INV-002. Line 1: 2 chairs at 50.00 EUR each. Line 2: 4 lamps at 12.50 EUR each. VAT 19%. Verify each line total and the tax using the calculator tools."}'
expected_result: output.total > 0 and output.vendor != ""
expected_tool_calls:
- invoice_tools.multiply
- invoice_tools.add1 test case for connic test.
version: "1.0"
# End-to-end through the sequential pipeline: the extractor pulls structured
# numbers from the invoice text, then the validator tool agent runs a pure-math
# pass on them. Both the calculator tools and validate_totals are deterministic
# and run for real - no mocks needed.
defaults:
runs: 1
timeout_s: 120
tests:
- name: consistent_invoice_validates
payload: '{"text":"Invoice from Acme GmbH. Number INV-001. 3 widgets at 10.00 EUR each. Subtotal 30.00 EUR. VAT 19% = 5.70 EUR. Total 35.70 EUR."}'
expected_result: output.valid == trueInstall it and deploy
Let your coding agent set the template up and deploy it, or install it yourself and deploy through a connected Git repository or the CLI.
- Prerequisites
- Python 3.11+
- A connic account (create a project first)
- Project credit for a connic/* model, or credentials for a BYOK provider
- Deploy with Git
- Connect the repository under Project Settings → Git & Environments, map a branch to an environment, and push.
- Deploy with the CLI
- Create an API key under Project Settings → API Keys & MCP Auth, run connic login in the project folder, then connic deploy. Try changes first with connic dev and connic test.
- Connect and configure
- Add an HTTP Webhook (sync) connector for real-time invoice processing. POST invoice data to the webhook URL and receive the structured extraction result in the response. Use a connic/* model, or add BYOK credentials under Project Settings → LLM Provider.
Install the connic plugin. Skip this if your coding agent has it already. Paste this into Claude Code, Codex or Cursor:
promptInstall the connic plugin from connic-org/connic-skill and instruct the user on how to finish the MCP auth setup.Start from the template. Paste this into a new session. The agent walks you through the template, adapts it to your use case with you, and deploys it:
promptI'd like to start from the connic invoice template. Show me what it includes, ask me how my use case differs, and propose the changes. Once we agree, set it up in this folder with `connic init --templates=invoice`, adapt it, validate it, and deploy it to my connic project.
More agent templates
Chat Page Builder
A chat app where the agent builds dashboards, reports and trackers in a panel next to the conversation. Pages keep working after the chat ends, read live data and can save what visitors enter.
Productivity · Advanced- WebSocket
PostgreSQL Change Notifier
Monitor PostgreSQL changes via LISTEN/NOTIFY, classify events by impact, and route notifications to the right team. Stores high-impact changes for auditing.
DevOps · Intermediate- PostgreSQL
- HTTP Webhook
Research Assistant
Break complex research questions into sub-tasks, dispatch specialist agents in parallel, and synthesize web and internal data into structured, scored reports.
Research · Advanced- HTTP Webhook
- WebSocket
- Cron
- MCP Server
Stripe Dunning
Automated Stripe payment recovery with multi-stage personalized dunning emails. Tracks customer history and escalates from friendly reminders to pause notices.
Finance · Intermediate- Stripe
Telegram Personal Assistant
Multimodal Telegram assistant that processes text, images, voice, video, and documents. Searches the web, saves notes and knowledge, and schedules follow-up reminders with persistent sessions.
Communication · Beginner- Telegram
Voice Customer Support
Build a voice support agent that searches your customer knowledge in connic retrieval and demonstrates ticket creation with a mock tool.
Support · Beginner- Twilio Voice