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();
- apiKey: Your API key.
- environment: 'dev' or 'prod' depending on your environment.
Create a Conversation
Start a new conversation with the following method:
const conversation = await captivateAPI.createConversation(userId, userBasicInfo, userData, mode);
Parameters:
- userId: A unique identifier for the user (e.g.,
"user123"). - userBasicInfo: User details (optional). Example:
{ firstName: "John", email: "john.doe@example.com" } - userData: Additional user data like preferences (optional). Example:
{ preferences: { theme: "dark" } } - mode: Conversation mode:
'bot-first'or'user-first'.
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);
- conversationId: The unique identifier of the conversation.
Send a Message
Send a message to the bot using:
await conversation.sendMessage('Hello, how can I help you?');
- messageContent: The text of the message to send.
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:
- text: Simple text message sent by the bot.
- buttons: Interactive buttons with a title and URL that the user can click to navigate to a different page.
- cards: An array of cards, each containing text, description, image URL, and a link.
- html: The message content formatted in HTML. For example, you can use HTML tags
like
<p>,<strong>, etc. - md: The message content formatted in Markdown. Supports bold, italic, and code formatting.
- files: A file message that includes the file type (image, document, audio, etc.), the URL to access the file, the MIME type, and an optional filename.
- any: A generic message type that can contain any custom fields as needed by your application.
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:
- metadata: Key-value pairs of metadata for the conversation (e.g., session ID, user role).
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:
- actionId: The ID of the action to trigger (e.g., button click, event).
- data: Additional data related to the action (optional).
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:
- actionId: The ID of the action that was received (e.g., a finished back process task or custom event).
- data: The data associated with the action (optional, depends on the action type).
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:
- from (string): The sender of the message. Possible values:
user,bot. - channelName (string): The name of the communication channel (e.g., 'Goldenfred GPT Socket').
- chatbotName (string): The name of the chatbot involved in the conversation.
2. Messages (Optional):
- messages (object): Contains the following subfields:
- idChat (string): Unique identifier for the chat session.
- messages (array): List of message strings.
- metadata (object): Metadata related to the session (e.g., session ID, user role).
- actions (array): List of actions taken by the user or bot (optional).
- cid (string|null): A unique identifier for the conversation, may be null.
- userData (object): Optional data about the user (e.g., preferences, language).
3. Actions (Optional):
- actions (array): List of actions, each containing:
- actionType (string): Type of action (e.g.,
click,type). - details (string): Additional details about the action (e.g., which button was clicked).
- actionType (string): Type of action (e.g.,
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:
- Storing conversations for analysis or audits.
- Processing messages and actions during a conversation.
- Displaying message logs for users or administrators.
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.