> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vchata.com/llms.txt
> Use this file to discover all available pages before exploring further.

# AI Controller

> AI-powered conversation handling, prompt templates, and intelligent automation API endpoints

# 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

<RequestExample>
  ```http theme={null}
  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"
    }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "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"
  }
  ```
</ResponseExample>

**Description**: Creates a new AI agent for automated conversation handling.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="name" type="string" required>
      Name of the AI agent
    </ParamField>

    <ParamField path="description" type="string">
      Description of the AI agent's purpose
    </ParamField>

    <ParamField path="promptTemplateId" type="string" required>
      ID of the prompt template to use
    </ParamField>

    <ParamField path="channels" type="array" required>
      Channels the agent responds to (DIRECT\_MESSAGE, COMMENT, POST)
    </ParamField>

    <ParamField path="autoResponse" type="boolean">
      Whether to automatically respond (default: true)
    </ParamField>

    <ParamField path="responseDelay" type="number">
      Delay in seconds before responding (default: 0)
    </ParamField>

    <ParamField path="maxResponsesPerConversation" type="number">
      Maximum responses per conversation (default: 10)
    </ParamField>

    <ParamField path="businessHoursOnly" type="boolean">
      Whether to only respond during business hours (default: false)
    </ParamField>

    <ParamField path="businessHours" type="object">
      Business hours configuration

      <ParamField path="start" type="string">
        Start time (HH:MM format)
      </ParamField>

      <ParamField path="end" type="string">
        End time (HH:MM format)
      </ParamField>

      <ParamField path="timezone" type="string">
        Timezone (e.g., "America/New\_York")
      </ParamField>
    </ParamField>
  </Expandable>
</ParamField>

### Get AI Agents

<RequestExample>
  ```http theme={null}
  GET /ai/agents/org_abc123?status=ACTIVE&channel=DIRECT_MESSAGE
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "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"
  }
  ```
</ResponseExample>

**Description**: Retrieves AI agents with optional filtering.

### Update AI Agent

<RequestExample>
  ```http theme={null}
  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
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "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"
  }
  ```
</ResponseExample>

**Description**: Updates an existing AI agent configuration.

### Delete AI Agent

<RequestExample>
  ```http theme={null}
  DELETE /ai/agents/org_abc123/agent_123
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "message": "AI agent deleted successfully"
  }
  ```
</ResponseExample>

**Description**: Permanently deletes an AI agent.

## Prompt Templates

### Create Prompt Template

<RequestExample>
  ```http theme={null}
  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
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "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"
  }
  ```
</ResponseExample>

**Description**: Creates a new AI prompt template with variables and business context.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="name" type="string" required>
      Name of the prompt template
    </ParamField>

    <ParamField path="description" type="string">
      Description of the template's purpose
    </ParamField>

    <ParamField path="templateContent" type="string" required>
      Template content with variable placeholders ({{variableName}})
    </ParamField>

    <ParamField path="inputVariables" type="array">
      Array of input variable names
    </ParamField>

    <ParamField path="businessInfo" type="object">
      Business context information

      <ParamField path="companyName" type="string">
        Company name
      </ParamField>

      <ParamField path="industry" type="string">
        Industry type
      </ParamField>

      <ParamField path="products" type="array">
        Array of product names
      </ParamField>

      <ParamField path="services" type="array">
        Array of service names
      </ParamField>
    </ParamField>

    <ParamField path="personalitySettings" type="object">
      AI personality configuration

      <ParamField path="tone" type="string">
        Tone (professional, friendly, casual)
      </ParamField>

      <ParamField path="style" type="string">
        Style (conversational, formal, technical)
      </ParamField>

      <ParamField path="expertise" type="string">
        Expertise area (sales, support, marketing)
      </ParamField>

      <ParamField path="language" type="string">
        Language code (en, es, fr, etc.)
      </ParamField>
    </ParamField>

    <ParamField path="isActive" type="boolean">
      Whether the template is active (default: true)
    </ParamField>
  </Expandable>
</ParamField>

### Get Prompt Templates

<RequestExample>
  ```http theme={null}
  GET /ai/templates/org_abc123?isActive=true&search=sales&page=1&limit=10
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "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"
  }
  ```
</ResponseExample>

**Description**: Retrieves prompt templates with optional filtering and pagination.

### Test Prompt Template

<RequestExample>
  ```http theme={null}
  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"
    }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "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"
  }
  ```
</ResponseExample>

**Description**: Tests a prompt template with sample input and variables.

## Interactive Templates

### Create Interactive Template

<RequestExample>
  ```http theme={null}
  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
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "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"
  }
  ```
</ResponseExample>

**Description**: Creates an interactive prompt template with A/B testing support.

### Get Interactive Templates

<RequestExample>
  ```http theme={null}
  GET /ai/interactive-templates/org_abc123?testId=test_123&isActive=true
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "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"
  }
  ```
</ResponseExample>

**Description**: Retrieves interactive templates with performance metrics.

## Debug and Testing

### Debug Conversation

<RequestExample>
  ```http theme={null}
  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
    }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "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"
  }
  ```
</ResponseExample>

**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

<ResponseExample status="400">
  ```json theme={null}
  {
    "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"
  }
  ```
</ResponseExample>

<ResponseExample status="404">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 404,
    "message": "AI agent not found or you don't have access",
    "error": "Not Found"
  }
  ```
</ResponseExample>

<ResponseExample status="409">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 409,
    "message": "Template name already exists",
    "error": "Conflict"
  }
  ```
</ResponseExample>

<ResponseExample status="502">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 502,
    "message": "AI service temporarily unavailable",
    "error": "Bad Gateway"
  }
  ```
</ResponseExample>

## 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
