Captivate Chat API Documentation

Introduction

This documentation explains the functionalities of the Captivate Chat API and provides examples for integrating it into your project.

Embedding the Script

Include the Captivate Chat API script in your HTML file:

<script src="dist/captivate-chat-api.js"></script>

Library Initialization

Initialize the Captivate Chat API with your API key and environment:


const captivateAPI = new CaptivateChatAPI(apiKey, environment);
await captivateAPI.connect();
      

Create a Conversation

Start a new conversation with the following method:


      const conversation = await captivateAPI.createConversation(userId, userBasicInfo, userData, mode);
        

Parameters:

Conversation Modes: Bot-First vs. User-First

In a conversation, you can define the starting point by choosing whether the bot or the user initiates the interaction. This is controlled by two modes: bot-first and user-first.

Bot-First Mode

In bot-first mode, the conversation begins with a message or action from the bot. This is the default setting, meaning if no parameter is specified, the bot will initiate the conversation.

Example: The bot might start by greeting the user or presenting options for interaction, such as buttons or cards. The user responds based on the options or prompts provided by the bot.


        // Bot-First Mode (default)
        const conversation = await captivateAPI.createConversation(userId, userBasicInfo, userData, 'bot-first');
        

User-First Mode

In user-first mode, the conversation starts with the user’s input. This mode can be used when the bot waits for the user to send a message first before responding. The bot listens for any incoming message from the user and responds accordingly.

Example: This is useful in scenarios where the user has specific needs or queries they want to address, and the bot waits for the user’s prompt to begin the interaction.


        // User-First Mode
        const conversation = await captivateAPI.createConversation(userId, userBasicInfo, userData, 'user-first');
        

Default Behavior

The default conversation mode is bot-first, meaning the bot will automatically initiate the conversation unless you specify otherwise. This ensures that the bot can start guiding the user through the interaction immediately without requiring input from the user first.

Choosing the appropriate mode depends on your application’s needs and how you want to manage the user interaction flow. For example, bot-first can be used for guided experiences where the bot leads, while user-first can be used for more open-ended conversations where the user has more control.

Retrieve an Existing Conversation

Retrieve a conversation by its ID:


const conversation = await captivateAPI.getConversation(conversationId);
      

Send a Message

Send a message to the bot using:


await conversation.sendMessage('Hello, how can I help you?');
      

Handle Messages

Listen for bot or agent responses using the onMessage method:


      conversation.onMessage((message, type) => {
        if (type === 'human_agent') {
          console.log('Human Agent says:', message);
        } else if (type === 'ai_agent') {
          console.log('AI Agent says:', message);
        } else {
          console.log('Unknown message type:', message);
        }
      });
        

Message Format:


      [{
        // Current supported types
        "type": "text || buttons || cards || html || md || files || any",
        
        // Sent only when type is "text"
        "text": "bot text message",
        
        // Sent only when type is "buttons"
        "buttons": {
          "type": "buttons",
          "buttons": [
            {
              "title": "Button 1",
              "url": "https://example.com/1"
            },
            {
              "title": "Button 2",
              "url": "https://example.com/2"
            }
          ]
        },
        
        // Sent only when type is "cards"
        "cards": {
          "type": "cards",
          "cards": [
            {
              "text": "Card 1 Title",
              "description": "This is a description of the first card.",
              "image_url": "https://example.com/image1.jpg",
              "link": "https://example.com/card1"
            },
            {
              "text": "Card 2 Title",
              "description": "This is a description of the second card.",
              "image_url": "https://example.com/image2.jpg",
              "link": "https://example.com/card2"
            }
          ]
        },
        
        // Sent only when type is "html"
        "html": {
          "type": "html",
          "html": "

This is an HTML message.

" }, // Sent only when type is "md" "md": { "type": "md", "md": "**Markdown** message with *italic* and `code`." }, // Sent only when type is "files" "files": { "type": "files", "files": [ { "type": "image", "url": "https://example.com/image.jpg", "mimetype": "image/jpeg", "filename": null }, { "type": "document", "url": "https://example.com/example.pdf", "mimetype": "application/pdf", "filename": "example.pdf" }, { "type": "audio", "url": "https://example.com/audio.mp3", "mimetype": "audio/mpeg", "filename": "audio.mp3" } ] }, // Sent only when type is "any" "any": { "type": "any", "customField": "Custom value here", "anotherField": "Another custom value" } }]

Explanation:

Note: Technically, there is no limit to the message types. The type field can be virtually any value defined by the AI developers, allowing for custom message types and flexible communication formats based on the application's needs.

Set Metadata

Set metadata for the conversation using the setMetadata method:


const metadata = { sessionId: 'session-1234', userRole: 'customer' };
conversation.setMetadata(metadata);
    

Parameters:

Send an Action

Send an action (e.g., button click, custom event) using the sendAction method:


const actionId = 'action-xyz';
conversation.sendAction(actionId, { buttonClicked: true });
    

Parameters:

Handle Actions with onActionReceived

Listen for actions received in the conversation using the onActionReceived method:


          conversation.onActionReceived((actionId, data) => {
            console.log(`Action received: ${actionId}`, data);
          });
            

Parameters:

Example:


          conversation.onActionReceived((actionId, data) => {
            if (actionId === 'pdf-parsing-done') {
              console.log('Backend task PDF parsing is done!', data);
            } else {
              console.log(`Action received with ID: ${actionId}`, data);
            }
          });
            

Get Transcript

Get the full transcript of the conversation using the getTranscript method:


const transcript = await conversation.getTranscript();
console.log('Full Transcript:', transcript);
    

This will provide the entire history of messages exchanged in the conversation.

Transcript Schema:

The transcript is returned as an array of message objects. Each object can contain the following fields:

1. Basic Fields:

2. Messages (Optional):

3. Actions (Optional):

Example Transcript Entry:


{
  "from": "user",
  "channelName": "Goldenfred GPT Socket",
  "chatbotName": "GPT Goldenfred"
}
    

This entry represents a message from the user in the "Goldenfred GPT Socket" channel.

Example Transcript Entry with Messages:


{
  "from": "bot",
  "messages": {
    "idChat": "index_lance_b73fcd8d-ce8c-4dc6-9fa6-6b990430652f",
    "messages": ["Hello, how can I assist you?"],
    "metadata": {
      "sessionId": "session-1234",
      "userRole": "customer"
    },
    "actions": [],
    "cid": null,
    "userData": {
      "preferences": {
        "language": "en"
      }
    }
  },
  "channelName": "Goldenfred GPT Socket",
  "chatbotName": "GPT Goldenfred"
}
    

This entry includes a bot message, metadata (session ID, user role), and user data (language preferences).

Example Transcript Entry with Actions:


{
  "from": "user",
  "actions": [
    {
      "actionType": "click",
      "details": "Button A clicked"
    }
  ],
  "channelName": "Goldenfred GPT Socket",
  "chatbotName": "GPT Goldenfred"
}
    

This entry shows a user action, specifically a click on "Button A".

Purpose:

The getTranscript function is used for retrieving the entire conversation history, useful for:

Summary:

The getTranscript function returns an array of message objects representing the entire conversation between the user and the bot. Each message contains relevant information, including the sender, content, metadata, actions, and other details that help in understanding the context and interactions.