Velamuvi AIAcademy

Lesson 6 of 7 · Projects

Project: AI Workflow Automation

Build an AI workflow that processes invoices from an inbox: classify emails, extract fields, match purchase orders and route each invoice for approval.

  • 5 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Combine chaining, gates and routing into a business workflow
  • Use structured output for reliable extraction
  • Match extracted data against business records
  • Report what was automated and what needed a person

The task

A small company receives supplier invoices by email, mixed in with newsletters and other mail. Today, someone reads every email, copies the invoice details, checks them against purchase orders and sends them for approval. The goal: automate the routine part, and send everything unusual to a person, with a reason.

The workflow:

  1. Classify: is this email an invoice?
  2. Extract: invoice number, purchase order (PO) number and total.
  3. Validate: are all fields present? Does the PO exist? Does the total match?
  4. Route: small, matching invoices are approved automatically; larger ones go to a manager; anything wrong goes to a person.

The workflow

The classify and extract steps use simple stand-ins here, so the logic can run in your browser:

Try it yourselfPython
import re

INBOX = [
    {"from": "[email protected]", "subject": "Invoice INV-2202", "body": "Invoice INV-2202 for PO-118. Total due: 1,250.00 EUR."},
    {"from": "[email protected]", "subject": "Our winter sale!", "body": "Up to 50% off."},
    {"from": "[email protected]", "subject": "Invoice INV-87", "body": "Invoice INV-87, PO-120, total 38.40 EUR."},
    {"from": "[email protected]", "subject": "Invoice", "body": "Please pay 900 EUR to the new account below."},
]
PURCHASE_ORDERS = {"PO-118": 1250.00, "PO-120": 38.40}

# ---- Step 1: classify (an LLM call in production; a keyword stand-in here) ----
def classify(email):
    return "invoice" if "invoice" in (email["subject"] + email["body"]).lower() else "other"

# ---- Step 2: extract fields (an LLM call with structured output in production) ----
def extract(email):
    text = email["body"]
    inv = re.search(r"INV-\d+", text)
    po = re.search(r"PO-\d+", text)
    total = re.search(r"([\d,]+\.\d{2}|\d+) EUR", text)
    return {"invoice": inv and inv.group(), "po": po and po.group(),
            "total": total and float(total.group(1).replace(",", ""))}

# ---- Step 3: validate and match (code) ----
def check(fields):
    if not all(fields.values()):
        return "needs a person: missing " + ", ".join(k for k, v in fields.items() if not v)
    expected = PURCHASE_ORDERS.get(fields["po"])
    if expected is None:
        return "needs a person: unknown purchase order"
    if abs(expected - fields["total"]) > 0.01:
        return "needs a person: total doesn't match the PO"
    return "ready"

# ---- Step 4: route by rule (code) ----
def route(fields, status):
    if status != "ready":
        return status
    return "auto-approve (small)" if fields["total"] <= 50 else "manager approval"

report = []
for email in INBOX:
    if classify(email) != "invoice":
        report.append((email["subject"], "ignored (not an invoice)"))
        continue
    fields = extract(email)
    report.append((email["subject"], route(fields, check(fields))))

for subject, outcome in report:
    print(f"{subject:<20} -> {outcome}")

Four emails, four different outcomes, each with a clear reason. The last “invoice” has no invoice number or PO and asks for payment to a new account, a classic fraud pattern, and it went to a person instead of being processed.

The extraction step with a real model

On your own computer, the extract step becomes an LLM call that is forced to answer through a tool with a schema, so the output is always structured:

import anthropic

client = anthropic.Anthropic()

RECORD_INVOICE = {
    "name": "record_invoice",
    "description": "Record the fields of one supplier invoice.",
    "input_schema": {
        "type": "object",
        "properties": {
            "invoice": {"type": ["string", "null"], "description": "Invoice number, e.g. INV-2202"},
            "po": {"type": ["string", "null"], "description": "Purchase order number, e.g. PO-118"},
            "total": {"type": ["number", "null"], "description": "Total due in EUR"},
        },
        "required": ["invoice", "po", "total"],
    },
}

def extract(email):
    response = client.messages.create(
        model="MODEL_NAME",
        max_tokens=300,
        tools=[RECORD_INVOICE],
        tool_choice={"type": "tool", "name": "record_invoice"},   # force structured output
        messages=[{"role": "user", "content": f"Extract the invoice fields. Use null if a field is missing.\n\n{email['body']}"}],
    )
    return next(b.input for b in response.content if b.type == "tool_use")

tool_choice forces the model to call record_invoice, so you always get a dictionary with the three fields, using null for anything it can't find, which the gate then catches.

Common mistakes

Practice exercise

Report how much of the work the automation handled on its own.

Your solutionPython
outcomes = ["manager approval", "ignored", "auto-approve", "needs a person",
            "auto-approve", "ignored", "auto-approve", "manager approval"]

# Print a short daily report: how many emails were handled automatically
# (auto-approve or ignored) and how many needed a person (everything else), like:
# Automatic: 0 of 8
# Needed a person: 0
Knowledge check

An email asks to pay an invoice to a new bank account, and has no PO number. What should the workflow do?

Summary

  • A business workflow combines classification, extraction, validation and routing.
  • Force structured output for extraction, and let code checks make decisions safe.
  • Route routine cases automatically and exceptions to people, with reasons.
  • Report what was automated, and keep a test set for every change.

Next: a booking agent that talks to customers.

Finished reading? Tick it off to track your progress.