公開日

エンタープライズチャットボットとAIアシスタント:アーキテクチャとベストプラクティス

本番で通用する企業向けチャットボットの作り方。対話管理、メモリ、意図検出、テンプレートとLLMによる回答、有人対応への引き継ぎ、評価指標までを解説します。

執筆者
Ali ÖzdurmuşVeni AI 創業者
更新日
読了時間
読了時間 約5分

企業のチャットボットは、定型回答を返すだけの決定木ではなくなりました。現在のアシスタントは、言語モデルに、社内のナレッジ、業務システム、人に引き継ぐタイミングの明確なルールを組み合わせています。このガイドでは、WebサイトやWhatsAppで顧客に対応する場合も、社内ポータルで従業員に対応する場合も、本番環境で信頼性を保つためのアーキテクチャとプラクティスを解説します。

コードサンプルは説明用のPythonです。clientは初期化済みのSDKクライアント、MODELは選択したモデルIDのプレースホルダーです。

チャットボットのアーキテクチャ

主要コンポーネント

┌────────────────────────────────────────────────────┐
│                    User Interface                   │
└───────────────────────┬────────────────────────────┘
                        │
┌───────────────────────▼────────────────────────────┐
│              Input Processing Layer                 │
│  ┌──────────┐  ┌──────────┐  ┌────────────────┐   │
│  │  Speech  │  │   Text   │  │   Multimodal   │   │
│  │  to Text │  │ Normalize│  │   Processing   │   │
│  └──────────┘  └──────────┘  └────────────────┘   │
└───────────────────────┬────────────────────────────┘
                        │
┌───────────────────────▼────────────────────────────┐
│                 Dialog Manager                      │
│  ┌──────────┐  ┌──────────┐  ┌────────────────┐   │
│  │  Intent  │  │  State   │  │    Context     │   │
│  │ Detection│  │ Manager  │  │    Handler     │   │
│  └──────────┘  └──────────┘  └────────────────┘   │
└───────────────────────┬────────────────────────────┘
                        │
┌───────────────────────▼────────────────────────────┐
│              Response Generation                    │
│  ┌──────────┐  ┌──────────┐  ┌────────────────┐   │
│  │   LLM    │  │ Template │  │     Action     │   │
│  │ Response │  │  Engine  │  │    Executor    │   │
│  └──────────┘  └──────────┘  └────────────────┘   │
└────────────────────────────────────────────────────┘

コンテキスト管理

会話メモリ

python
from typing import List, Dict
from datetime import datetime

class ConversationMemory:
    def __init__(self, max_turns: int = 10):
        self.max_turns = max_turns
        self.history: List[Dict] = []
        self.metadata: Dict = {}
    
    def add_message(self, role: str, content: str):
        message = {
            "role": role,
            "content": content,
            "timestamp": datetime.now().isoformat()
        }
        self.history.append(message)
        
        # Clean old messages
        if len(self.history) > self.max_turns * 2:
            self.history = self.history[-self.max_turns * 2:]
    
    def get_context(self) -> List[Dict]:
        return [{"role": m["role"], "content": m["content"]} 
                for m in self.history]
    
    def summarize(self, llm_client) -> str:
        """Summarize long conversations"""
        if len(self.history) < 10:
            return None
        
        response = llm_client.chat.completions.create(
            model=MODEL,
            messages=[
                {"role": "system", "content": "Summarize this conversation."},
                {"role": "user", "content": str(self.history)}
            ]
        )
        return response.choices[0].message.content

セッション状態

python
class SessionState:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.user_info: Dict = {}
        self.collected_data: Dict = {}
        self.current_intent: str = None
        self.current_step: str = None
        self.awaiting_input: str = None
    
    def set_slot(self, name: str, value: any):
        self.collected_data[name] = value
    
    def get_slot(self, name: str) -> any:
        return self.collected_data.get(name)
    
    def clear_slots(self):
        self.collected_data = {}
    
    def is_complete(self, required_slots: List[str]) -> bool:
        return all(slot in self.collected_data for slot in required_slots)

意図分類

LLMベースの意図検出

python
def detect_intent(user_message: str, available_intents: List[Dict]) -> Dict:
    intent_descriptions = "\n".join([
        f"- {intent['name']}: {intent['description']}"
        for intent in available_intents
    ])
    
    response = client.chat.completions.create(
        model=MODEL,
        response_format={"type": "json_object"},
        messages=[
            {
                "role": "system",
                "content": f"""Determine the intent of the user message.
                
Available intents:
{intent_descriptions}

Respond in JSON format:
{{"intent": "intent_name", "confidence": 0.0-1.0, "entities": {{}}}}
"""
            },
            {"role": "user", "content": user_message}
        ]
    )
    
    return json.loads(response.choices[0].message.content)

ハイブリッド型の意図検出

python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression

class HybridIntentClassifier:
    def __init__(self):
        self.ml_classifier = None
        self.vectorizer = TfidfVectorizer()
    
    def train_ml(self, texts: List[str], labels: List[str]):
        X = self.vectorizer.fit_transform(texts)
        self.ml_classifier = LogisticRegression()
        self.ml_classifier.fit(X, labels)
    
    def classify(self, text: str) -> Dict:
        # ML prediction
        X = self.vectorizer.transform([text])
        ml_intent = self.ml_classifier.predict(X)[0]
        ml_confidence = max(self.ml_classifier.predict_proba(X)[0])
        
        # Ask LLM if confidence is low
        if ml_confidence < 0.7:
            llm_result = detect_intent(text, self.available_intents)
            return llm_result
        
        return {"intent": ml_intent, "confidence": ml_confidence}

対話フロー

ステートマシン

python
from enum import Enum

class OrderState(Enum):
    START = "start"
    PRODUCT_SELECTION = "product_selection"
    QUANTITY = "quantity"
    ADDRESS = "address"
    CONFIRMATION = "confirmation"
    COMPLETE = "complete"

class OrderFlow:
    def __init__(self):
        self.state = OrderState.START
        self.data = {}
    
    def process(self, user_input: str, intent: str) -> str:
        if self.state == OrderState.START:
            if intent == "order":
                self.state = OrderState.PRODUCT_SELECTION
                return "Which product would you like to order?"
        
        elif self.state == OrderState.PRODUCT_SELECTION:
            self.data["product"] = user_input
            self.state = OrderState.QUANTITY
            return f"You selected {user_input}. How many do you want?"
        
        elif self.state == OrderState.QUANTITY:
            self.data["quantity"] = int(user_input)
            self.state = OrderState.ADDRESS
            return "Could you provide your delivery address?"
        
        elif self.state == OrderState.ADDRESS:
            self.data["address"] = user_input
            self.state = OrderState.CONFIRMATION
            return f"Order summary:\n{self.data}\nDo you confirm?"
        
        elif self.state == OrderState.CONFIRMATION:
            if "yes" in user_input.lower():
                self.state = OrderState.COMPLETE
                return "Order received. Thank you!"
            else:
                self.state = OrderState.START
                return "Order cancelled."

応答の生成

テンプレートとLLMのハイブリッド

python
class ResponseGenerator:
    def __init__(self):
        self.templates = {
            "greeting": [
                "Hello! How can I help you?",
                "Welcome! What would you like to do today?"
            ],
            "farewell": [
                "Have a good day! See you again.",
                "I'm here if you have any other questions. Goodbye!"
            ]
        }
    
    def generate(self, intent: str, context: Dict) -> str:
        # Template for simple intents
        if intent in self.templates:
            return random.choice(self.templates[intent])
        
        # LLM for complex intents
        return self.llm_generate(intent, context)
    
    def llm_generate(self, intent: str, context: Dict) -> str:
        system_prompt = f"""You are a helpful customer service assistant.
User intent: {intent}
Current context: {json.dumps(context, ensure_ascii=False)}

Rules:
- Give short and concise answers
- Be friendly but professional
- Ask follow-up questions if necessary
"""
        
        response = client.chat.completions.create(
            model=MODEL,
            messages=[
                {"role": "system", "content": system_prompt},
                *context.get("history", [])
            ]
        )
        
        return response.choices[0].message.content

フォールバック処理

python
class FallbackHandler:
    def __init__(self):
        self.fallback_count = 0
        self.max_fallbacks = 3
    
    def handle(self, user_input: str, context: Dict) -> str:
        self.fallback_count += 1
        
        if self.fallback_count >= self.max_fallbacks:
            self.fallback_count = 0
            return self.human_handoff(context)
        
        responses = [
            "I didn't understand. Could you rephrase that?",
            "I cannot help with this. You can ask a different question.",
            "I think I misunderstood you. could you try again?"
        ]
        
        return responses[self.fallback_count - 1]
    
    def human_handoff(self, context: Dict) -> str:
        # Hand off to human agent
        create_support_ticket(context)
        return "I am connecting you to a customer representative. Please wait."

分析とモニタリング

python
class ChatAnalytics:
    def __init__(self):
        self.metrics = {
            "total_conversations": 0,
            "successful_resolutions": 0,
            "fallback_rate": 0,
            "avg_turns_per_conversation": 0,
            "intent_distribution": {}
        }
    
    def log_conversation(self, conversation: Dict):
        self.metrics["total_conversations"] += 1
        
        # Intent tracking
        for message in conversation["messages"]:
            if "intent" in message:
                intent = message["intent"]
                self.metrics["intent_distribution"][intent] = \
                    self.metrics["intent_distribution"].get(intent, 0) + 1
        
        # Resolution tracking
        if conversation.get("resolved"):
            self.metrics["successful_resolutions"] += 1
    
    def get_resolution_rate(self) -> float:
        if self.metrics["total_conversations"] == 0:
            return 0
        return self.metrics["successful_resolutions"] / self.metrics["total_conversations"]

本番運用チェックリスト

セキュリティ

  • 入力のサニタイズ
  • レート制限
  • 個人情報(PII)のマスキング
  • インジェクション対策
  • ユーザーがAIと会話していることの明示
  • KVKK/GDPRに準拠した会話ログの保持

パフォーマンス

  • 応答時間 2秒未満
  • 同時ユーザーへの対応
  • キャッシュレイヤー
  • オートスケーリング

ユーザー体験

  • 入力中インジケーター
  • エラーメッセージ
  • 会話履歴
  • 多言語対応

まとめ

信頼できるアシスタントは、いくつかの明確な部品で構成されます。上限を守るメモリ、自信がないときにそれを自覚できる意図検出、テンプレートと生成回答の組み合わせ、そして人へ素早くつなぐ経路です。回答は社内データに基づかせ、解決率とフォールバック率を測定し、実際の会話から改善していきます。

Veni AIは、企業自身の文書やシステムに基づいて、トルコ語をはじめとする各言語で回答し、有人対応への引き継ぎを組み込んだAIアシスタントを構築しています。サービスを見る、またはアシスタントについてご相談ください。

続けて読む

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

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