# Customer Support Bot with RAG (Retrieval Augmented Generation)

## Overview

The Customer Support Bot is an AI-powered system that provides automated customer support using Retrieval Augmented Generation (RAG). It answers customer queries by retrieving relevant information from a brand's knowledge base and generating contextual responses.

## Features

### Core Capabilities
- **RAG-based Responses**: Retrieves relevant documents and generates accurate answers
- **Vector Embeddings**: Uses OpenAI embeddings for semantic search
- **PII Redaction**: Automatically detects and redacts sensitive information
- **Confidence Scoring**: Evaluates answer quality and escalates when needed
- **Human Handoff**: Seamlessly escalates to human agents when necessary
- **Multi-channel Support**: Widget, email, API, and chat channels
- **Analytics Dashboard**: Comprehensive metrics and insights
- **Knowledge Base Management**: Easy upload and management of support documents

### Security & Compliance
- PII detection and redaction (email, phone, SSN, credit cards, etc.)
- Encrypted knowledge base storage
- Role-based access control (RBAC)
- GDPR/CCPA compliant data handling
- Audit logging for all interactions

## Architecture

### Components

1. **Knowledge Base Documents** (`knowledge_base_documents`)
   - Stores FAQs, manuals, policies, terms, campaign docs
   - Vector embeddings for semantic search
   - Support for PDF, DOCX, TXT files

2. **Support Conversations** (`support_conversations`)
   - Tracks customer interactions
   - Manages escalation and resolution
   - Stores satisfaction ratings

3. **Support Messages** (`support_messages`)
   - Individual messages in conversations
   - PII-redacted versions
   - Citations and confidence scores

4. **Bot Settings** (`support_bot_settings`)
   - Per-brand configuration
   - Confidence thresholds
   - Business hours
   - Widget customization

5. **Analytics** (`support_analytics`)
   - Daily aggregated metrics
   - Performance tracking
   - Topic analysis

### Services

#### RAGService
Handles retrieval augmented generation:
- Document indexing with vector embeddings
- Semantic search using cosine similarity
- Context building from retrieved documents
- LLM response generation
- Confidence scoring

#### PIIRedactionService
Protects sensitive information:
- Pattern-based PII detection
- Automatic redaction
- Custom pattern support
- Compliance with data protection regulations

## Installation & Setup

### 1. Database Migration

```bash
php artisan migrate
```

This creates the following tables:
- `knowledge_base_documents`
- `support_conversations`
- `support_messages`
- `support_bot_settings`
- `support_analytics`

### 2. Environment Configuration

Add to your `.env` file:

```env
# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-4
OPENAI_EMBEDDING_MODEL=text-embedding-ada-002
```

### 3. Initialize Bot Settings

For each brand, create bot settings:

```php
use App\Models\SupportBotSettings;

SupportBotSettings::create([
    'brand_id' => $brandId,
    'bot_enabled' => true,
    'confidence_threshold' => 70.0,
    'max_messages_before_escalation' => 10,
    'welcome_message' => 'Hello! How can I help you today?',
]);
```

## Usage

### Brand Admin: Knowledge Base Management

#### Upload Documents

```php
POST /brand/support/knowledge-base
```

**Parameters:**
- `title` (required): Document title
- `document_type` (required): faq, manual, policy, terms, campaign, other
- `content` (required): Document content
- `file` (optional): PDF, DOCX, or TXT file
- `metadata` (optional): Additional metadata

**Example:**
```javascript
const formData = new FormData();
formData.append('title', 'Product FAQ');
formData.append('document_type', 'faq');
formData.append('content', 'Q: How do I reset my password? A: ...');
formData.append('file', fileInput.files[0]);

fetch('/brand/support/knowledge-base', {
    method: 'POST',
    body: formData,
    headers: {
        'X-CSRF-TOKEN': csrfToken
    }
});
```

#### Batch Index Documents

```php
POST /brand/support/knowledge-base/batch-index
```

Indexes all active documents for the brand.

### Customer: Using the Support Bot

#### Start Conversation

```javascript
POST /api/support/conversations/start

{
    "brand_id": 1,
    "customer_name": "John Doe",
    "customer_email": "john@example.com",
    "initial_query": "How do I track my order?",
    "channel": "widget"
}
```

**Response:**
```json
{
    "success": true,
    "data": {
        "conversation": {
            "conversation_id": "conv_abc123",
            "status": "active"
        },
        "welcome_message": {
            "message_text": "Hello! How can I help you today?"
        },
        "bot_available": true
    }
}
```

#### Send Message

```javascript
POST /api/support/conversations/{conversationId}/messages

{
    "message": "I need help with my order #12345"
}
```

**Response:**
```json
{
    "success": true,
    "data": {
        "bot_message": {
            "message_text": "I can help you track your order...",
            "citations": [
                {
                    "document_id": 5,
                    "title": "Order Tracking Guide",
                    "relevance_score": 92.5
                }
            ],
            "confidence_score": 85.3
        }
    }
}
```

#### Provide Feedback

```javascript
POST /api/support/messages/{messageId}/feedback

{
    "helpful": true,
    "comment": "This answered my question perfectly!"
}
```

#### Request Human Agent

```javascript
POST /api/support/conversations/{conversationId}/request-human

{
    "reason": "Need more detailed assistance"
}
```

#### Rate Conversation

```javascript
POST /api/support/conversations/{conversationId}/rate

{
    "rating": 5,
    "feedback": "Great support experience!"
}
```

### Brand Admin: Dashboard & Analytics

#### View Dashboard

```
GET /brand/support/dashboard
```

Shows:
- Active conversations
- Escalated conversations
- Recent interactions
- Key metrics

#### Get Statistics

```
GET /brand/support/statistics?date_range=7
```

**Response:**
```json
{
    "total_conversations": 150,
    "resolved_by_bot": 120,
    "escalated": 30,
    "bot_resolution_rate": 80.0,
    "avg_confidence_score": 82.5,
    "avg_satisfaction_rating": 4.3
}
```

#### View Analytics

```
GET /brand/support/analytics?start_date=2025-01-01&end_date=2025-01-31
```

Returns daily analytics data for the specified period.

#### Low Confidence Topics

```
GET /brand/support/low-confidence-topics
```

Identifies topics where the bot struggles, helping improve the knowledge base.

### Bot Settings Configuration

#### Update Settings

```javascript
PUT /brand/support/settings

{
    "bot_enabled": true,
    "confidence_threshold": 75.0,
    "max_messages_before_escalation": 15,
    "business_hours": {
        "monday": {"start": "09:00", "end": "17:00"},
        "tuesday": {"start": "09:00", "end": "17:00"},
        "wednesday": {"start": "09:00", "end": "17:00"},
        "thursday": {"start": "09:00", "end": "17:00"},
        "friday": {"start": "09:00", "end": "17:00"},
        "saturday": "closed",
        "sunday": "closed"
    },
    "widget_settings": {
        "position": "bottom-right",
        "primary_color": "#007bff",
        "show_branding": true
    },
    "collect_feedback": true,
    "enable_human_handoff": true,
    "fallback_email": "support@brand.com"
}
```

## Widget Integration

### Basic HTML Integration

```html
<!-- Add to your website -->
<div id="support-bot-widget"></div>

<script>
window.SupportBotConfig = {
    brandId: 1,
    apiUrl: 'https://your-domain.com/api/support',
    position: 'bottom-right',
    primaryColor: '#007bff'
};
</script>
<script src="/js/support-bot-widget.js"></script>
```

### React Integration

```jsx
import SupportBotWidget from '@/components/SupportBotWidget';

function App() {
    return (
        <div>
            <SupportBotWidget
                brandId={1}
                apiUrl="/api/support"
                position="bottom-right"
                primaryColor="#007bff"
            />
        </div>
    );
}
```

## Best Practices

### Knowledge Base Management

1. **Organize by Type**: Use document types (FAQ, manual, policy) for better organization
2. **Keep Content Updated**: Regularly review and update documents
3. **Use Clear Titles**: Descriptive titles improve retrieval accuracy
4. **Add Metadata**: Tags and categories help with organization
5. **Monitor Low Confidence**: Review topics where bot struggles

### Content Writing

1. **Be Specific**: Provide detailed, actionable information
2. **Use Examples**: Include real-world examples
3. **Structure Well**: Use headings, lists, and clear formatting
4. **Cover Variations**: Include different ways customers might ask
5. **Update Regularly**: Keep information current

### Escalation Strategy

1. **Set Appropriate Thresholds**: Balance automation with quality
2. **Monitor Escalation Rates**: Adjust thresholds based on performance
3. **Train Agents**: Ensure smooth handoff process
4. **Collect Feedback**: Use escalations to improve knowledge base

### Performance Optimization

1. **Batch Index**: Use batch indexing for multiple documents
2. **Cache Embeddings**: Embeddings are cached for 1 hour
3. **Monitor API Usage**: Track OpenAI API costs
4. **Optimize Queries**: Keep queries focused and relevant

## Troubleshooting

### Bot Not Responding

1. Check bot is enabled in settings
2. Verify business hours configuration
3. Check OpenAI API key is valid
4. Review error logs

### Low Confidence Scores

1. Add more relevant documents to knowledge base
2. Improve document content quality
3. Use more specific titles and descriptions
4. Review and update existing documents

### High Escalation Rate

1. Lower confidence threshold
2. Add more comprehensive documentation
3. Review escalated conversations for patterns
4. Update knowledge base with missing information

### PII Not Being Redacted

1. Check PII patterns in settings
2. Add custom patterns if needed
3. Review detected PII in logs
4. Test with sample data

## API Reference

### Endpoints

#### Customer Endpoints
- `POST /api/support/conversations/start` - Start new conversation
- `GET /api/support/conversations/{id}` - Get conversation history
- `POST /api/support/conversations/{id}/messages` - Send message
- `POST /api/support/messages/{id}/feedback` - Provide feedback
- `POST /api/support/conversations/{id}/request-human` - Request human agent
- `POST /api/support/conversations/{id}/rate` - Rate conversation
- `POST /api/support/conversations/{id}/close` - Close conversation

#### Brand Admin Endpoints
- `GET /brand/support/dashboard` - View dashboard
- `GET /brand/support/statistics` - Get statistics
- `GET /brand/support/analytics` - Get analytics data
- `GET /brand/support/knowledge-base` - List documents
- `POST /brand/support/knowledge-base` - Upload document
- `PUT /brand/support/knowledge-base/{id}` - Update document
- `DELETE /brand/support/knowledge-base/{id}` - Delete document
- `POST /brand/support/knowledge-base/batch-index` - Batch index
- `GET /brand/support/settings` - Get bot settings
- `PUT /brand/support/settings` - Update bot settings

## Security Considerations

### PII Protection
- All customer messages are scanned for PII
- Redacted versions stored separately
- Original messages encrypted at rest
- Access controlled via policies

### Access Control
- Brand admins can manage their brand's bot
- Agents can only view assigned conversations
- Customers can only view their own conversations
- Super admins have full access

### Data Retention
- Conversations soft-deleted after closure
- Analytics aggregated daily
- PII purged according to retention policy
- Audit logs maintained for compliance

## Performance Metrics

### Key Metrics
- **Bot Resolution Rate**: % of conversations resolved without escalation
- **Average Confidence Score**: Quality of bot responses
- **Escalation Rate**: % of conversations escalated to humans
- **Average Satisfaction Rating**: Customer satisfaction (1-5 stars)
- **Response Time**: Time to first response
- **Resolution Time**: Time to resolve conversation

### Monitoring
- Real-time dashboard
- Daily analytics reports
- Low confidence topic alerts
- Escalation notifications

## Support & Maintenance

### Regular Tasks
1. Review low confidence topics weekly
2. Update knowledge base monthly
3. Analyze escalation patterns
4. Monitor API usage and costs
5. Review customer feedback

### Optimization
1. A/B test confidence thresholds
2. Experiment with different prompts
3. Refine PII patterns
4. Optimize document structure
5. Train team on best practices

## License

This Customer Support Bot system is part of the AI Business Market platform.

## Contact

For support or questions, contact the development team.