Conversation API

The Conversation API enables real-time interactions with deployed assistants, handling message exchanges, context management, and conversation history.

Ask Assistant

Sends a message to an assistant and receives a response.

Endpoint

POST /api/ai-hub/assistant/ask

Request Body

{
  "message": {
    "id": "msg_123",
    "role": "user",
    "content": "How do I reset my password?",
    "createdAt": "2024-01-20T15:30:00Z"
  },
  "id": "conv_550e8400-e29b-41d4",
  "assistantId": "550e8400-e29b-41d4-a716-446655440001",
  "metadata": {
    "user_id": "user_456",
    "session_id": "session_789",
    "channel": "web"
  },
  "foldersId": [
    "550e8400-e29b-41d4-a716-446655440000",
    "550e8400-e29b-41d4-a716-446655440003"
  ]
}

Request Fields

Message Object

  • id: Unique message identifier
  • role: Message sender role ("user" or "assistant")
  • content: The message text
  • createdAt: Timestamp of message creation

Core Fields

  • id: Conversation/thread identifier for maintaining context
  • assistantId: The assistant to interact with
  • metadata: Additional context information (automatically lowercased keys)
  • foldersId: Optional array of folder IDs to search for context

Preview Mode

For testing assistants before deployment, you can use preview mode:

{
  "message": {
    "id": "msg_123",
    "role": "user",
    "content": "Test message"
  },
  "id": "preview_conv_123",
  "assistantId": "preview_assistant",
  "previewAssistantData": {
    "name": "Test Assistant",
    "description": "Testing new configuration"
  }
}

Response

The assistant returns a streaming response or a complete message:

{
  "success": true,
  "message": {
    "id": "msg_124",
    "role": "assistant",
    "content": "To reset your password, please follow these steps:\n\n1. Go to the login page\n2. Click on 'Forgot Password'\n3. Enter your email address\n4. Check your email for the reset link\n5. Follow the link to create a new password\n\nThe reset link will expire in 24 hours. If you need further assistance, please contact support.",
    "createdAt": "2024-01-20T15:30:05Z"
  },
  "metadata": {
    "processing_time": 1500,
    "tokens_used": 85,
    "knowledge_sources": ["FAQ_Doc_001", "Password_Policy_v2"]
  }
}

Conversation Management

Conversation Context

The API maintains conversation context using the id field. Each conversation has:

  • Persistent Context: Messages within the same conversation ID are remembered
  • Isolated Sessions: Different conversation IDs maintain separate contexts
  • Metadata Tracking: Custom metadata is preserved throughout the conversation

Best Practices

  1. Conversation IDs: Use consistent IDs for ongoing conversations
    {
      "id": "user_456_session_20240120",
      "assistantId": "550e8400-e29b-41d4-a716-446655440001"
    }
    
  2. Metadata Usage: Include relevant context in metadata
    {
      "metadata": {
        "user_tier": "premium",
        "language": "pt-BR",
        "timezone": "America/Sao_Paulo"
      }
    }
    
  3. Folder Context: Specify relevant knowledge base folders
    {
      "foldersId": [
        "product_docs_folder_id",
        "user_specific_folder_id"
      ]
    }
    

Message Types

Text Messages

Standard text-based interactions:

{
  "message": {
    "role": "user",
    "content": "What are your business hours?"
  }
}

System Messages

For providing context or instructions:

{
  "message": {
    "role": "system",
    "content": "User is a VIP customer with priority support"
  }
}

Error Handling

Validation Errors

{
  "success": false,
  "error": "Message parse problem from ask assistant",
  "issues": [
    {
      "field": "assistantId",
      "message": "The assistant id is required!"
    }
  ]
}

Rate Limiting

{
  "success": false,
  "error": "Rate limit exceeded",
  "retry_after": 60
}

Assistant Not Found

{
  "success": false,
  "error": "Assistant not found or not deployed",
  "assistant_id": "550e8400-e29b-41d4-a716-446655440001"
}

Integration Examples

Web Application

async function askAssistant(userMessage) {
  const response = await fetch('/api/ai-hub/assistant/ask', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${authToken}`
    },
    body: JSON.stringify({
      message: {
        id: generateMessageId(),
        role: 'user',
        content: userMessage,
        createdAt: new Date().toISOString()
      },
      id: sessionId,
      assistantId: ASSISTANT_ID,
      metadata: {
        user_id: currentUser.id,
        channel: 'web'
      }
    })
  });
  
  return response.json();
}

WhatsApp Integration

async function handleWhatsAppMessage(phoneNumber, message) {
  const response = await askAssistant({
    message: {
      id: `whatsapp_${Date.now()}`,
      role: 'user',
      content: message
    },
    id: `whatsapp_${phoneNumber}`,
    assistantId: WHATSAPP_ASSISTANT_ID,
    metadata: {
      phone_number: phoneNumber,
      channel: 'whatsapp'
    }
  });
  
  // Send response back via WhatsApp API
  await sendWhatsAppMessage(phoneNumber, response.message.content);
}