# Customer Support Bot div strong 🔨 In Development — This section is still being developed and may change. This comprehensive example demonstrates how to build an intelligent customer support assistant that can handle common inquiries, provide troubleshooting guidance, and escalate complex issues to human agents. ## Overview We'll create a customer support bot that: 1. Understands and categorizes customer inquiries 2. Provides automated responses to common questions 3. Guides customers through troubleshooting steps 4. Escalates complex issues to human support 5. Tracks support interactions and outcomes 6. Integrates with help desk and CRM systems ## Prerequisites - Freddy API account with function calling enabled - Support ticket system integration (Zendesk, Intercom, etc.) - Knowledge base or FAQ system - Customer database access ## Step 1: Define Support Functions Create functions for handling support inquiries, knowledge base searches, and ticket management: ```python import json from typing import List, Dict, Optional from support_system import SupportAPI, KnowledgeBaseAPI class SupportFunctions: def __init__(self, support_api_key: str, kb_api_key: str): self.support = SupportAPI(support_api_key) self.knowledge_base = KnowledgeBaseAPI(kb_api_key) def search_knowledge_base(self, query: str, category: str = None) -> Dict: """Search the knowledge base for relevant articles and solutions.""" try: results = self.knowledge_base.search( query=query, category=category, limit=5 ) return { "articles": [ { "id": article["id"], "title": article["title"], "summary": article["summary"], "url": article["url"], "relevance_score": article["score"] } for article in results["articles"] ], "total_found": results["total"], "search_query": query } except Exception as e: return {"error": f"Knowledge base search failed: {str(e)}"} def create_support_ticket(self, customer_id: str, issue: str, priority: str = "medium", category: str = "general") -> Dict: """Create a new support ticket for the customer.""" try: ticket = self.support.create_ticket( customer_id=customer_id, subject=f"Support Request: {issue[:50]}...", description=issue, priority=priority, category=category ) return { "ticket_id": ticket["id"], "status": ticket["status"], "priority": priority, "estimated_response_time": ticket.get("eta"), "support_agent": ticket.get("assigned_to") } except Exception as e: return {"error": f"Failed to create ticket: {str(e)}"} def check_ticket_status(self, ticket_id: str) -> Dict: """Check the status of an existing support ticket.""" try: ticket = self.support.get_ticket(ticket_id) return { "ticket_id": ticket_id, "status": ticket["status"], "priority": ticket["priority"], "created_at": ticket["created_at"], "last_updated": ticket["last_updated"], "assigned_agent": ticket.get("assigned_to"), "responses": ticket.get("responses", []) } except Exception as e: return {"error": f"Failed to check ticket status: {str(e)}"} def escalate_issue(self, ticket_id: str, reason: str, urgency: str = "high") -> Dict: """Escalate a support ticket to higher priority or different department.""" try: escalated = self.support.escalate_ticket( ticket_id=ticket_id, reason=reason, urgency=urgency ) return { "ticket_id": ticket_id, "new_priority": escalated["priority"], "escalation_reason": reason, "escalated_to": escalated.get("escalated_to"), "estimated_resolution": escalated.get("eta") } except Exception as e: return {"error": f"Failed to escalate ticket: {str(e)}"} def get_customer_info(self, customer_id: str) -> Dict: """Get customer information and support history.""" try: customer = self.support.get_customer(customer_id) return { "customer_id": customer_id, "name": customer["name"], "email": customer["email"], "support_history": customer.get("tickets", []), "account_status": customer.get("status"), "subscription_tier": customer.get("tier") } except Exception as e: return {"error": f"Failed to get customer info: {str(e)}"} def provide_troubleshooting_steps(self, issue_type: str) -> Dict: """Provide step-by-step troubleshooting guidance.""" try: steps = self.knowledge_base.get_troubleshooting_steps(issue_type) return { "issue_type": issue_type, "steps": [ { "step": i + 1, "instruction": step["instruction"], "expected_result": step["expected_result"], "tips": step.get("tips", []) } for i, step in enumerate(steps["steps"]) ], "common_solutions": steps.get("common_solutions", []) } except Exception as e: return {"error": f"Failed to get troubleshooting steps: {str(e)}"} ``` ## Step 2: Create the Support Assistant ```python import os from freddy import Freddy # Initialize support functions support_functions = SupportFunctions( support_api_key=os.getenv("SUPPORT_API_KEY"), kb_api_key=os.getenv("KB_API_KEY") ) # Create the support assistant assistant = freddy.assistants.create( name="Customer Support Assistant", instructions="""You are a helpful customer support assistant. Your role is to: 1. Understand and categorize customer inquiries 2. Provide immediate answers to common questions using the knowledge base 3. Guide customers through troubleshooting steps when appropriate 4. Create support tickets for issues that need human attention 5. Escalate urgent or complex issues appropriately 6. Follow up on existing tickets and provide status updates When handling inquiries: - Ask clarifying questions if the issue isn't clear - Be empathetic and professional in all responses - Use the knowledge base to provide accurate, up-to-date information - Escalate issues that are beyond your scope or expertise - Always confirm resolution and ask if there's anything else you can help with For technical issues: - Guide customers through troubleshooting steps systematically - Ask them to confirm each step before proceeding - Document what they've already tried - Escalate if basic troubleshooting doesn't resolve the issue Always: - Maintain customer privacy and data security - Use clear, non-technical language when possible - Be patient and understanding - Follow company policies and procedures - Log all interactions for quality assurance""", model="gpt-4", tools=[ { "type": "function", "function": { "name": "search_knowledge_base", "description": "Search knowledge base for solutions to common issues", "parameters": { "type": "object", "properties": { "query": {"type": "string", "description": "Search query"}, "category": {"type": "string", "description": "Issue category"} }, "required": ["query"] } } }, { "type": "function", "function": { "name": "create_support_ticket", "description": "Create a support ticket for issues needing human attention", "parameters": { "type": "object", "properties": { "customer_id": {"type": "string", "description": "Customer ID"}, "issue": {"type": "string", "description": "Issue description"}, "priority": {"type": "string", "description": "Issue priority"}, "category": {"type": "string", "description": "Issue category"} }, "required": ["customer_id", "issue"] } } }, { "type": "function", "function": { "name": "check_ticket_status", "description": "Check the status of an existing support ticket", "parameters": { "type": "object", "properties": { "ticket_id": {"type": "string", "description": "Ticket ID"} }, "required": ["ticket_id"] } } }, { "type": "function", "function": { "name": "provide_troubleshooting_steps", "description": "Provide step-by-step troubleshooting guidance", "parameters": { "type": "object", "properties": { "issue_type": {"type": "string", "description": "Type of issue"} }, "required": ["issue_type"] } } } ] ) ``` ## Step 3: Implement Support Workflows ```python # Example support conversation workflow def handle_support_conversation(customer_id: str, initial_message: str): """Handle a complete support conversation from initial inquiry to resolution.""" # Create thread for this support session thread = freddy.threads.create( metadata={ "customer_id": customer_id, "session_type": "support", "start_time": datetime.now().isoformat() } ) # Send initial customer message freddy.threads.messages.create( thread_id=thread.id, role="user", content=initial_message ) # Run assistant to analyze the inquiry run = freddy.threads.runs.create( thread_id=thread.id, assistant_id=assistant.id ) # Process the conversation while run.status not in ["completed", "failed", "cancelled"]: run = freddy.threads.runs.retrieve(thread_id=thread.id, run_id=run.id) # Check if any functions were called if hasattr(run, 'tool_calls') and run.tool_calls: for tool_call in run.tool_calls: if tool_call.function.name == "search_knowledge_base": # Handle knowledge base search pass elif tool_call.function.name == "create_support_ticket": # Handle ticket creation pass if run.status == "completed": # Get final response messages = freddy.threads.messages.list(thread_id=thread.id) return messages.data[-1].content[0].text.value return "Support session completed" ``` ## Step 4: Advanced Support Features ### Sentiment Analysis ```python def analyze_customer_sentiment(message: str) -> Dict: """Analyze the sentiment of customer messages to prioritize urgent issues.""" # Use AI to detect urgency, frustration, or satisfaction sentiment = freddy.analyze_sentiment(message) return { "sentiment": sentiment["label"], # positive, negative, neutral "confidence": sentiment["score"], "urgency_indicators": detect_urgency_indicators(message), "recommended_priority": calculate_priority(sentiment, message) } ``` ### Auto-Categorization ```python def categorize_inquiry(message: str) -> Dict: """Automatically categorize support inquiries for better routing.""" categories = [ "billing", "technical", "account", "product", "shipping", "returns", "general" ] # Use AI to categorize the inquiry category = freddy.categorize_text(message, categories) return { "primary_category": category["primary"], "confidence": category["confidence"], "subcategories": category.get("subcategories", []), "requires_human": category.get("escalation_recommended", False) } ``` ### Proactive Support ```python def identify_at_risk_customers() -> List[Dict]: """Identify customers who might need proactive support.""" # Analyze support history and behavior patterns at_risk = [] # Check for customers with multiple recent tickets recent_tickets = support.get_recent_tickets(days=7) # Check for customers with negative sentiment trends sentiment_trends = analyze_sentiment_trends() # Check for customers with unresolved issues unresolved = support.get_unresolved_tickets() return at_risk ``` ## Step 5: Integration and Deployment ### Help Desk Integration ```python def sync_with_help_desk(ticket_data: Dict): """Sync support interactions with external help desk systems.""" # Create or update ticket in Zendesk, Intercom, etc. external_ticket = help_desk.create_ticket(ticket_data) # Sync conversation history for message in conversation_history: help_desk.add_comment(external_ticket["id"], message) return external_ticket ``` ### Quality Assurance ```python def evaluate_support_quality(conversation: List[Dict]) -> Dict: """Evaluate the quality of support interactions.""" metrics = { "response_time": calculate_average_response_time(conversation), "resolution_rate": calculate_resolution_rate(conversation), "customer_satisfaction": analyze_satisfaction_signals(conversation), "escalation_rate": calculate_escalation_rate(conversation), "knowledge_base_utilization": measure_kb_usage(conversation) } return { "overall_score": calculate_overall_score(metrics), "metrics": metrics, "recommendations": generate_improvement_recommendations(metrics) } ``` ## Step 6: Testing and Monitoring ### Test Scenarios 1. **Simple Question**: "How do I reset my password?" 2. **Technical Issue**: "My app keeps crashing when I try to upload photos" 3. **Billing Inquiry**: "I was charged twice this month" 4. **Complex Issue**: "I need help with my enterprise account setup" 5. **Follow-up**: "Can you check on ticket #12345?" ### Monitoring and Analytics - Track resolution rates by category - Monitor average response times - Analyze customer satisfaction scores - Identify common failure points - Track knowledge base effectiveness ## Best Practices 1. **Empathy First**: Always acknowledge the customer's issue and show understanding 2. **Clear Communication**: Use simple language and avoid technical jargon 3. **Proper Escalation**: Know when to escalate rather than trying to solve everything 4. **Documentation**: Keep detailed records of all interactions 5. **Continuous Learning**: Regularly update knowledge base and assistant instructions ## Deployment Checklist - [ ] Test all support functions thoroughly - [ ] Set up proper error handling and fallbacks - [ ] Configure escalation procedures - [ ] Train human support team on bot capabilities - [ ] Set up monitoring and alerting - [ ] Implement regular knowledge base updates - [ ] Configure proper access controls and permissions ## Troubleshooting **Bot not understanding inquiries**: Improve the categorization and intent recognition in your assistant instructions. **Poor knowledge base results**: Regularly update and expand your knowledge base with new solutions. **High escalation rate**: Review assistant instructions and add more comprehensive solutions to the knowledge base. **Customer frustration**: Monitor sentiment and adjust response strategies accordingly. For more help, check the [Function Calling Guide](/docs/documentation/core-concepts/function-calling) or [API Reference](/docs/api-reference/introduction).