Conversationele AI: Best Practices voor Chatbot-ontwikkeling
Conversationele AI-systemen maken interactie tussen mens en computer mogelijk via natuurlijke taal. In deze gids onderzoeken we strategieën voor chatbot-ontwikkeling op ondernemingsniveau.
Chatbot-architectuur
Kerncomponenten
1┌────────────────────────────────────────────────────┐ 2│ User Interface │ 3└───────────────────────┬────────────────────────────┘ 4 │ 5┌───────────────────────▼────────────────────────────┐ 6│ Input Processing Layer │ 7│ ┌──────────┐ ┌──────────┐ ┌────────────────┐ │ 8│ │ Speech │ │ Text │ │ Multimodal │ │ 9│ │ to Text │ │ Normalize│ │ Processing │ │ 10│ └──────────┘ └──────────┘ └────────────────┘ │ 1130: └───────────────────────┬────────────────────────────┘ 12 │ 13┌───────────────────────▼────────────────────────────┐ 14│ Dialog Manager │ 15│ ┌──────────┐ ┌──────────┐ ┌────────────────┐ │ 16│ │ Intent │ │ State │ │ Context │ │ 17│ │ Detection│ │ Manager │ │ Handler │ │ 18│ └──────────┘ └──────────┘ └────────────────┘ │ 1938: └───────────────────────┬────────────────────────────┘ 20 │ 21┌───────────────────────▼────────────────────────────┐ 22│ Response Generation │ 23│ ┌──────────┐ ┌──────────┐ ┌────────────────┐ │ 24│ │ LLM │ │ Template │ │ Action │ │ 25│ │ Response │ │ Engine │ │ Executor │ │ 26│ └──────────┘ └──────────┘ └────────────────┘ │ 2746: └────────────────────────────────────────────────────┘
Contextbeheer
Gespreksgeheugen
1from typing import List, Dict 2from datetime import datetime 3 4class ConversationMemory: 5 def __init__(self, max_turns: int = 10): 6 self.max_turns = max_turns 7 self.history: List[Dict] = [] 8 self.metadata: Dict = {} 9 10 def add_message(self, role: str, content: str): 11 message = { 12 "role": role, 13 "content": content, 14 "timestamp": datetime.now().isoformat() 15 } 16 self.history.append(message) 17 18 # Clean old messages 19 if len(self.history) > self.max_turns * 2: 20 self.history = self.history[-self.max_turns * 2:] 21 22 def get_context(self) -> List[Dict]: 23 return [{"role": m["role"], "content": m["content"]} 24 for m in self.history] 25 26 def summarize(self, llm_client) -> str: 27 """Summarize long conversations""" 28 if len(self.history) < 10: 29 return None 30 31 response = llm_client.chat.completions.create( 32 model="gpt-4-turbo", 33 messages=[ 34 {"role": "system", "content": "Summarize this conversation."}, 35 {"role": "user", "content": str(self.history)} 36 ] 37 ) 38 return response.choices[0].message.content
Sessie-status
1class SessionState: 2 def __init__(self, session_id: str): 3 self.session_id = session_id 4 self.user_info: Dict = {} 5 self.collected_data: Dict = {} 6 self.current_intent: str = None 7 self.current_step: str = None 8 self.awaiting_input: str = None 9 10 def set_slot(self, name: str, value: any): 11 self.collected_data[name] = value 12 13 def get_slot(self, name: str) -> any: 14 return self.collected_data.get(name) 15 16 def clear_slots(self): 17 self.collected_data = {} 18 19 def is_complete(self, required_slots: List[str]) -> bool: 20 return all(slot in self.collected_data for slot in required_slots) 21## Intentclassificatie 22 23### LLM-gebaseerde intentdetectie 24 25```python 26def detect_intent(user_message: str, available_intents: List[Dict]) -> Dict: 27 intent_descriptions = "\n".join([ 28 f"- {intent['name']}: {intent['description']}" 29 for intent in available_intents 30 ]) 31 32 response = client.chat.completions.create( 33 model="gpt-4-turbo", 34 response_format={"type": "json_object"}, 35 messages=[ 36 { 37 "role": "system", 38 "content": f"""Determine the intent of the user message. 39 40Available intents: 41{intent_descriptions} 42 43Respond in JSON format: 44{{"intent": "intent_name", "confidence": 0.0-1.0, "entities": {{}}}} 45""" 46 }, 47 {"role": "user", "content": user_message} 48 ] 49 ) 50 51 return json.loads(response.choices[0].message.content)
Hybride intentdetectie
1from sklearn.feature_extraction.text import TfidfVectorizer 2from sklearn.linear_model import LogisticRegression 3 4class HybridIntentClassifier: 5 def __init__(self): 6 self.ml_classifier = None 7 self.vectorizer = TfidfVectorizer() 8 9 def train_ml(self, texts: List[str], labels: List[str]): 10 X = self.vectorizer.fit_transform(texts) 11 self.ml_classifier = LogisticRegression() 12 self.ml_classifier.fit(X, labels) 13 14 def classify(self, text: str) -> Dict: 15 # ML prediction 16 X = self.vectorizer.transform([text]) 17 ml_intent = self.ml_classifier.predict(X)[0] 18 ml_confidence = max(self.ml_classifier.predict_proba(X)[0]) 19 20 # Ask LLM if confidence is low 21 if ml_confidence < 0.7: 22 llm_result = detect_intent(text, self.available_intents) 23 return llm_result 24 25 return {"intent": ml_intent, "confidence": ml_confidence}
Dialoogflow
Toestandsmachine
1from enum import Enum 2 3class OrderState(Enum): 4 START = "start" 5 PRODUCT_SELECTION = "product_selection" 6 QUANTITY = "quantity" 7 ADDRESS = "address" 8 CONFIRMATION = "confirmation" 9 COMPLETE = "complete" 10 11class OrderFlow: 12 def __init__(self): 13 self.state = OrderState.START 14 self.data = {} 15 16 def process(self, user_input: str, intent: str) -> str: 17 if self.state == OrderState.START: 18 if intent == "order": 19 self.state = OrderState.PRODUCT_SELECTION 20 return "Welk product wilt u bestellen?" 21 22 elif self.state == OrderState.PRODUCT_SELECTION: 23 self.data["product"] = user_input 24 self.state = OrderState.QUANTITY 25 return f"U heeft {user_input} geselecteerd. Hoeveel wilt u?" 26 27 elif self.state == OrderState.QUANTITY: 28 self.data["quantity"] = int(user_input) 29 self.state = OrderState.ADDRESS 30 return "Kunt u uw afleveradres opgeven?" 31 32 elif self.state == OrderState.ADDRESS: 33 self.data["address"] = user_input 34 self.state = OrderState.CONFIRMATION 35 return f"Bestellingsoverzicht:\n{self.data}\nBevestigt u?" 36 37 elif self.state == OrderState.CONFIRMATION: 38 if "yes" in user_input.lower(): 39 self.state = OrderState.COMPLETE 40 return "Bestelling ontvangen. Dank u wel!" 41 else: 42 self.state = OrderState.START 43 return "Bestelling geannuleerd." 44## Responsgeneratie 45 46### Template + LLM-hybride 47 48```python 49class ResponseGenerator: 50 def __init__(self): 51 self.templates = { 52 "greeting": [ 53 "Hello! How can I help you?", 54 "Welcome! What would you like to do today?" 55 ], 56 "farewell": [ 57 "Have a good day! See you again.", 58 "I'm here if you have any other questions. Goodbye!" 59 ] 60 } 61 62 def generate(self, intent: str, context: Dict) -> str: 63 # Template for simple intents 64 if intent in self.templates: 65 return random.choice(self.templates[intent]) 66 67 # LLM for complex intents 68 return self.llm_generate(intent, context) 69 70 def llm_generate(self, intent: str, context: Dict) -> str: 71 system_prompt = f"""You are a helpful customer service assistant. 72User intent: {intent} 73Current context: {json.dumps(context, ensure_ascii=False)} 74 75Rules: 76- Give short and concise answers 77- Be friendly but professional 78- Ask follow-up questions if necessary 79""" 80 81 response = client.chat.completions.create( 82 model="gpt-4-turbo", 83 messages=[ 84 {"role": "system", "content": system_prompt}, 85 *context.get("history", []) 86 ] 87 ) 88 89 return response.choices[0].message.content
Fallbackafhandeling
1class FallbackHandler: 2 def __init__(self): 3 self.fallback_count = 0 4 self.max_fallbacks = 3 5 6 def handle(self, user_input: str, context: Dict) -> str: 7 self.fallback_count += 1 8 9 if self.fallback_count >= self.max_fallbacks: 10 self.fallback_count = 0 11 return self.human_handoff(context) 12 13 responses = [ 14 "I didn't understand. Could you rephrase that?", 15 "I cannot help with this. You can ask a different question.", 16 "I think I misunderstood you. could you try again?" 17 ] 18 19 return responses[self.fallback_count - 1] 20 21 def human_handoff(self, context: Dict) -> str: 22 # Hand off to human agent 23 create_support_ticket(context) 24 return "I am connecting you to a customer representative. Please wait."
Analytics en Monitoring
1class ChatAnalytics: 2 def __init__(self): 3 self.metrics = { 4 "total_conversations": 0, 5 "successful_resolutions": 0, 6 "fallback_rate": 0, 7 "avg_turns_per_conversation": 0, 8 "intent_distribution": {} 9 } 10 11 def log_conversation(self, conversation: Dict): 12 self.metrics["total_conversations"] += 1 13 14 # Intent tracking 15 for message in conversation["messages"]: 16 if "intent" in message: 17 intent = message["intent"] 18 self.metrics["intent_distribution"][intent] = \ 19 self.metrics["intent_distribution"].get(intent, 0) + 1 20 21 # Resolution tracking 22 if conversation.get("resolved"): 23 self.metrics["successful_resolutions"] += 1 24 25 def get_resolution_rate(self) -> float: 26 if self.metrics["total_conversations"] == 0: 27 return 0 28 return self.metrics["successful_resolutions"] / self.metrics["total_conversations"]
Productiechecklist
Beveiliging
- Invoersanitisatie
- Rate limiting
- PII-masking
- Injectiebescherming
Prestaties
- Responstijd < 2s
- Ondersteuning voor gelijktijdige gebruikers
- Caching-laag
- Auto-scaling
Gebruikservaring
- Typindicatoren
- Foutmeldingen
- Gespreksgeschiedenis
- Meertalige ondersteuning
Conclusie
Conversationele AI is een krachtige technologie die klantinteracties transformeert. Je kunt succesvolle chatbots bouwen met een goed ontworpen dialoogflow, robuuste foutafhandeling en continue verbetering.
Bij Veni AI ontwikkelen we chatbotoplossingen voor ondernemingen.
