Published

AI Workflow Automation: Documents, Email and Approvals in Business Processes

Automate document processing, email triage, data extraction and approvals with LLMs, with code for each step and human review points that keep decisions safe.

Written by
Ali ÖzdurmuşFounder, Veni AI
Updated
Reading time
6 min read

AI workflow automation uses language models to handle the repetitive steps in a business process: reading an invoice, sorting an email, extracting fields from a form, routing an approval. Unlike classic rule-based RPA, it copes with messy, unstructured input. This guide shows the building blocks with code, and where to keep a person in the loop.

Code samples are illustrative Python. client is an initialized SDK client and MODEL is a placeholder for the model ID you choose.

Automation Categories

1. Document Processing

  • Invoice processing
  • Contract analysis
  • Form data extraction

2. Communication Automation

  • Email classification
  • Auto-response
  • Ticket routing

3. Data Processing

  • Data extraction
  • Data transformation
  • Reporting

4. Decision Automation

  • Approval processes
  • Risk assessment
  • Anomaly detection

Document Processing Pipeline

Invoice Processing

python
from openai import OpenAI
import base64

client = OpenAI()
MODEL = "your-model-id"

def process_invoice(image_path: str) -> dict:
    with open(image_path, "rb") as f:
        image_data = base64.b64encode(f.read()).decode()
    
    response = client.chat.completions.create(
        model=MODEL,
        response_format={"type": "json_object"},
        messages=[
            {
                "role": "system",
                "content": """Extract information from the invoice:
                {
                    "vendor": "string",
                    "invoice_number": "string",
                    "date": "YYYY-MM-DD",
                    "total": number,
                    "tax": number,
                    "items": [{"description": "string", "quantity": number, "price": number}]
                }"""
            },
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_data}"}}
                ]
            }
        ]
    )
    
    return json.loads(response.choices[0].message.content)

Contract Analysis

python
def analyze_contract(contract_text: str) -> dict:
    response = client.chat.completions.create(
        model=MODEL,
        response_format={"type": "json_object"},
        messages=[
            {
                "role": "system",
                "content": """Analyze the contract and extract the following information:
                {
                    "parties": ["string"],
                    "effective_date": "YYYY-MM-DD",
                    "termination_date": "YYYY-MM-DD",
                    "key_obligations": ["string"],
                    "payment_terms": "string",
                    "risks": ["string"],
                    "unusual_clauses": ["string"]
                }"""
            },
            {"role": "user", "content": contract_text}
        ]
    )
    
    return json.loads(response.choices[0].message.content)

Email Automation

Email Classification

python
def classify_email(email_content: str, categories: list) -> dict:
    response = client.chat.completions.create(
        model=MODEL,
        response_format={"type": "json_object"},
        messages=[
            {
                "role": "system",
                "content": f"""Classify the email:
                Categories: {categories}
                
                Response format:
                {{
                    "category": "string",
                    "confidence": 0.0-1.0,
                    "priority": "high|medium|low",
                    "sentiment": "positive|neutral|negative",
                    "requires_response": boolean,
                    "summary": "string"
                }}"""
            },
            {"role": "user", "content": email_content}
        ]
    )
    
    return json.loads(response.choices[0].message.content)

# Usage
categories = ["sales_inquiry", "support_request", "complaint", "partnership", "spam"]
result = classify_email(email_body, categories)

Auto-Reply Generation

python
def generate_auto_reply(email: dict, context: str = "") -> str:
    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {
                "role": "system",
                "content": f"""Generate a professional auto-reply.
                Tone: Friendly but professional
                Language: English
                
                Company info: {context}
                
                Email category: {email['category']}
                Priority: {email['priority']}
                """
            },
            {"role": "user", "content": f"Email content:\n{email['content']}\n\nSummary: {email['summary']}"}
        ]
    )
    
    return response.choices[0].message.content

Workflow Orchestration

Sequential Pipeline

python
class WorkflowPipeline:
    def __init__(self):
        self.steps = []
    
    def add_step(self, name: str, function: callable, config: dict = None):
        self.steps.append({
            "name": name,
            "function": function,
            "config": config or {}
        })
    
    def execute(self, input_data: dict) -> dict:
        result = input_data
        
        for step in self.steps:
            print(f"Executing: {step['name']}")
            try:
                result = step["function"](result, **step["config"])
            except Exception as e:
                return {"error": str(e), "failed_step": step["name"]}
        
        return result

# Pipeline definition
pipeline = WorkflowPipeline()
pipeline.add_step("extract", extract_data)
pipeline.add_step("validate", validate_data)
pipeline.add_step("transform", transform_data)
pipeline.add_step("load", load_to_database)

result = pipeline.execute({"file_path": "invoice.pdf"})

Conditional Workflow

python
class ConditionalWorkflow:
    def __init__(self):
        self.routes = {}
        self.default_route = None
    
    def add_route(self, condition: callable, handler: callable):
        self.routes[condition] = handler
    
    def set_default(self, handler: callable):
        self.default_route = handler
    
    def execute(self, data: dict) -> dict:
        for condition, handler in self.routes.items():
            if condition(data):
                return handler(data)
        
        if self.default_route:
            return self.default_route(data)
        
        raise ValueError("No matching route found")

# Usage
workflow = ConditionalWorkflow()
workflow.add_route(
    lambda x: x["category"] == "support",
    create_support_ticket
)
workflow.add_route(
    lambda x: x["category"] == "sales",
    forward_to_sales
)
workflow.set_default(archive_email)

Data Extraction

Table Extraction

python
def extract_table_from_document(document_path: str) -> list:
    # Convert document to image or parse PDF
    images = convert_to_images(document_path)
    
    all_tables = []
    for img in images:
        response = client.chat.completions.create(
            model=MODEL,
            response_format={"type": "json_object"},
            messages=[
                {
                    "role": "system",
                    "content": "Extract tables from image as JSON array. Each table should be a list of dicts."
                },
                {
                    "role": "user",
                    "content": [
                        {"type": "image_url", "image_url": {"url": img}}
                    ]
                }
            ]
        )
        
        tables = json.loads(response.choices[0].message.content)
        all_tables.extend(tables.get("tables", []))
    
    return all_tables

Entity Extraction

python
def extract_entities(text: str, entity_types: list) -> dict:
    response = client.chat.completions.create(
        model=MODEL,
        response_format={"type": "json_object"},
        messages=[
            {
                "role": "system",
                "content": f"""Extract the following entities from text: {entity_types}
                
                Format:
                {{
                    "entities": [
                        {{"type": "string", "value": "string", "confidence": 0.0-1.0}}
                    ]
                }}"""
            },
            {"role": "user", "content": text}
        ]
    )
    
    return json.loads(response.choices[0].message.content)

# Usage
entities = extract_entities(
    "John Doe paid $5,000 on January 15, 2024.",
    ["PERSON", "DATE", "MONEY"]
)

Approval Workflows

python
class ApprovalWorkflow:
    def __init__(self, rules: list):
        self.rules = rules
    
    def evaluate(self, request: dict) -> dict:
        for rule in self.rules:
            if rule["condition"](request):
                return {
                    "decision": rule["action"],
                    "rule_name": rule["name"],
                    "approvers": rule.get("approvers", []),
                    "reason": rule.get("reason", "")
                }
        
        return {"decision": "manual_review", "reason": "No matching rule"}
    
    def ai_evaluate(self, request: dict) -> dict:
        """Complex decisions with LLM"""
        response = client.chat.completions.create(
            model=MODEL,
            response_format={"type": "json_object"},
            messages=[
                {
                    "role": "system",
                    "content": f"""Approval rules: {json.dumps(self.rules)}
                    
                    Evaluate the request and decide:
                    {{
                        "decision": "approve|reject|escalate",
                        "confidence": 0.0-1.0,
                        "reasoning": "string",
                        "risk_level": "low|medium|high"
                    }}"""
                },
                {"role": "user", "content": json.dumps(request)}
            ]
        )
        
        return json.loads(response.choices[0].message.content)

# Rules
rules = [
    {
        "name": "auto_approve_small",
        "condition": lambda x: x["amount"] < 1000,
        "action": "approve",
        "reason": "Amount below threshold"
    },
    {
        "name": "manager_approval",
        "condition": lambda x: x["amount"] < 10000,
        "action": "route",
        "approvers": ["manager"]
    }
]

workflow = ApprovalWorkflow(rules)

Human Review Points

Automation does not mean removing people from the process. It means people only look at the cases that need them:

  • Low confidence: route extractions or classifications below a confidence threshold to a reviewer.
  • High impact: payments, contract changes and customer-facing replies above a set value get a human approval step.
  • Validation failures: totals that do not add up, missing mandatory fields or unknown vendors go to a review queue instead of the ERP.
  • Sampling: review a small random share of fully automated cases every week to catch silent drift.
python
def needs_review(result: dict) -> bool:
    return (
        result.get("confidence", 0) < 0.85
        or result.get("total", 0) > 50_000
        or not validate_totals(result)
    )

Error Handling & Monitoring

python
class AutomationMonitor:
    def __init__(self):
        self.executions = []
    
    def log_execution(self, workflow_name: str, input_data: dict, 
                     result: dict, duration: float):
        self.executions.append({
            "workflow": workflow_name,
            "timestamp": datetime.now(),
            "success": "error" not in result,
            "duration": duration,
            "input_size": len(str(input_data)),
            "error": result.get("error")
        })
    
    def get_metrics(self) -> dict:
        if not self.executions:
            return {}
        
        successful = [e for e in self.executions if e["success"]]
        
        return {
            "total_executions": len(self.executions),
            "success_rate": len(successful) / len(self.executions),
            "avg_duration": sum(e["duration"] for e in self.executions) / len(self.executions),
            "error_types": self._group_errors()
        }

Integration Patterns

Webhook Trigger

python
from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/webhook/email")
async def handle_email_webhook(request: Request):
    data = await request.json()
    
    # Email processing
    classification = classify_email(data["body"], CATEGORIES)
    
    if classification["requires_response"]:
        reply = generate_auto_reply(data, COMPANY_CONTEXT)
        send_email(data["from"], reply)
    
    # Route to appropriate workflow
    workflow = get_workflow(classification["category"])
    result = workflow.execute(data)
    
    return {"status": "processed", "result": result}

Conclusion

AI workflow automation works best as a pipeline of small, testable steps: extract, validate, route, act, with clear review points for low-confidence and high-impact cases. Start with one document type or one inbox, measure accuracy against real examples, then widen the scope.

Veni AI builds automated workflows on top of companies' existing systems, from an incoming email to an ERP update, with human review where it matters. See what we build or discuss your workflow with us.

Keep reading

Have a process that should run on AI?

Describe one process as it runs today, and we'll show you which repetitive steps an AI application or agent could handle.