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ワークフロー自動化は、小さくテスト可能なステップ(抽出、検証、ルーティング、実行)をつなぐパイプラインとして組むのが最も効果的です。信頼度が低いケースや影響が大きいケースには、明確なレビューポイントを設けます。まずは1種類の文書、または1つの受信箱から始め、実際の事例で精度を測定し、その後に対象を広げてください。

Veni AIは、受信メールからERPの更新まで、企業の既存システムの上に自動化ワークフローを構築し、重要な箇所には人間によるレビューを組み込みます。私たちの開発内容を見る、またはワークフローについてご相談ください。

続けて読む

AIで動かしたい業務はありますか?

現在の動き方のまま、1つの業務プロセスをご説明ください。AIアプリケーションやエージェントが担える繰り返しのステップをお示しします。