### Platform Tutorials
Source: https://chatbotkit.com/manuals/index
Follow step-by-step guides and practical examples for building conversational AI applications.
```APIDOC
## Platform Tutorials
### Description
The platform tutorial system provides step-by-step guides and practical examples that help developers build and deploy conversational AI applications.
### Method
GET
### Endpoint
/manuals/platform-tutorials.md
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **tutorial_content** (string) - The content of the platform tutorials.
#### Response Example
{
"tutorial_content": "... (tutorial content) ..."
}
```
--------------------------------
### Install MCP Integration using mcp/install
Source: https://chatbotkit.com/docs/skillsets
This snippet shows how to install an MCP (Multi-Cloud Platform) integration. It requires the URL of the MCP server and a prefix for namespacing the tools. This allows for dynamic loading and real-time updates of abilities from external services.
```markdown
```mcp/install
url: ((url! ys|the MCP server URL))
prefix: ((prefix ys|namespace prefix for tools))
```
```
--------------------------------
### Platform Guides
Source: https://chatbotkit.com/manuals/index
Understand and implement conversational AI solutions with comprehensive, in-depth guides.
```APIDOC
## Platform Guides
### Description
The platform guide system provides comprehensive, in-depth guides that help developers understand and implement conversational AI solutions.
### Method
GET
### Endpoint
/manuals/platform-guides.md
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **guide_content** (string) - The content of the platform guides.
#### Response Example
{
"guide_content": "... (guide content) ..."
}
```
--------------------------------
### Fetch Action Syntax Example
Source: https://chatbotkit.com/docs/skillsets
Demonstrates the basic syntax for the 'fetch' action, including URL, method, headers, and body. The body can include parameters that will be filled by the AI.
```markdown
```fetch
url: https://api.example.com/data
method: POST
headers:
Content-Type: application/json
Authorization: Bearer ${API_KEY}
body:
query: $[query! ys|the search query]
```
```
--------------------------------
### Install Chatbotkit React SDK
Source: https://chatbotkit.com/manuals/react-sdk
Instructions for installing the Chatbotkit React SDK using npm or yarn. This is the first step to integrating the SDK into your React project.
```shell
npm install @chatbotkit/react
# or using yarn
yarn add @chatbotkit/react
```
--------------------------------
### CLI
Source: https://chatbotkit.com/manuals/index
Comprehensive guide to the ChatBotKit CLI for local file system operations, coding assistance, and API management.
```APIDOC
## CLI
### Description
Comprehensive guide to the ChatBotKit CLI featuring autonomous agent mode for local file system operations, coding assistance, business automation workflows, and complete API management capabilities.
### Method
GET
### Endpoint
/manuals/cli.md
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **cli_documentation** (string) - The documentation for the ChatBotKit CLI.
#### Response Example
{
"cli_documentation": "... (CLI documentation content) ..."
}
```
--------------------------------
### Install Chatbotkit SDK and Next.js Integration
Source: https://chatbotkit.com/manuals/next-sdk
Installs the core Chatbotkit SDK, the Next.js integration package, and the React components using npm or yarn.
```shell
# Install core SDK and Next.js integration
npm install @chatbotkit/sdk @chatbotkit/next @chatbotkit/react
# or using yarn
yarn add @chatbotkit/sdk @chatbotkit/next @chatbotkit/react
```
--------------------------------
### Platform Documentation
Source: https://chatbotkit.com/manuals/index
Access comprehensive guides, tutorials, and reference materials for building and deploying conversational AI applications.
```APIDOC
## Platform Documentation
### Description
The platform documentation system provides comprehensive guides, tutorials, and reference materials that help developers build and deploy conversational AI applications.
### Method
GET
### Endpoint
/manuals/platform-documentation.md
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **documentation_content** (string) - The content of the platform documentation.
#### Response Example
{
"documentation_content": "... (documentation content) ..."
}
```
--------------------------------
### MCP Server for Skillset Exposure
Source: https://chatbotkit.com/manuals/index
Documentation for the ChatBotKit Model Context Protocol (MCP) server. It explains what MCP is, how it works, setup instructions, available tools, authentication, and usage examples for exposing skillsets as MCP-compliant servers.
```python
from chatbotkit.mcp import MCPHandler
class MySkillset(MCPHandler):
def handle(self, context):
return "Response from my skillset."
# Example of how to run the MCP server (implementation details may vary)
# server = MCPService(handler=MySkillset())
# server.run()
print("MCP server setup complete.")
```
--------------------------------
### ChatBotKit Webhooks Setup
Source: https://chatbotkit.com/docs/index
Set up and use webhooks within ChatBotKit to automate workflows and integrate different services. This section covers step-by-step setup, event selection, and validating incoming webhook requests using the X-Hub-Signature header.
```markdown
- [Webhooks](/docs/webhooks.md) - Learn how to set up and use webhooks within ChatBotKit to automate workflows and integrate different services. This section covers step-by-step setup, event selection, and validating incoming webhook requests using the X-Hub-Signature header.
```
--------------------------------
### Fetch Action with Parameters Example
Source: https://chatbotkit.com/docs/skillsets
Illustrates how to use different parameter syntaxes within a 'fetch' action. It shows referencing secrets, conversation IDs, meta fields, and defining AI-extracted parameters.
```markdown
```fetch
url: https://httpbin.org/anything/collect/details
method: POST
headers:
Content-Type: application/json
Authorization: Bearer ${SECRET_TEST}
body:
name: $[name! ys|The name of the user]
email: $[email! ys|The email of the user]
```
```
--------------------------------
### Agent SDK for Autonomous AI Agents
Source: https://chatbotkit.com/manuals/index
A comprehensive guide to the ChatBotKit Agent SDK. It details features, installation, tool creation, execution modes, and best practices for building autonomous AI agents that integrate custom tools with ChatBotKit capabilities.
```python
from chatbotkit.agent import Agent
from chatbotkit.tools import Tool
class MyTool(Tool):
name = "my_tool"
description = "A simple tool."
def run(self, **kwargs):
return "Tool executed successfully."
agent = Agent(tools=[MyTool()])
response = agent.execute("Run my tool")
print(response)
```
--------------------------------
### Platform Manuals
Source: https://chatbotkit.com/manuals/index
Access detailed operational guides and API reference documentation for platform features.
```APIDOC
## Platform Manuals
### Description
Platform manuals provide detailed operational guides and API reference documentation that explain how to use specific platform features, resources, and endpoints.
### Method
GET
### Endpoint
/manuals/platform-manuals.md
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **manual_content** (string) - The content of the platform manuals.
#### Response Example
{
"manual_content": "... (manual content) ..."
}
```
--------------------------------
### Install ChatBotKit Agent SDK
Source: https://chatbotkit.com/manuals/agent-sdk
Installs the necessary packages for the ChatBotKit Agent SDK using either npm or yarn. Ensure you have Node.js 20.x or higher installed.
```shell
npm install @chatbotkit/agent @chatbotkit/sdk
# or
yarn add @chatbotkit/agent @chatbotkit/sdk
```
--------------------------------
### Pack Definition Example in Markdown
Source: https://chatbotkit.com/docs/skillsets
This example demonstrates how to define a pack using Markdown syntax. It includes properties like backstory, model, task, and a list of abilities to be used by the sub-agent.
```markdown
```pack
backstory: You are a Google Drive assistant that helps users manage their files.
model: claude-4.5-sonnet
task: $[task! ys|what the user wants to do with Google Drive]
abilities:
- google-drive-list-files
- google-drive-create-file
- google-drive-delete-file
- google-drive-share-file
```
```
--------------------------------
### Search Action Syntax Example
Source: https://chatbotkit.com/docs/skillsets
Shows the syntax for the 'search' action, which allows the chatbot to find information. It includes properties for specifying the search type or a dataset ID, and a query parameter.
```markdown
```search
datasetId: ((datasetId! ys|the dataset ID to search))
query: $[query! ys|the search query]
```
```
--------------------------------
### ChatBotKit API Guide
Source: https://chatbotkit.com/docs/index
A comprehensive guide to understanding and utilizing the ChatBotKit API endpoints and features for integrating conversational AI into applications.
```markdown
- [API](/docs/api.md) - The ChatBotKit API is a powerful tool for developers looking to integrate conversational AI functionality into their applications. This documentation provides a comprehensive guide to understanding and utilizing the various endpoints and features offered by the API.
```
--------------------------------
### Next.js SDK for AI Chat
Source: https://chatbotkit.com/manuals/index
Detailed documentation for the Chatbotkit Next.js SDK. It covers key features, installation, server-side integration, best practices, TypeScript support, and examples for AI-powered chat in Next.js applications.
```javascript
import { Chatbot } from 'chatbotkit-nextjs';
const chatbot = new Chatbot({
secret: 'YOUR_SECRET_KEY'
});
export default async function handler(req, res) {
const { message } = req.body;
const response = await chatbot.send(message);
res.json(response);
}
```
--------------------------------
### Node SDK
Source: https://chatbotkit.com/manuals/index
Comprehensive guide to the ChatBotKit Node.js SDK for building conversational AI applications.
```APIDOC
## Node SDK
### Description
Comprehensive guide to the ChatBotKit Node.js SDK for building conversational AI applications with streaming support, TypeScript integration, and advanced features.
### Method
GET
### Endpoint
/manuals/node-sdk.md
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **node_sdk_documentation** (string) - The documentation for the Node.js SDK.
#### Response Example
{
"node_sdk_documentation": "... (Node.js SDK documentation content) ..."
}
```
--------------------------------
### Create WhatsApp AI Bot
Source: https://chatbotkit.com/tutorials/index
Integrate ChatBotKit with WhatsApp. This guide covers setup, configuration, and advanced features for a seamless conversational experience.
```python
# Example Python code for WhatsApp bot integration via a platform like Twilio (conceptual)
from flask import Flask, request, jsonify
from chatbotkit.client import ChatBotKit
app = Flask(__name__)
cbk = ChatBotKit(api_key='YOUR_CHATBOTKIT_API_KEY')
# Assume you have configured Twilio or another WhatsApp Business API provider
@app.route('/whatsapp', methods=['POST'])
def whatsapp_webhook():
incoming_msg = request.values.get('Body', None)
from_number = request.values.get('From', None)
if incoming_msg and from_number:
# Use ChatBotKit to get a response
response = cbk.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful WhatsApp assistant."},
{"role": "user", "content": incoming_msg}
]
)
bot_reply = response.choices[0].message.content
# Send the reply back via WhatsApp (e.g., using Twilio)
# send_whatsapp_message(from_number, bot_reply)
print(f"Received: {incoming_msg} from {from_number}. Replying: {bot_reply}")
return jsonify({'message': 'Message processed'}), 200
else:
return jsonify({'error': 'Invalid request'}), 400
# Placeholder for sending WhatsApp message
def send_whatsapp_message(to, message):
print(f"Sending to {to}: {message}")
# Implement Twilio or other API call here
pass
# if __name__ == '__main__':
# app.run(debug=True, port=5000)
```
--------------------------------
### Manual Widget Instantiation
Source: https://chatbotkit.com/docs/widget-sdk
Example of how to manually create and embed a ChatBotKit widget instance.
```APIDOC
## Manual Widget Instantiation
### Description
Demonstrates how to manually create a widget instance by including the SDK and adding the widget element to the page.
### Code Example
```html
```
```
--------------------------------
### ChatBotKit Primers Overview
Source: https://chatbotkit.com/docs/index
An overview of ChatBotKit Primers, guiding you on how to create conversational AI chatbots using ChatBotKit API and SDKs.
```markdown
- [Primers](/docs/primers.md) - Overview of the ChatBotKit Primers. Learn how to create conversational AI chatbots using ChatBotKit API and SDKs.
```
--------------------------------
### Agent SDK
Source: https://chatbotkit.com/manuals/index
A comprehensive guide to the ChatBotKit Agent SDK for building autonomous AI agents.
```APIDOC
## Agent SDK
### Description
This page provides a comprehensive guide to the ChatBotKit Agent SDK, detailing key features, installation instructions, tool creation, execution modes, and best practices for building autonomous AI agents that combine custom tools with ChatBotKit platform capabilities.
### Method
GET
### Endpoint
/manuals/agent-sdk.md
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **agent_sdk_documentation** (string) - The documentation for the Agent SDK.
#### Response Example
{
"agent_sdk_documentation": "... (Agent SDK documentation content) ..."
}
```
--------------------------------
### Integrate ChatBotKit with Slack
Source: https://chatbotkit.com/docs/index
Learn how to integrate ChatBotKit with Slack to deploy chatbots on the platform. This guide provides step-by-step instructions for interacting with your ChatBotKit Slack bot and advanced setup details.
```markdown
- [Slack](/docs/slack.md) - Learn how to integrate ChatBotKit with Slack and deploy chatbots on the platform. This guide provides step-by-step instructions, including how to interact with your ChatBotKit Slack bot, advanced setup details, troubleshooting tips, and more.
```
--------------------------------
### Use AI Widget Notifications
Source: https://chatbotkit.com/tutorials/index
Guide to setting up notifications, retrieving them dynamically, and managing their display order within your AI Widget integration.
```javascript
// Example JavaScript for interacting with AI Widget Notifications (conceptual)
// Assuming you have a reference to the ChatBotKit widget instance
// const widgetInstance = window.ChatBotKitWidgetInstance; // This would be obtained after widget initialization
function displayNotification(message, type = 'info', duration = 5000) {
// This is a conceptual representation. Actual implementation depends on the widget's API.
if (widgetInstance && widgetInstance.showNotification) {
widgetInstance.showNotification({
message: message,
type: type, // e.g., 'info', 'success', 'warning', 'error'
duration: duration // milliseconds
});
} else {
console.warn('ChatBotKit widget instance not available or showNotification method not found.');
// Fallback to a simple alert or custom notification system
alert(message);
}
}
// Example of dynamically retrieving and displaying notifications
async function fetchAndShowNotifications() {
// Assume a function to fetch notifications from your backend or ChatBotKit API
// const notifications = await getNotificationsFromAPI();
const notifications = [
{ message: 'Welcome back!', type: 'info', duration: 3000 },
{ message: 'New update available.', type: 'warning', duration: 7000 }
];
// Sort notifications if needed (e.g., by priority or timestamp)
notifications.sort((a, b) => a.priority - b.priority); // Example sorting
notifications.forEach(notif => {
displayNotification(notif.message, notif.type, notif.duration);
});
}
// Call this function when appropriate, e.g., after the widget loads or on a specific user action.
// fetchAndShowNotifications();
```
--------------------------------
### Instantiate ChatBotKit Client
Source: https://chatbotkit.com/docs/node-sdk
Provides an example of how to instantiate a ChatBotKit client, like ConversationClient, with optional configuration options. This is a prerequisite for making API calls.
```javascript
import { ConversationClient } from '@chatbotkit/sdk/conversation/index.js'
const client = new ConversationClient({
// options
})
```
--------------------------------
### Build Free AI Tools for Any Website
Source: https://chatbotkit.com/tutorials/index
Learn to build free AI tools for your website to attract high-intent customers, drive SEO traffic, and enhance user engagement. This is a step-by-step guide.
```html
My Website with AI Tool
Welcome to Our Website!
Discover our amazing products and services.
?
```
--------------------------------
### Integrate ChatBotKit with Discord
Source: https://chatbotkit.com/docs/index
Easily integrate ChatBotKit with Discord to access conversational AI functionalities within the platform. This guide offers step-by-step instructions to get started with your Discord bot.
```markdown
- [Discord](/docs/discord.md) - Learn how to easily integrate ChatBotKit with Discord and access a wide range of conversational AI functionalities directly within the popular messaging and collaboration platform for gamers and communities. Follow our step-by-step guide to get started.
```
--------------------------------
### Integrate ChatBotKit with Zendesk for Support
Source: https://chatbotkit.com/tutorials/index
Learn to integrate ChatBotKit with Zendesk for an efficient customer support system. Covers email setup, chatbot integration, and ticket management for streamlined inquiries.
```javascript
// Example JavaScript code for Zendesk integration (conceptual)
// This would typically involve backend logic or a middleware service
async function createZendeskTicket(conversationData) {
const zendeskApiUrl = 'https://YOUR_ZENDESK_DOMAIN.zendesk.com/api/v2/tickets.json';
const zendeskApiKey = 'YOUR_ZENDESK_API_KEY'; // Use API token or OAuth
const zendeskUserEmail = 'YOUR_ZENDESK_EMAIL';
const response = await fetch(zendeskApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + Buffer.from(zendeskUserEmail + '/token:' + zendeskApiKey).toString('base64')
},
body: JSON.stringify({
"ticket": {
"subject": `New Inquiry from ChatBotKit: ${conversationData.subject || 'No Subject'}`,
"comment": {
"body": conversationData.message
},
"priority": "normal",
"status": "open"
}
})
});
if (!response.ok) {
console.error('Failed to create Zendesk ticket:', await response.text());
return null;
}
const data = await response.json();
console.log('Zendesk ticket created:', data.ticket.url);
return data.ticket;
}
// Example usage within a ChatBotKit webhook or backend function:
// async function handleChatbotMessage(message) {
// if (message.needsSupport) {
// await createZendeskTicket({
// subject: message.topic,
// message: message.details
// });
// }
// }
```
--------------------------------
### API V1 Specification
Source: https://chatbotkit.com/docs/index
This section provides a comprehensive guide to the RESTful API provided by ChatBotKit. It includes all available endpoints, expected input and output parameters, and detailed usage examples.
```APIDOC
## GET /api/v1/spec
### Description
Retrieves the API V1 specification document.
### Method
GET
### Endpoint
/api/v1/spec
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **spec_document** (string) - The API V1 specification in markdown format.
#### Response Example
```markdown
# API V1 Specification
## Endpoints
### GET /users
#### Description
Retrieves a list of users.
#### Parameters
None
#### Response
- **users** (array) - A list of user objects.
- **id** (integer) - The user ID.
- **name** (string) - The user's name.
#### Response Example
```json
{
"users": [
{
"id": 1,
"name": "John Doe"
}
]
}
```
```
```
--------------------------------
### Install Additional ChatBotKit SDK Packages
Source: https://chatbotkit.com/docs/node-sdk
Installs additional ChatBotKit SDK packages for platforms like Next.js and React. These packages provide specialized components and utilities for specific frameworks.
```shell
npm install @chatbotkit/next @chatbotkit/react
```
--------------------------------
### Build AI Chatbot Application with ChatBotKit and Next.js Framework
Source: https://chatbotkit.com/tutorials/index
This tutorial provides a step-by-step guide on how to create a powerful AI chatbot application using the ChatBotKit SDK and Next.js framework. It covers the essential steps for building a complete chatbot application.
```javascript
import { ChatBotKit } from '@chatbotkit/sdk';
const chatbotkit = new ChatBotKit({
apiKey: 'YOUR_API_KEY',
});
async function createAIChatbot() {
// Example: Creating a new chatbot instance
const newChatbot = await chatbotkit.chatbots.create({
name: 'My Awesome Bot',
// other configurations...
});
console.log('Chatbot created:', newChatbot);
}
createAIChatbot();
```
--------------------------------
### Install ChatBotKit Node SDK
Source: https://chatbotkit.com/docs/node-sdk
Installs the core ChatBotKit SDK package for Node.js using npm. This is the primary package required to integrate ChatBotKit functionalities into your Node.js applications.
```shell
npm install @chatbotkit/sdk
```
--------------------------------
### Use ChatBotKit Data Extraction Integration
Source: https://chatbotkit.com/tutorials/index
Learn to effectively use ChatBotKit's Data Extraction integration to capture and send data from conversations to third-party endpoints. Guide covers setup, configuration, and testing.
```javascript
// Example JavaScript code for Data Extraction webhook (conceptual)
async function handleDataExtraction(extractedData) {
const thirdPartyEndpoint = 'https://api.example.com/data';
try {
const response = await fetch(thirdPartyEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify(extractedData)
});
if (!response.ok) {
console.error('Failed to send extracted data:', response.status, await response.text());
} else {
console.log('Successfully sent extracted data:', await response.json());
}
} catch (error) {
console.error('Error sending extracted data:', error);
}
}
// In ChatBotKit, you would configure a webhook to call this function
// when data extraction is triggered. The 'extractedData' object would contain
// the information captured by the AI based on your extraction rules.
```
--------------------------------
### Use Triggers for Stateless and Stateful Interactions
Source: https://chatbotkit.com/tutorials/index
Learn how to use triggers for enhanced chatbot workflows. Examples provided for both stateless and stateful modes to manage conversation context.
```json
// Example JSON configuration for ChatBotKit Triggers (conceptual)
{
"triggers": [
{
"name": "Greeting Trigger",
"type": "stateless", // Responds immediately without needing prior context
"condition": {
"intent": "greet"
},
"response": {
"type": "text",
"content": "Hello! How can I help you today?"
}
},
{
"name": "Order Status Trigger",
"type": "stateful", // Requires context or previous steps
"condition": {
"intent": "check_order_status"
},
"steps": [
{
"action": "ask",
"question": "What is your order number?",
"variable": "order_number"
},
{
"action": "api_call",
"url": "https://api.example.com/orders/{{order_number}}",
"method": "GET",
"variable": "order_details"
},
{
"action": "respond",
"template": "Your order status is: {{order_details.status}}. It is expected to arrive on {{order_details.delivery_date}}. "
}
]
}
]
}
```
--------------------------------
### Create and Manage Bots
Source: https://chatbotkit.com/manuals/node-sdk
Provides examples for creating, listing, fetching, updating, and deleting bots. Bot creation involves specifying parameters like name, description, backstory, model, and optional dataset and skillset IDs. Listing bots supports pagination and metadata filtering, with streaming results.
```javascript
// Creating Bots
const bot = await cbk.bot.create({
name: 'Support Assistant',
description: 'Helpful customer support bot',
backstory: 'You are a friendly and knowledgeable support agent.',
model: 'gpt-4o',
datasetId: 'dataset_abc123', // Optional: Link to knowledge base
skillsetId: 'skillset_xyz789', // Optional: Add abilities
privacy: true,
moderation: true
})
console.log(`Created bot: ${bot.id}`)
```
```javascript
// Managing Bots
// List bots with pagination
const result = await cbk.bot.list({
cursor: null,
order: 'desc',
take: 10,
meta: { environment: 'production' } // Filter by metadata
})
// Iterate through streaming results
for await (const { type, data } of result.stream()) {
if (type === 'item') {
console.log('Bot:', data)
}
}
// Fetch specific bot
const bot = await cbk.bot.fetch('bot_abc123')
// Update bot
await cbk.bot.update('bot_abc123', {
name: 'Updated Name',
backstory: 'New personality'
})
// Delete bot
await cbk.bot.delete('bot_abc123')
```
--------------------------------
### Create Weather Forecast Bot using ChatBotKit Skillsets
Source: https://chatbotkit.com/tutorials/index
This tutorial demonstrates building a weather forecast bot with ChatBotKit's skillsets. It guides through creating a custom skillset and an ability to fetch weather data via API requests. This involves defining intents, entities, and API call configurations.
```javascript
const weatherSkill = {
name: "weather",
description: "Provides weather forecasts.",
abilities: [
{
name: "getWeather",
description: "Gets the weather for a specified location.",
intents: ["get_weather"],
parameters: [
{ name: "location", type: "string", required: true }
],
handler: async (params) => {
// API call to fetch weather data
const response = await fetch(`https://api.weather.com?location=${params.location}`);
const data = await response.json();
return `The weather in ${params.location} is ${data.condition} with a temperature of ${data.temperature}°C.`;
}
}
]
};
// Add the skillset to your bot
// bot.addSkillset(weatherSkill);
```
--------------------------------
### Integrate ChatBotKit with Notion
Source: https://chatbotkit.com/docs/index
Learn how to integrate ChatBotKit with Notion and deploy chatbots on the platform. This guide provides instructions for setting up and interacting with your Notion bot.
```markdown
- [Notion](/docs/notion.md) - Learn how to integrate ChatBotKit with Notion and deploy chatbots on the platform. This guide provides instructions set up and interact with your Notion bot.
```
--------------------------------
### Implement Multi-Step Workflows with Execute in JavaScript
Source: https://chatbotkit.com/manuals/agent-sdk
Shows how to define and execute complex multi-step workflows using the `execute` function. The example illustrates a phased approach to task completion, from analysis to reporting and notification, by providing a detailed multi-line user message.
```javascript
const stream = execute({
client,
tools: comprehensiveTools,
botId: 'bot_123',
messages: [{
type: 'user',
text: `
Phase 1: Analyze codebase for security issues
Phase 2: Generate detailed report with findings
Phase 3: Create Jira tickets for high-severity issues
Phase 4: Update team documentation in Notion
Phase 5: Send summary to #security Slack channel
`
}],
maxIterations: 50
});
```
--------------------------------
### Build Stateless Conversational AI Chatbot with Next.js and ChatBotKit SDK
Source: https://chatbotkit.com/tutorials/index
Learn how to build a stateless conversational AI chatbot using Next.js and ChatBotKit SDK. This tutorial guides you through setting up a Next.js project, creating an API endpoint, and designing a chat user interface.
```javascript
import { ChatBotKit } from '@chatbotkit/sdk';
const chatbotkit = new ChatBotKit({
apiKey: 'YOUR_API_KEY',
});
async function handleChat(req, res) {
const { message } = req.body;
const response = await chatbotkit.chat({ message });
res.json(response);
}
export default handleChat;
```
--------------------------------
### Build Google Meet Transcription Bot
Source: https://chatbotkit.com/tutorials/index
Create a bot to fetch and summarize Google Meet transcripts using ChatBotKit. This tutorial guides through bot creation for streamlined workflow and time-saving.
```python
# Example Python code for Google Meet transcript summarization (conceptual)
from chatbotkit.client import ChatBotKit
# Initialize ChatBotKit client
cbk = ChatBotKit(api_key='YOUR_CHATBOTKIT_API_KEY')
def get_and_summarize_transcript(meet_url):
# Assume a function to fetch transcript from meet_url (implementation details omitted)
transcript_text = fetch_google_meet_transcript(meet_url)
# Use ChatBotKit for summarization
response = cbk.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant that summarizes meeting transcripts."},
{"role": "user", "content": f"Summarize the following meeting transcript:\n{transcript_text}"}
]
)
summary = response.choices[0].message.content
return summary
def fetch_google_meet_transcript(meet_url):
# Placeholder for actual transcript fetching logic
# This would involve Google Meet API or other methods
return "This is a sample transcript text from a Google Meet recording..."
# Example usage:
# meet_link = "https://meet.google.com/abc-def-ghi"
# summary = get_and_summarize_transcript(meet_link)
# print(summary)
```
--------------------------------
### Assigning Notifications
Source: https://chatbotkit.com/docs/widget-sdk
Example of how to dynamically assign notifications to the ChatBotKit widget.
```APIDOC
## Assigning Notifications
### Description
Shows how to dynamically insert interactive messages and notifications into the ChatBotKit widget.
### Code Example
```javascript
// a placeholder function to retrieve the available notifications from the application
async function getNotifications() {
// artificial delay to simulate network fetch
await new Promise((resolve) => {
setTimeout(() => resolve(), 1000);
});
// return available notifications
const uniqueNotificationId = Math.random().toString(32).slice(2);
return {
[uniqueNotificationId]: {
text: 'Hi Sara, your device has been offline for 12 hours\n\n[What is the current status of my device]() [How can I get my device back online]()'
}
};
}
// a helper function to setup the notifications
async function setupNotifications() {
const notifications = await getNotifications();
const instance = await window.chatbotkitWidget.instancePromise;
instance.notifications = notifications;
}
setupNotifications();
```
### Explanation
This example retrieves notifications and assigns them to the widget instance once `instancePromise` is resolved. The widget manages the notification state, and removing a notification from the object will remove it from the conversation.
```
--------------------------------
### Node.js SDK for Conversational AI
Source: https://chatbotkit.com/manuals/index
Comprehensive guide to the ChatBotKit Node.js SDK for building conversational AI applications. It features streaming support, TypeScript integration, and advanced functionalities.
```javascript
import ChatBotKit from 'chatbotkit';
const kit = new ChatBotKit({
secret: 'YOUR_SECRET_KEY'
});
async function createConversation() {
const conversation = await kit.conversations.create({
name: 'My New Conversation'
});
console.log(conversation);
}
```
--------------------------------
### Create Question/Answer Chatbot from Document with ChatBotKit
Source: https://chatbotkit.com/tutorials/index
Learn to build a question-answering chatbot from PDF or DOCX documents using ChatBotKit. This guide provides simple methods to upload your document and enable the chatbot to answer queries based on its content. It involves creating a dataset from the document.
```javascript
// Assuming you have the ChatBotKit SDK initialized
// const chatbotkit = new ChatBotKit({ apiKey: 'YOUR_API_KEY' });
async function createQnABotFromDocument(filePath) {
// Upload document to create a dataset
const dataset = await chatbotkit.datasets.create({
name: 'document_qa_dataset',
// file: filePath // In a real scenario, you'd handle file upload properly
});
// Add document content to the dataset (implementation depends on SDK)
// await chatbotkit.datasets.addContent(dataset.id, { content: '...' });
// Create a bot using this dataset
const bot = await chatbotkit.bots.create({
name: 'Document Q&A Bot',
datasets: [dataset.id]
});
console.log('Q&A Bot created:', bot);
return bot;
}
```
--------------------------------
### Create Datasets and Dataset Records in JavaScript
Source: https://chatbotkit.com/docs/node-sdk
Provides a code example for creating a new dataset with a name and description, and then adding a record to that dataset. This is a fundamental operation for managing custom data within ChatBotKit.
```javascript
import { ChatBotKit } from '@chatbotkit/sdk'
const client = new ChatBotKit({
secret: '...your secret here'
})
const dataset = await client.dataset.create({
name: '...the dataset name',
description: '...the dataset description',
})
await client.dataset.record.create(dataset.id, {
text: '...the record text'
})
```
--------------------------------
### Handle Stateless Conversations with Function Calling
Source: https://chatbotkit.com/manuals/node-sdk
Demonstrates how to conduct stateless conversations, suitable for one-off interactions without persistent storage. This example includes using function calling by defining available functions with their descriptions and parameters, allowing the bot to interact with external tools.
```javascript
// Stateless Conversations
// Complete a conversation without creating a record
for await (const { type, data } of cbk.conversation
.complete(null, {
model: 'gpt-4o',
messages: [
{ type: 'user', text: 'What is the weather in Tokyo?' }
],
functions: [
{
name: 'get_weather',
description: 'Get current weather',
parameters: {
type: 'object',
properties: {
location: { type: 'string' }
}
}
}
]
})
.stream()) {
if (type === 'token') {
process.stdout.write(data.token)
}
}
```
--------------------------------
### Integrate AI Widget with Ionic Framework
Source: https://chatbotkit.com/tutorials/index
Integrate the AI Widget with the Ionic Framework. Guide covers embedding the widget using an iframe, managing user experience, and setting client-side functions.
```typescript
// Example TypeScript code for integrating ChatBotKit AI Widget in Ionic Framework
import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonRouterOutlet } from '@ionic/angular';
@Component({
selector: 'app-home',
template: `
AI Assistant
`
})
export class HomePage {
@ViewChild('chatbotFrame') chatbotFrame: ElementRef;
constructor() {}
// Example of handling messages from the widget using postMessage
// You would need to add an event listener in ngOnInit or similar lifecycle hook
// ngOnInit() {
// window.addEventListener('message', this.handleWidgetMessage.bind(this));
// }
// ngOnDestroy() {
// window.removeEventListener('message', this.handleWidgetMessage.bind(this));
// }
handleWidgetMessage(event: MessageEvent) {
// IMPORTANT: Always verify the origin of the message for security
if (event.origin !== 'https://widget.chatbotkit.com') {
return;
}
const messageData = event.data;
console.log('Message from ChatBotKit widget:', messageData);
// Example: Handle a specific event like 'userLoggedIn'
// if (messageData.type === 'userLoggedIn' && messageData.payload) {
// console.log('User logged in:', messageData.payload.userId);
// }
}
// Example of sending a message to the widget
sendMessageToWidget(data: any) {
const iframe = this.chatbotFrame.nativeElement;
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage(data, 'https://widget.chatbotkit.com');
}
}
}
```
--------------------------------
### Execute Agent in Complete Mode with Streaming Responses and Tool Calls
Source: https://chatbotkit.com/manuals/agent-sdk
Demonstrates how to use the 'complete' function for streaming agent responses, including handling tool execution. It processes events like text tokens, tool call starts, and tool call ends.
```javascript
import { complete } from '@chatbotkit/agent';
const stream = complete({
client,
tools,
botId: 'bot_123', // Optional: use existing bot configuration
model: 'gpt-4o', // Or specify model directly
messages: [
{ type: 'user', text: 'What is 234 plus 567?' }
]
});
// Process the stream
for await (const event of stream) {
if (event.type === 'token') {
process.stdout.write(event.data.token);
} else if (event.type === 'toolCallStart') {
console.log(`\\nCalling tool: ${event.data.name}`);
} else if (event.type === 'toolCallEnd') {
console.log(`Tool result:`, event.data.result);
}
}
```
--------------------------------
### Monitor Agent Progress with Events in JavaScript
Source: https://chatbotkit.com/manuals/agent-sdk
Illustrates how to monitor the progress of an agent's execution by iterating over events. It shows how to log iteration counts, the start and end of tool calls, and associated arguments, which is crucial for debugging and user feedback.
```javascript
for await (const event of execute({ client, tools, botId, messages })) {
if (event.type === 'iteration') {
console.log(`Progress: Iteration ${event.data.iteration}`);
} else if (event.type === 'toolCallStart') {
console.log(`Executing: ${event.data.name}`, event.data.args);
} else if (event.type === 'toolCallEnd') {
console.log(`Completed: ${event.data.name}`);
}
}
```
--------------------------------
### List Available Tutorials API
Source: https://context7_llms
Returns a complete list of available tutorials, including their associated metadata. This endpoint is useful for discovering available tutorial content.
```HTTP
GET https://chatbotkit.com/api/v1/platform/tutorial/list
```
--------------------------------
### User Assumption Header Example (Plain Text)
Source: https://chatbotkit.com/docs/api
Demonstrates how to use the 'X-RunAs-UserId' header for user assumption in a parent-child account setup. This requires both the Authorization and X-RunAs-UserId headers.
```plain text
Authorization: Bearer {your_token_here}
X-RunAs-UserId: {child_user_id_here}
```
--------------------------------
### Integrate AI Widget with iOS using SwiftUI
Source: https://chatbotkit.com/tutorials/index
Integrate the AI Widget into your iOS app using SwiftUI and WebKit. Guide provides step-by-step instructions for embedding the widget frame and setting up client-side functions.
```swift
// Example Swift code for integrating ChatBotKit AI Widget in SwiftUI
import SwiftUI
import WebKit
struct ChatBotWidgetView: UIViewRepresentable {
let widgetUrl: String
func makeUIView(context: Context) -> WKWebView {
let webView = WKWebView()
if let url = URL(string: widgetUrl) {
let request = URLRequest(url: url)
webView.load(request)
}
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
// Update view if needed
}
}
struct ContentView: View {
// Replace with your actual widget URL, potentially with fullscreen parameters
let chatbotWidgetUrl = "https://widget.chatbotkit.com/YOUR_WIDGET_ID?fullscreen=true"
var body: some View {
NavigationView {
VStack {
Text("My App")
.font(.largeTitle)
ChatBotWidgetView(widgetUrl: chatbotWidgetUrl)
.navigationBarTitle("AI Assistant", displayMode: .inline)
}
}
}
}
// To handle client-side functions, you would typically use WKScriptMessageHandler
// Add this to makeUIView function:
// webView.configuration.userContentController.add(context.coordinator, name: "chatbotkit")
// Then implement:
// func makeCoordinator() -> Coordinator {
// Coordinator(self)
// }
// class Coordinator: NSObject, WKScriptMessageHandler {
// var parent: ChatBotWidgetView
// init(_ parent: ChatBotWidgetView) {
// self.parent = parent
// }
// func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
// if message.name == "chatbotkit" {
// // Process message.body from the widget
// print("Received message from widget: \(message.body)")
// }
// }
// }
```
--------------------------------
### Create Google Calendar AI Agent with Telegram Bot
Source: https://chatbotkit.com/tutorials/index
Learn to build an intelligent AI agent for Google Calendar using a Telegram chatbot. This tutorial covers setup, authentication, and interaction for seamless calendar management.
```python
# Example Python code for Telegram bot integration (conceptual)
import telegram
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Telegram bot setup
bot = telegram.Bot(token='YOUR_TELEGRAM_BOT_TOKEN')
# Google Calendar API setup
SCOPES = ['https://www.googleapis.com/auth/calendar']
creds = service_account.Credentials.from_service_account_file(
'credentials.json', scopes=SCOPES)
service = build('calendar', 'v3', credentials=creds)
def handle_message(update, context):
user_message = update.message.text
chat_id = update.message.chat_id
# Process user_message to interact with Google Calendar
# Example: Add an event
if "add event" in user_message.lower():
# Parse event details from user_message
event = {
'summary': 'New Event',
'start': {'dateTime': '2023-10-27T10:00:00-07:00'},
'end': {'dateTime': '2023-10-27T10:30:00-07:00'},
}
created_event = service.events().insert(calendarId='primary', body=event).execute()
bot.send_message(chat_id=chat_id, text=f"Event created: {created_event.get('htmlLink')}")
else:
bot.send_message(chat_id=chat_id, text="I can help you manage your Google Calendar.")
# In a real application, you would set up a webhook or polling mechanism
# for the Telegram bot to receive messages.
```
--------------------------------
### Conditional Tool Execution Logic in JavaScript
Source: https://chatbotkit.com/manuals/agent-sdk
Provides an example of setting up conditional tool execution by defining two tools: `checkCondition` to evaluate a condition and `conditionalAction` to perform an action based on the result. This pattern is useful for creating dynamic agent behaviors.
```javascript
const tools = {
checkCondition: {
description: 'Check if condition is met',
input: z.object({
condition: z.string()
}),
handler: async ({ condition }) => {
// Evaluate condition
return { met: true, value: 'some_value' };
}
},
conditionalAction: {
description: 'Perform action based on previous check',
input: z.object({
action: z.string(),
data: z.any()
}),
handler: async ({ action, data }) => {
// Execute conditional logic
return { success: true };
}
}
};
```
--------------------------------
### List Available Tutorials API
Source: https://context7_llms
Returns a complete list of available tutorials with similar metadata structure.
```APIDOC
## GET /api/v1/platform/tutorial/list
### Description
Returns a complete list of available tutorials with similar metadata structure.
### Method
GET
### Endpoint
https://chatbotkit.com/api/v1/platform/tutorial/list
### Parameters
#### Path Parameters
None
#### Query Parameters
None
### Request Example
```
GET https://chatbotkit.com/api/v1/platform/tutorial/list
```
### Response
#### Success Response (200)
- **tutorials** (array) - A list of available tutorials.
#### Response Example
```json
{
"tutorials": [
{
"id": "tutorial-1",
"title": "Tutorial Title 1"
},
{
"id": "tutorial-2",
"title": "Tutorial Title 2"
}
]
}
```
```
--------------------------------
### Fetch Individual Tutorial API
Source: https://context7_llms
Retrieves the full content of a specific tutorial using its unique identifier. The tutorial ID is appended to the URL path.
```HTTP
GET https://chatbotkit.com/api/v1/platform/tutorial/{tutorialId}/fetch
```
```HTTP
GET https://chatbotkit.com/api/v1/platform/tutorial/getting-started/fetch
```