Skip to main content

AI Controller

The AI Controller provides comprehensive artificial intelligence capabilities including conversation processing, prompt template management, AI agent configuration, and intelligent automation for the VChata platform.

Base Path

/ai

Overview

This controller enables sophisticated AI-powered automation:
  • 🤖 AI Agents - Configure and manage intelligent response agents
  • 📝 Prompt Templates - Create and manage AI prompt templates
  • 🧠 Conversation Processing - Advanced conversation flow management
  • 🎯 Interactive Templates - Dynamic template management with variables
  • 🔄 Debug Tools - Conversation debugging and testing utilities
  • 📊 AI Analytics - Performance tracking and optimization insights

Authentication & Authorization

  • 🔐 All endpoints require valid JWT authentication token
  • 🏢 All operations are scoped to the user’s current organization
  • 👥 Organization membership required for all operations

AI Agents

Create AI Agent

POST /ai/agents/org_abc123
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Sales Assistant Bot",
  "description": "AI agent for handling sales conversations",
  "promptTemplateId": "template_123",
  "channels": ["DIRECT_MESSAGE", "COMMENT"],
  "autoResponse": true,
  "responseDelay": 30,
  "maxResponsesPerConversation": 5,
  "businessHoursOnly": false,
  "businessHours": {
    "start": "09:00",
    "end": "17:00",
    "timezone": "America/New_York"
  }
}
{
  "success": true,
  "aiAgent": {
    "id": "agent_123",
    "organizationId": "org_abc123",
    "name": "Sales Assistant Bot",
    "description": "AI agent for handling sales conversations",
    "promptTemplateId": "template_123",
    "channels": ["DIRECT_MESSAGE", "COMMENT"],
    "autoResponse": true,
    "responseDelay": 30,
    "maxResponsesPerConversation": 5,
    "businessHoursOnly": false,
    "businessHours": {
      "start": "09:00",
      "end": "17:00",
      "timezone": "America/New_York"
    },
    "status": "ACTIVE",
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:00Z"
  },
  "message": "AI agent created successfully"
}
Description: Creates a new AI agent for automated conversation handling.
body
object

Get AI Agents

GET /ai/agents/org_abc123?status=ACTIVE&channel=DIRECT_MESSAGE
Authorization: Bearer <token>
{
  "success": true,
  "aiAgents": [
    {
      "id": "agent_123",
      "name": "Sales Assistant Bot",
      "description": "AI agent for handling sales conversations",
      "channels": ["DIRECT_MESSAGE", "COMMENT"],
      "autoResponse": true,
      "responseDelay": 30,
      "status": "ACTIVE",
      "conversationCount": 150,
      "averageResponseTime": 2.5,
      "satisfactionScore": 4.2,
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-20T15:30:00Z"
    }
  ],
  "total": 1,
  "message": "AI agents retrieved successfully"
}
Description: Retrieves AI agents with optional filtering.

Update AI Agent

PATCH /ai/agents/org_abc123/agent_123
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Updated Sales Assistant Bot",
  "autoResponse": false,
  "responseDelay": 60,
  "businessHoursOnly": true
}
{
  "success": true,
  "aiAgent": {
    "id": "agent_123",
    "name": "Updated Sales Assistant Bot",
    "autoResponse": false,
    "responseDelay": 60,
    "businessHoursOnly": true,
    "updatedAt": "2024-01-20T16:00:00Z"
  },
  "message": "AI agent updated successfully"
}
Description: Updates an existing AI agent configuration.

Delete AI Agent

DELETE /ai/agents/org_abc123/agent_123
Authorization: Bearer <token>
{
  "success": true,
  "message": "AI agent deleted successfully"
}
Description: Permanently deletes an AI agent.

Prompt Templates

Create Prompt Template

POST /ai/templates/org_abc123
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Sales Response Template",
  "description": "Template for sales conversation responses",
  "templateContent": "You are a helpful sales assistant for {{companyName}}. Help customers with their inquiries about {{products}}. Be professional and friendly.",
  "inputVariables": ["companyName", "products"],
  "businessInfo": {
    "companyName": "Acme Corp",
    "industry": "Technology",
    "products": ["Product A", "Product B"],
    "services": ["Consulting", "Support"]
  },
  "personalitySettings": {
    "tone": "professional",
    "style": "conversational",
    "expertise": "sales",
    "language": "en"
  },
  "isActive": true
}
{
  "success": true,
  "promptTemplate": {
    "id": "template_123",
    "organizationId": "org_abc123",
    "name": "Sales Response Template",
    "description": "Template for sales conversation responses",
    "templateContent": "You are a helpful sales assistant for {{companyName}}. Help customers with their inquiries about {{products}}. Be professional and friendly.",
    "inputVariables": ["companyName", "products"],
    "businessInfo": {
      "companyName": "Acme Corp",
      "industry": "Technology",
      "products": ["Product A", "Product B"],
      "services": ["Consulting", "Support"]
    },
    "personalitySettings": {
      "tone": "professional",
      "style": "conversational",
      "expertise": "sales",
      "language": "en"
    },
    "isActive": true,
    "usageCount": 0,
    "testCount": 0,
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:00Z"
  },
  "message": "Prompt template created successfully"
}
Description: Creates a new AI prompt template with variables and business context.
body
object

Get Prompt Templates

GET /ai/templates/org_abc123?isActive=true&search=sales&page=1&limit=10
Authorization: Bearer <token>
{
  "success": true,
  "promptTemplates": [
    {
      "id": "template_123",
      "name": "Sales Response Template",
      "description": "Template for sales conversation responses",
      "templateContent": "You are a helpful sales assistant...",
      "inputVariables": ["companyName", "products"],
      "personalitySettings": {
        "tone": "professional",
        "style": "conversational"
      },
      "isActive": true,
      "usageCount": 150,
      "testCount": 25,
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-20T15:30:00Z"
    }
  ],
  "pagination": {
    "total": 1,
    "page": 1,
    "limit": 10,
    "hasMore": false
  },
  "message": "Prompt templates retrieved successfully"
}
Description: Retrieves prompt templates with optional filtering and pagination.

Test Prompt Template

POST /ai/templates/template_123/test
Authorization: Bearer <token>
Content-Type: application/json

{
  "testMessage": "Hi, I'm interested in your products. Can you tell me more?",
  "variables": {
    "companyName": "Acme Corp",
    "products": "our innovative software solutions"
  }
}
{
  "success": true,
  "testResult": {
    "templateId": "template_123",
    "testMessage": "Hi, I'm interested in your products. Can you tell me more?",
    "variables": {
      "companyName": "Acme Corp",
      "products": "our innovative software solutions"
    },
    "response": "Hello! I'd be happy to help you learn more about our innovative software solutions. We offer a comprehensive suite of tools designed to streamline your business operations. Which specific area are you most interested in?",
    "responseTime": 1.2,
    "qualityScore": 0.85,
    "testedAt": "2024-01-20T16:00:00Z"
  },
  "message": "Prompt template tested successfully"
}
Description: Tests a prompt template with sample input and variables.

Interactive Templates

Create Interactive Template

POST /ai/interactive-templates/org_abc123
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Dynamic Sales Template",
  "description": "Interactive template with dynamic content generation",
  "templateContent": "You are {{agentName}}, a {{role}} at {{companyName}}. Help customers with {{inquiryType}}.",
  "inputVariables": ["agentName", "role", "companyName", "inquiryType"],
  "businessInfo": {
    "companyName": "Acme Corp",
    "industry": "Technology"
  },
  "abTestVariant": {
    "variant": "A",
    "testId": "test_123",
    "weight": 0.5
  },
  "isActive": true
}
{
  "success": true,
  "interactiveTemplate": {
    "id": "interactive_template_123",
    "organizationId": "org_abc123",
    "name": "Dynamic Sales Template",
    "description": "Interactive template with dynamic content generation",
    "templateContent": "You are {{agentName}}, a {{role}} at {{companyName}}. Help customers with {{inquiryType}}.",
    "inputVariables": ["agentName", "role", "companyName", "inquiryType"],
    "businessInfo": {
      "companyName": "Acme Corp",
      "industry": "Technology"
    },
    "abTestVariant": {
      "variant": "A",
      "testId": "test_123",
      "weight": 0.5
    },
    "isActive": true,
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:00Z"
  },
  "message": "Interactive template created successfully"
}
Description: Creates an interactive prompt template with A/B testing support.

Get Interactive Templates

GET /ai/interactive-templates/org_abc123?testId=test_123&isActive=true
Authorization: Bearer <token>
{
  "success": true,
  "interactiveTemplates": [
    {
      "id": "interactive_template_123",
      "name": "Dynamic Sales Template",
      "description": "Interactive template with dynamic content generation",
      "abTestVariant": {
        "variant": "A",
        "testId": "test_123",
        "weight": 0.5
      },
      "isActive": true,
      "usageCount": 75,
      "performance": {
        "averageResponseTime": 2.1,
        "satisfactionScore": 4.3,
        "conversionRate": 12.5
      },
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-20T15:30:00Z"
    }
  ],
  "total": 1,
  "message": "Interactive templates retrieved successfully"
}
Description: Retrieves interactive templates with performance metrics.

Debug and Testing

Debug Conversation

POST /debug/conversations/org_abc123/debug
Authorization: Bearer <token>
Content-Type: application/json

{
  "agentId": "agent_123",
  "userMessage": "I need help with my order",
  "conversationHistory": [
    {
      "role": "user",
      "content": "Hello"
    },
    {
      "role": "assistant",
      "content": "Hi! How can I help you today?"
    }
  ],
  "debugOptions": {
    "includePrompt": true,
    "includeVariables": true,
    "includeProcessingSteps": true,
    "includePerformance": true
  }
}
{
  "success": true,
  "debugInfo": {
    "agentId": "agent_123",
    "userMessage": "I need help with my order",
    "conversationHistory": [
      {
        "role": "user",
        "content": "Hello"
      },
      {
        "role": "assistant",
        "content": "Hi! How can I help you today?"
      }
    ],
    "processedPrompt": "You are a helpful sales assistant for Acme Corp. Help customers with their inquiries about our products. Be professional and friendly.\n\nConversation History:\nUser: Hello\nAssistant: Hi! How can I help you today?\n\nUser: I need help with my order",
    "variables": {
      "companyName": "Acme Corp",
      "products": "our innovative software solutions"
    },
    "processingSteps": [
      "Template loaded",
      "Variables substituted",
      "Context enhanced",
      "Response generated"
    ],
    "response": "I'd be happy to help you with your order! Could you please provide me with your order number so I can look up the details for you?",
    "performance": {
      "totalTime": 1.8,
      "templateLoadTime": 0.1,
      "variableSubstitutionTime": 0.2,
      "contextEnhancementTime": 0.3,
      "aiGenerationTime": 1.2
    },
    "qualityMetrics": {
      "relevanceScore": 0.92,
      "completenessScore": 0.88,
      "toneScore": 0.95
    },
    "debuggedAt": "2024-01-20T16:00:00Z"
  },
  "message": "Conversation debug completed successfully"
}
Description: Debug a conversation to understand AI processing steps and performance.

AI Status Values

  • ACTIVE - AI agent is active and responding
  • PAUSED - AI agent is temporarily paused
  • INACTIVE - AI agent is inactive
  • TESTING - AI agent is in testing mode

Channel Types

  • DIRECT_MESSAGE - Private messages/DMs
  • COMMENT - Public comments on posts
  • POST - Direct posts (for posting content)

Error Responses

Common Errors

{
  "success": false,
  "statusCode": 400,
  "message": [
    "name is required",
    "promptTemplateId must be a valid UUID",
    "channels must contain at least one valid channel type"
  ],
  "error": "Bad Request"
}
{
  "success": false,
  "statusCode": 404,
  "message": "AI agent not found or you don't have access",
  "error": "Not Found"
}
{
  "success": false,
  "statusCode": 409,
  "message": "Template name already exists",
  "error": "Conflict"
}
{
  "success": false,
  "statusCode": 502,
  "message": "AI service temporarily unavailable",
  "error": "Bad Gateway"
}

Advanced Features

Multi-Channel Support

AI agents can respond across multiple channels simultaneously:
  • Unified Responses - Consistent responses across all channels
  • Channel-Specific Logic - Different behavior per channel type
  • Cross-Platform Integration - Seamless integration with social media platforms

A/B Testing

Interactive templates support A/B testing:
  • Variant Management - Multiple template variants
  • Performance Tracking - Compare variant performance
  • Automatic Optimization - AI-powered variant selection

Business Hours Management

  • Timezone Support - Global timezone handling
  • Custom Hours - Flexible business hour configuration
  • Holiday Support - Holiday and exception handling
  • Graceful Degradation - Fallback responses outside business hours

Performance Optimization

  • Response Caching - Intelligent response caching
  • Batch Processing - Efficient batch operations
  • Rate Limiting - Respect API rate limits
  • Error Recovery - Automatic retry mechanisms