Overview
Our Embed SDK lets you interact with TeamAI chatbots embedded on your web pages. It provides methods to update context and retrieve current context, giving you full control over your embedded chatbots.
If you embedded your chatbot before September 29, 2024, you may need to update
the embed code on your website. The new embed code now includes the Embed SDK
automatically.
To use the Embed SDK, ensure that you have the correct assistant ID and the
appropriate plan.
Embed Data Attributes
You can control the appearance and behavior of your embedded chatbot by adding data attributes to the embed <div>. Here are the supported attributes:
| Attribute | Description | Example Value |
|---|
data-chatbot-id | (Required) The unique identifier for your chatbot instance. | "YOUR_ASSISTANT_ID" |
data-chatbot-mode | Display mode: "standard" (default) or "popover" for a floating bubble. | "popover" |
data-hide-header | Hide the agent header (avatar, title, clear button) if set to "true". | "true" |
data-button-color | Background color for the chat bubble button (popover mode only). | "#007bff" |
data-icon-color | Icon color for the chat bubble button (popover mode only). | "#fff" |
Example:
<div
data-chatbot-id="YOUR_ASSISTANT_ID"
data-chatbot-mode="popover"
data-hide-header="true"
data-button-color="#007bff"
data-icon-color="#fff"
></div>
Methods
Initialize Embed SDK
The SDK automatically initializes when the chatbot is embedded on your page. You don’t need to call an explicit init function.
Get Chatbot Instance
Retrieves an instance of the chatbot for interaction.
const chatbotInstance = tai.getInstance("YOUR_ASSISTANT_ID");
The unique identifier for your chatbot instance.
This method returns a chatbot instance that you can use to interact with your embedded chatbot.
Wait for Chatbot Ready State
window.addEventListener("teamAIChatbotReady", function () {
const chatbotInstance = tai.getInstance("YOUR_ASSISTANT_ID");
// Your code here
});
Update Chatbot Context
Updates the context for your chatbot.
The new context data to update the chatbot with.
This method allows you to update the context for the chatbot dynamically. You can use these context variables in your assistant’s instructions like so: {{userEmail}}.
Get Chatbot Context
Retrieves the current context of the chatbot.
const currentContext = chatbotInstance.getContext();
This method returns the current context of the chatbot.
Get Conversation History
Retrieves the complete conversation history between the user and the chatbot.
const conversation = await chatbotInstance.getConversation();
This method returns a Promise that resolves to an object containing the conversation history. The returned object has the following structure:
interface MessageEntry {
role: "user" | "assistant"; // Who sent the message
content: string; // The message content
timestamp: number; // Unix timestamp in milliseconds
}
interface ConversationData {
assistantId: string; // The ID of the assistant
messages: MessageEntry[]; // Array of messages in chronological order
}
Example: Retrieve and Display Conversation History
window.addEventListener("teamAIChatbotReady", async function () {
const chatbotInstance = tai.getInstance("YOUR_ASSISTANT_ID");
// Wait until chatbot is fully ready
await chatbotInstance.ready();
try {
// Get the conversation history
const conversation = await chatbotInstance.getConversation();
console.log(`Retrieved ${conversation.messages.length} messages`);
// Display or process the messages
conversation.messages.forEach((message) => {
console.log(`[${message.role}]: ${message.content}`);
console.log(`Timestamp: ${new Date(message.timestamp).toLocaleString()}`);
});
} catch (error) {
console.error("Failed to retrieve conversation:", error);
}
});
This method is useful for analytics, saving conversation logs, or implementing custom conversation displays.
Reset Conversation
Resets the conversation with the chatbot, clearing the chat history and starting fresh.
await chatbotInstance.resetConversation();
This method returns a Promise that resolves when the conversation has been successfully reset. It’s useful for implementing a “Start Over” or “New Chat” button in your interface.
window.addEventListener("teamAIChatbotReady", function () {
const chatbot = tai.getInstance("YOUR_ASSISTANT_ID");
// Create a reset button
const resetButton = document.createElement("button");
resetButton.textContent = "Start New Conversation";
resetButton.addEventListener("click", async () => {
try {
await chatbot.resetConversation();
console.log("Conversation reset successfully");
// Optionally send a welcome message
chatbot.sendMessage("Hi! How can I help you today?");
} catch (error) {
console.error("Failed to reset conversation:", error);
}
});
// Add button to your page
document.getElementById("chatbot-controls").appendChild(resetButton);
});
Register custom tools that your chatbot can execute on the client side. This allows your chatbot to interact with the user’s browser environment.
chatbotInstance.registerTool({
name: "getCurrentTime",
description: "Gets the current time in the user's timezone",
parameters: {
format: {
type: "string",
description: "Format to display the time (optional)",
},
},
execute: (params) => {
const now = new Date();
return {
time: now.toLocaleTimeString(),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
};
},
});
The name of the tool, which the chatbot will use to call it.
A description of what the tool does.
The parameters the tool accepts (similar to OpenAI function schema).
A function that will be called when the chatbot uses this tool. It receives
the parameters provided by the chatbot and should return a result.
Remove a previously registered client-side tool.
chatbotInstance.unregisterTool("getCurrentTime");
The name of the tool to unregister.
Retrieve a list of all currently registered client-side tools.
const registeredTools = chatbotInstance.getRegisteredTools();
Multi-Agent Events
When your chatbot uses multi-agent orchestration (specialist agents for specific tasks), you can listen to events for enhanced user experience and tracking.
Listen for Agent Handoffs
Called when the main agent delegates a task to a specialist agent.
chatbotInstance.onAgentHandoff((data) => {
console.log(`Task delegated to ${data.targetAgentName}: ${data.task}`);
console.log(`Reason: ${data.reason}`);
// Available data:
// - targetAgentId: string
// - targetAgentName: string
// - task: string
// - reason: string
});
Function to call when an agent handoff occurs. Receives an object with
targetAgentId, targetAgentName, task, and reason.
Listen for Specialist Returns
Called when a specialist agent completes its task and returns control to the main agent.
chatbotInstance.onSpecialistReturn((data) => {
console.log(`Task completed: ${data.completedTask}`);
console.log(`Results: ${data.taskResults}`);
// Available data:
// - taskResults: string
// - taskSummary: string
// - additionalContext?: string
// - completedTask: string
});
Function to call when a specialist returns to the main agent. Receives an
object with task results and completion details.
How Multi-Agent Orchestration Works
- Task Analysis: The main agent analyzes the user’s request
- Specialist Selection: If specialized knowledge is needed, the main agent selects an appropriate specialist
- Task Handoff: The main agent hands off the specific task to the specialist
- Specialist Processing: The specialist agent handles the task with its specialized knowledge
- Result Integration: The specialist returns results to the main agent
- Unified Response: The main agent presents the final response to the user
Hidden Messages
During multi-agent orchestration, internal coordination messages between agents are automatically hidden from the user interface to maintain a seamless experience. Users only see the relevant parts of the conversation.
Example: Multi-Agent Integration
window.addEventListener("teamAIChatbotReady", function () {
const chatbotInstance = tai.getInstance("YOUR_ASSISTANT_ID");
// Listen for agent handoff events
chatbotInstance.onAgentHandoff((data) => {
console.log("🎯 Agent handoff received:", data);
// Log the handoff with full details
console.log(`🔄 Agent Handoff: ${data.targetAgentName} taking over`);
console.log(`📋 Task: ${data.task}`);
console.log(`🎯 Reason: ${data.reason}`);
// Show loading indicator for specialist work
showSpecialistWorkingIndicator(data.targetAgentName, data.task);
// Update UI to show current agent
updateCurrentAgent(data.targetAgentId, data.targetAgentName);
});
// Listen for specialist completion events
chatbotInstance.onSpecialistReturn((data) => {
console.log("🔄 Specialist return received:", data);
// Log the completion
console.log(`✅ Task Completed: ${data.completedTask}`);
console.log(`📊 Results: ${data.taskResults}`);
console.log(`🔄 Returning to: Main Assistant`);
// Hide loading indicator
hideSpecialistWorkingIndicator();
// Return to main agent
updateCurrentAgent("main", "Main Assistant");
});
console.log("🤖 Chatbot initialized and multi-agent events connected");
});
function showSpecialistWorkingIndicator(specialistName, task) {
// Remove any existing indicator first
hideSpecialistWorkingIndicator();
const indicator = document.createElement("div");
indicator.id = "specialist-indicator";
indicator.innerHTML = `🔄 <strong>${specialistName}</strong> is working on: ${task}`;
indicator.style.cssText = `
padding: 12px;
background: #fff3cd;
border: 1px solid #ffeaa7;
border-radius: 6px;
margin: 10px 0;
font-size: 14px;
color: #856404;
`;
// Add to your chatbot container with fallback to body
const container =
document.getElementById("chatbot-container") || document.body;
container.appendChild(indicator);
}
function hideSpecialistWorkingIndicator() {
const indicator = document.getElementById("specialist-indicator");
if (indicator) {
indicator.remove();
}
}
function updateCurrentAgent(agentId, agentName) {
const currentAgentElement = document.getElementById("current-agent");
if (currentAgentElement) {
currentAgentElement.textContent = agentName;
}
console.log(`🤖 Current Agent: ${agentName}`);
}
Upload Data
Uploads a file (e.g., a CSV or text file) to your chatbot so you can query that data directly within the conversation. Once uploaded, the chatbot will have immediate access to the file contents. If you attempt to upload the same file again, the SDK will detect a matching file fingerprint and re-use the previous upload — so you won’t need to re-upload duplicates.
chatbotInstance.uploadBlob(myFile: Blob): Promise<UploadResponse>;
A Blob or File
object. Currently, only CSV-formatted files are supported.
Example: Updating Context
In this example, we’re setting up the chatbot and updating the context with the user’s email and name.
Example: Updating Context
window.addEventListener("teamAIChatbotReady", function () {
console.log("The TeamAI Chatbot is ready!");
const chatbotInstance = tai.getInstance("YOUR_ASSISTANT_ID");
// Update context with user's email and name
chatbotInstance.updateContext({
userEmail: "[email protected]",
userName: "John Doe",
});
});
This example demonstrates how to set up the chatbot, log its readiness, and update its context programmatically.
Example: Chat with a CSV or Excel file
Upload your CSV file to let your chatbot parse and answer questions about it.
// Create CSV content on the fly (or fetch from server)
const csvContent = `name,age,city
John Smith,32,New York
Sarah Johnson,28,San Francisco`;
// Convert CSV string to a File object
const csvFile = new File([csvContent], "dummy.csv", { type: "text/csv" });
// Upload the file so the chatbot can access it
chatbotInstance
.uploadBlob(csvFile)
.then((uploadResponse) => {
console.log("Upload successful:", uploadResponse);
// After upload, you can instruct your chatbot:
chatbotInstance.sendMessage(
"Hi, please analyze the CSV data you just received."
);
})
.catch((error) => {
console.error("Upload failed:", error);
});
This example shows how to register client-side tools that allow your chatbot to interact with the user’s browser.
window.addEventListener("teamAIChatbotReady", function () {
const chatbotInstance = tai.getInstance("YOUR_ASSISTANT_ID");
// Register a tool to get user's location (with permission)
chatbotInstance.registerTool({
name: "getUserLocation",
description: "Gets the user's current location (requires permission)",
parameters: {},
execute: async () => {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject({ error: "Geolocation not supported by this browser" });
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
resolve({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
});
},
(error) => {
reject({ error: error.message });
}
);
});
},
});
// Register a tool to get data from your application
chatbotInstance.registerTool({
name: "getProductDetails",
description: "Gets details about a product by ID",
parameters: {
productId: {
type: "string",
description: "The ID of the product to look up",
},
},
execute: async (params) => {
try {
// This is where you would call your API or access your app state
const response = await fetch(`/api/products/${params.productId}`);
const product = await response.json();
return product;
} catch (error) {
return { error: "Failed to fetch product details" };
}
},
});
// Let the chatbot know it can use these tools
chatbotInstance.sendMessage(
"Hi, I'm ready to help with product information or location-based services."
);
});
Debug Mode
To enable debug mode in TeamAI, add ?teamAIDebug=true to your app’s URL.
For example, if you’ve embedded your TeamAI instance in your app hosted at https://example.com, you can activate debug mode by changing the URL to:
https://example.com?teamAIDebug=true
After adding this parameter, refresh the page and open your browser’s developer console (usually by pressing F12 or right-clicking and selecting “Inspect” then navigating to the “Console” tab).