发布于

AI工作流自动化:业务流程中的文档、邮件与审批

用LLM自动化文档处理、邮件分拣、数据抽取和审批流程,附每个步骤的示例代码,并说明如何设置人工复核节点,确保自动化决策安全可靠、结果可审计。

作者
Ali ÖzdurmuşVeni AI 创始人
更新于
阅读时间
阅读约 5 分钟

AI工作流自动化利用语言模型处理业务流程中的重复环节:读发票、分拣邮件、从表单中抽取字段、路由审批。与传统的基于规则的RPA不同,它能应对杂乱的非结构化输入。本指南通过代码展示这些构建模块,以及哪些环节应当让人参与。

代码示例为示意性的Python。client是已初始化的SDK客户端,MODEL是您所选模型ID的占位符。

自动化类别

1. 文档处理

  • 发票处理
  • 合同分析
  • 表单数据抽取

2. 沟通自动化

  • 邮件分类
  • 自动回复
  • 工单路由

3. 数据处理

  • 数据抽取
  • 数据转换
  • 报表

4. 决策自动化

  • 审批流程
  • 风险评估
  • 异常检测

文档处理流水线

发票处理

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)

合同分析

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)

邮件自动化

邮件分类

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)

生成自动回复

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

工作流编排

顺序流水线

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"})

条件工作流

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)

数据抽取

表格抽取

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

实体抽取

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"]
)

审批工作流

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)

人工复核节点

自动化并不意味着把人从流程中移除,而是让人只处理真正需要他们的案例:

  • 低置信度: 将置信度低于阈值的抽取或分类结果交给复核人员。
  • 高影响: 超过设定金额的付款、合同变更和面向客户的回复,需要经过人工批准环节。
  • 校验失败: 合计不对、必填字段缺失或供应商未知的记录,进入复核队列,而不是直接写入ERP。
  • 抽样: 每周从完全自动化的案例中随机抽取一小部分复核,以发现悄然出现的漂移。
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)
    )

错误处理与监控

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()
        }

集成模式

Webhook触发

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}

结论

AI工作流自动化最适合做成由小而可测试的步骤组成的流水线:抽取、校验、路由、执行,并为低置信度和高影响案例设置清晰的复核节点。先从一种文档类型或一个收件箱开始,用真实样本衡量准确率,再逐步扩大范围。

Veni AI在企业现有系统之上构建自动化工作流,从收到一封邮件到更新ERP,并在关键之处保留人工复核。了解我们的产品,或与我们探讨您的工作流。

继续阅读

有流程适合交给 AI 来跑吗?

描述一个目前的流程,我们会告诉您 AI 应用或智能体可以承担其中哪些重复性步骤。