### Define View Action for Image Description
Source: https://chatbotkit.com/docs/skillsets
This example defines a 'view' action that utilizes a vision model to describe an image. The input for this action must be a URL pointing to the image, and can optionally include a text description to guide the vision model.
```markdown
```view
https://example.com/image.jpg
A picture of a cat.
```
```
--------------------------------
### Installation
Source: https://chatbotkit.com/manuals/next-sdk
Install the core SDK and the Next.js integration package using npm or yarn.
```APIDOC
## Installation
`````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
`````
```
--------------------------------
### Install ChatBotKit Agent SDK with npm or yarn
Source: https://chatbotkit.com/manuals/agent-sdk
Installs the necessary ChatBotKit Agent and SDK packages using either npm or yarn. Ensure Node.js v20.x or higher is installed.
```shell
npm install @chatbotkit/agent @chatbotkit/sdk
# or
yarn add @chatbotkit/agent @chatbotkit/sdk
```
--------------------------------
### Complete Chat Implementation Example
Source: https://chatbotkit.com/manuals/next-sdk
An example of a complete chat implementation using the `useConversationManager` hook from `@chatbotkit/react` for a seamless user experience.
```APIDOC
## Complete Chat Implementation Example
### Description
This example demonstrates how to use the `useConversationManager` hook to build a functional chat interface in a Next.js application.
### Code Snippet
```typescript
import { useConversationManager, AutoTextarea } from '@chatbotkit/react'
export default function Chat() {
const {
thinking,
text,
setText,
messages,
submit,
error
} = useConversationManager({
endpoint: '/api/chat', // Ensure this endpoint is configured on your server
initialMessages: [
{
id: 'welcome',
type: 'bot',
text: 'Hello! How can I help you today?'
}
]
})
const handleSubmit = async () => {
if (!text.trim()) return
await submit()
}
return (
)
}
```
```
--------------------------------
### Quick Start: Stream Conversation Completion with Node.js SDK
Source: https://chatbotkit.com/manuals/node-sdk
Demonstrates how to initiate a stateless conversation and stream responses using the `ConversationClient`. This example utilizes async/await and the stream() method to process tokens as they arrive, suitable for real-time chat interfaces. It requires a ChatBotKit API secret key environment variable.
```javascript
import { ConversationClient } from '@chatbotkit/sdk/conversation/index.js'
const client = new ConversationClient({
secret: process.env.CHATBOTKIT_API_SECRET
})
// Stream conversation responses
for await (const { type, data } of client
.complete(null, {
model: 'gpt-4o',
messages: [
{ type: 'user', text: 'Hello! How are you?' }
]
})
.stream()) {
if (type === 'token') {
process.stdout.write(data.token)
}
}
```
--------------------------------
### Create a Question/Answer Chatbot from a Document
Source: https://chatbotkit.com/tutorials/index
Learn how to create a question and answer chatbot from your PDF or DOCX document using ChatBotKit. This guide provides simple methods to get started with chatting with your chatbot.
```python
from chatbotkit.chatbot import Chatbot
chatbot = Chatbot(api_key='YOUR_API_KEY')
document_path = 'path/to/your/document.pdf'
# Create a dataset from the document
dataset_id = chatbot.datasets.create_from_document(document_path=document_path, name='My Document Q&A')
# Create a chatbot instance using the dataset
chatbot_instance = chatbot.create(name='Document Q&A Bot', dataset_ids=[dataset_id])
print(f"Chatbot created with ID: {chatbot_instance.id}")
```
--------------------------------
### Load Multiple MCP Services (Linear and Notion)
Source: https://chatbotkit.com/docs/skillsets
This example shows how to load tools from multiple MCP servers to create comprehensive workflows. It first loads Linear for issue tracking, then Notion for documentation.
```mcp
mcp/install
url:
prefix: linear
```
```mcp
mcp/install
url: https://mcp.notion.com/mcp
prefix: notion
```
--------------------------------
### Leverage Google Groups for Cost-Effective Customer Support Using ChatBotKit
Source: https://chatbotkit.com/tutorials/index
This tutorial explains how to integrate Google Groups with ChatBotKit to establish a cost-effective customer support system. It covers the setup and integration process, enabling automated handling of customer inquiries while maintaining support quality.
```python
from chatbotkit.integrations.google_groups import GoogleGroupsIntegration
# Initialize the integration (replace with actual credentials/setup)
# This is a conceptual example, actual implementation details may vary.
groups_integration = GoogleGroupsIntegration(
api_key='YOUR_API_KEY',
google_service_account_key='path/to/service/account/key.json'
)
async def handle_support_inquiry(user_message, group_email):
try:
# Send the user message to a specific Google Group
success = await groups_integration.post_message(
group_email=group_email,
subject="Customer Support Inquiry",
body=user_message
)
if success:
return "Your inquiry has been forwarded. We will respond shortly."
else:
return "Sorry, there was an issue forwarding your inquiry."
except Exception as e:
print(f"Error posting to Google Group: {e}")
return "An error occurred while processing your request."
# Example usage:
# group = 'support@example.com'
# user_msg = 'I have a problem with my order.'
# asyncio.run(handle_support_inquiry(user_msg, group))
```
--------------------------------
### Train Your Own ChatGPT with Your Data using ChatBotKit Datasets
Source: https://chatbotkit.com/tutorials/index
This tutorial guides users through training their own ChatGPT model with custom data using ChatBotKit Datasets. It details the creation and configuration of datasets, adding files and integrations, and creating dataset records for building personalized conversational AI bots.
```python
from chatbotkit.datasets import Datasets
datasets = Datasets(api_key='YOUR_API_KEY')
# Example: Creating a new dataset
dataset_id = datasets.create_dataset(
name='My Custom Data',
description='Data for training a specific chatbot'
)
print(f"Created dataset with ID: {dataset_id}")
# Example: Adding a file to the dataset (assuming file_path exists)
# with open(file_path, 'rb') as f:
# datasets.add_file(dataset_id, f)
# Example: Creating a dataset record
# datasets.create_record(dataset_id, {
# "prompt": "What is the capital of France?",
# "completion": "Paris"
# })
```
--------------------------------
### Install Chatbotkit SDK and Next.js Integration
Source: https://chatbotkit.com/manuals/next-sdk
Install the core Chatbotkit SDK along with Next.js and React integrations using npm or yarn package managers.
```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
```
--------------------------------
### Build AI Chatbot Application with ChatBotKit and Next.js Framework
Source: https://chatbotkit.com/tutorials/index
A step-by-step guide to creating a powerful AI chatbot application using the ChatBotKit SDK and the Next.js framework. This tutorial covers the integration of ChatBotKit's capabilities within a Next.js project to develop a functional chatbot application.
```javascript
import { ChatBotKit } from "chatbotkit";
const chatbotkit = new ChatBotKit({
secret: "YOUR_SECRET_KEY"
});
async function sendMessageToChatbot(message) {
try {
const response = await chatbotkit.chat.send(
"YOUR_CHATBOT_ID",
message
);
console.log("Chatbot response:", response.message);
return response.message;
} catch (error) {
console.error("Error sending message:", error);
return "An error occurred.";
}
}
// Example: sendMessageToChatbot("Hello, how are you?");
```
--------------------------------
### Parameter Syntax Examples
Source: https://chatbotkit.com/docs/skillsets
Demonstrates various syntaxes for using parameters within ChatBotKit actions. Supports accessing secrets, conversation information, and defining user-fillable parameters.
```markdown
`${SECRET_NAME}` or `{{SECRET_NAME}}`
`${CONVERSATION_ID}` or `{{CONVERSATION_ID}}`
`${CONVERSATION_META_FIELD}` or `{{CONVERSATION_META_FIELD}}`
`$[param|parameter description]` or `[[param|parameter description]]`
```
--------------------------------
### Install Chatbotkit React SDK
Source: https://chatbotkit.com/manuals/react-sdk
Install the @chatbotkit/react package using npm or yarn package managers. This is the first step to integrate Chatbotkit into a React project.
```shell
npm install @chatbotkit/react
# or using yarn
yarn add @chatbotkit/react
```
--------------------------------
### Listen to Widget Initialization Event
Source: https://chatbotkit.com/docs/widget-sdk
Demonstrates listening to the chatbotkitWidgetInit window event that fires when the widget SDK is initialized and the widget becomes available. This allows performing setup tasks immediately after widget initialization.
```javascript
window.addEventListener('chatbotkitWidgetInit', (event) => {
const widget = event.target;
console.log('Widget initialized:', widget);
});
```
--------------------------------
### Example: Listing Conversations with ChatBotKit API
Source: https://chatbotkit.com/docs/api
Demonstrates how to list conversations using the ChatBotKit API. This request uses the GET method and requires an Authorization header.
```plain text
GET /v1/conversation/list HTTP/1.1
Host: api.chatbotkit.com
Authorization: Bearer ...
```
--------------------------------
### Show Videos in ChatBotKit Widget
Source: https://chatbotkit.com/tutorials/index
Discover how to embed videos into your ChatBotKit Widget using markdown format. This tutorial provides guidance and examples for enriching user experience with engaging video content directly within the chat interface.
```html
```
--------------------------------
### Install Additional ChatBotKit SDK Packages
Source: https://chatbotkit.com/docs/node-sdk
Installs additional ChatBotKit SDK packages, such as those for Next.js and React, allowing for platform-specific integrations. Use this after installing the core SDK.
```shell
npm install @chatbotkit/next @chatbotkit/react
```
--------------------------------
### Install ChatBotKit Node SDK
Source: https://chatbotkit.com/docs/node-sdk
Installs the core ChatBotKit SDK package using npm. This is the first step to integrating chatbot functionalities into your Node.js project.
```shell
npm install @chatbotkit/sdk
```
--------------------------------
### Build Stateless Conversational AI Chatbot with Next.js and ChatBotKit SDK
Source: https://chatbotkit.com/tutorials/index
Learn to build a stateless conversational AI chatbot using Next.js and the ChatBotKit SDK. This involves setting up a Next.js project, creating an API endpoint for chat interactions, and designing a user interface for the chat. It guides users through the fundamental steps of integrating ChatBotKit into a modern web application.
```javascript
import { ChatBotKit } from "chatbotkit";
const chatbotkit = new ChatBotKit({
secret: "YOUR_SECRET_KEY"
});
// Example usage in a Next.js API route
export default async function handler(req, res) {
const { message } = req.body;
const response = await chatbotkit.chat.send(
"YOUR_CHATBOT_ID",
message
);
res.status(200).json({ reply: response.message });
}
```
--------------------------------
### Synchronize Notion Pages with ChatBotKit Datasets
Source: https://chatbotkit.com/tutorials/index
This tutorial provides step-by-step instructions on using the ChatBotKit Notion integration to synchronize Notion pages with datasets. It covers creating a token, sharing content, setting up the Notion importer, and initiating the synchronization process.
```python
from chatbotkit.chatbot import Chatbot
CHATBOTKIT_API_KEY = 'YOUR_CHATBOTKIT_API_KEY'
NOTION_TOKEN = 'YOUR_NOTION_INTEGRATION_TOKEN'
NOTION_PAGE_ID = 'YOUR_NOTION_PAGE_ID'
chatbot = Chatbot(api_key=CHATBOT_API_KEY)
# Create a new dataset or use an existing one
dataset_id = 'YOUR_EXISTING_DATASET_ID' # Or create a new one: chatbot.datasets.create(name='My Notion Data')
# Create a new Notion importer
importer_id = chatbot.integrations.notion.create_importer(
dataset_id=dataset_id,
notion_token=NOTION_TOKEN,
notion_page_id=NOTION_PAGE_ID,
name='My Notion Sync'
)
# Trigger the synchronization process
chatbot.integrations.notion.sync_importer(importer_id=importer_id)
print(f"Notion importer created with ID: {importer_id} and sync initiated.")
```
--------------------------------
### API V1 Specification
Source: https://chatbotkit.com/docs/index
The API V1 Spec provides a comprehensive guide to the RESTful API provided by ChatBotKit. It includes all available endpoints, the expected input and output parameters for each endpoint, and detailed examples of how to use the API.
```APIDOC
## GET /docs/api/v1/spec.md
### Description
Provides access to the comprehensive guide for the RESTful API v1.
### Method
GET
### Endpoint
/docs/api/v1/spec.md
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **documentation** (string) - The full API V1 specification documentation.
#### Response Example
{
"documentation": "## ChatBotKit API V1 Specification\n\nThis document outlines the available endpoints, request/response formats, and usage examples for the ChatBotKit API version 1..."
}
```
--------------------------------
### Configure 'complete' Mode with Options in JavaScript
Source: https://chatbotkit.com/manuals/agent-sdk
This example shows how to configure the 'complete' mode of ChatBotKit. It includes essential parameters like client, tools, botId, model, and messages, along with optional 'extensions' for adding context like 'backstory'.
```javascript
complete({
client,
tools,
botId,
model,
messages,
extensions: {
backstory: 'Custom context for this session',
}
})
```
--------------------------------
### Automate Zendesk Support Requests with ChatBotKit
Source: https://chatbotkit.com/tutorials/index
This tutorial explains how to use ChatBotKit's Conversation AI technology with Zapier integration to automatically answer incoming Zendesk support requests. It covers creating a ChatBotKit dataset and integrating it with Zapier.
```python
from chatbotkit.chatbot import Chatbot
import requests
CHATBOTKIT_API_KEY = 'YOUR_CHATBOTKIT_API_KEY'
ZAPIER_WEBHOOK_URL = 'YOUR_ZAPIER_WEBHOOK_URL'
chatbot = Chatbot(api_key=CHATBOTKIT_API_KEY)
def process_zendesk_request(subject, description):
# Create a dataset or use an existing one for Zendesk support
# For simplicity, we'll assume a dataset exists or is created elsewhere
dataset_id = 'YOUR_ZENDESK_DATASET_ID'
conversation = chatbot.conversation.create(dataset_ids=[dataset_id])
response = chatbot.message.create(conversation_id=conversation.id, message=f"Subject: {subject}\nDescription: {description}")
# Send the response to Zapier to update Zendesk
payload = {
'ticket_id': 'TICKET_ID_FROM_ZENDESK', # This would come from Zapier
'reply_body': response.message
}
requests.post(ZAPIER_WEBHOOK_URL, json=payload)
# This function would be triggered by a Zapier integration when a new Zendesk ticket is created
# Example usage (within a Zapier automation context):
# process_zendesk_request(subject='Login Issue', description='I cannot log in to my account.')
```
--------------------------------
### GET /api/v1/dataset/list
Source: https://chatbotkit.com/manuals/datasets
Retrieves a list of all created datasets, useful for management and overview.
```APIDOC
## GET /api/v1/dataset/list
### Description
Retrieves a list of all datasets created by the user.
### Method
GET
### Endpoint
/api/v1/dataset/list
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
(No request body for GET requests)
### Response
#### Success Response (200)
A list of datasets (structure not provided in source).
#### Response Example
(Response structure not provided in source)
```
--------------------------------
### Create Weather Forecast Bot with ChatBotKit Skillsets
Source: https://chatbotkit.com/tutorials/index
This tutorial demonstrates how to create a weather forecast bot using ChatBotKit's skillsets. It covers setting up a skillset and implementing an ability to fetch weather information via API requests, enabling the bot to provide weather updates.
```javascript
import { ChatBotKit } from "chatbotkit";
const chatbotkit = new ChatBotKit({
secret: "YOUR_SECRET_KEY"
});
async function getWeatherForecast(location) {
// In a real scenario, you would call a weather API here.
// For demonstration, returning a mock response.
console.log(`Fetching weather for ${location}...`);
return {
location: location,
temperature: "25°C",
condition: "Sunny"
};
}
// This function would be part of a ChatBotKit Skillset definition
// Example of how it might be invoked:
// const weatherInfo = await getWeatherForecast("London");
// console.log(weatherInfo);
```
--------------------------------
### Agent SDK: Automate Development Workflow with Git and Tests
Source: https://chatbotkit.com/manuals/agent-sdk
This example showcases defining local development tools such as checking git status and running tests, then executing them via the Agent SDK. It depends on Node.js environment for 'git' and 'npm' commands. The input is a user request, and the output is a stream of agent execution results.
```javascript
const devTools = {
checkGitStatus: {
description: 'Get current git repository status',
input: z.object({}),
handler: async () => {
const { stdout } = await execAsync('git status --porcelain');
return { changes: stdout, hasChanges: stdout.length > 0 };
}
},
runTests: {
description: 'Execute test suite',
input: z.object({
path: z.string().optional()
}),
handler: async ({ path = '.' }) => {
try {
const { stdout } = await execAsync(`npm test -- ${path}`);
return { success: true, output: stdout };
} catch (error) {
return { success: false, error: error.message };
}
}
}
};
const stream = execute({
client,
tools: devTools,
botId: 'bot_123',
messages: [{
type: 'user',
text: 'Run all tests, check git status, and create deployment checklist in Jira'
}],
maxIterations: 20
});
```
--------------------------------
### GET /api/v1/bot/{botId}/fetch
Source: https://chatbotkit.com/manuals/bots
Retrieves detailed information about a specific bot including its complete configuration, AI model settings, backstory, connected resources, and customization options. This endpoint is essential for displaying bot information in user interfaces and verifying bot settings before starting conversations.
```APIDOC
## GET /api/v1/bot/{botId}/fetch
### Description
Retrieves comprehensive details about a specific bot, including its configuration, behavior settings, connected resources, and all customization options.
### Method
GET
### Endpoint
/api/v1/bot/{botId}/fetch
### Parameters
#### Path Parameters
- **botId** (string) - Required - The unique identifier of the bot to retrieve. Can be either the bot's unique identifier or a custom identifier defined in the bot's metadata.
### Response
#### Success Response (200)
- **id** (string) - The unique identifier of the bot
- **name** (string) - The name of the bot
- **description** (string) - The description of the bot
- **backstory** (string) - The backstory instructions that define the bot's behavior
- **model** (string) - The AI model being used by the bot
- **datasetId** (string) - Reference to connected dataset
- **skillsetId** (string) - Reference to connected skillset
- **privacy** (boolean) - Privacy setting for the bot
- **moderation** (boolean) - Moderation setting for the bot
- **visibility** (string) - Visibility settings (public/private)
- **createdAt** (string) - ISO 8601 timestamp when the bot was created
- **updatedAt** (string) - ISO 8601 timestamp when the bot was last updated
### Response Example
```json
{
"id": "bot_abc123",
"name": "Support Bot",
"description": "Technical support assistant",
"backstory": "You are an expert technical support representative",
"model": "gpt-4o",
"datasetId": "dataset_xyz789",
"privacy": true,
"moderation": true,
"visibility": "private",
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-20T14:45:00Z"
}
```
### Security
Only bots that belong to your account can be fetched. Attempting to retrieve a bot that doesn't exist or belongs to another user will result in an error response.
```
--------------------------------
### Define Search Action for Web or Datasets
Source: https://chatbotkit.com/docs/skillsets
This example shows how to define a 'search' action for retrieving information. You can specify the search type (web, news, images, videos) or a datasetId to search within a specific dataset. The action requires a search phrase as input.
```markdown
```search
Search for 'latest AI advancements' type:web
```
```
```markdown
```search
Search in dataset 'company-docs' for 'product features'
datasetId: company-docs
```
```
--------------------------------
### Example: Initial Request for Paginated Conversation List
Source: https://chatbotkit.com/docs/api
The first request to retrieve a list of conversations without using the cursor parameter for pagination. It requires an Authorization header.
```plain text
GET /v1/conversation/list HTTP/1.1
Host: api.chatbotkit.com
Authorization: Bearer {your_token_here}
```
--------------------------------
### Fetch Skillset Details - HTTP GET Request
Source: https://chatbotkit.com/manuals/skillsets
Retrieve complete details about a specific skillset including configuration, metadata, and timestamps. The response includes skillset ID, name, description, visibility settings, blueprint associations, and creation/modification timestamps, but excludes the list of abilities which must be fetched separately.
```http
GET /api/v1/skillset/{skillsetId}/fetch
```
--------------------------------
### Platform Integration: Using ChatBotKit Platform Capabilities (JavaScript)
Source: https://chatbotkit.com/manuals/agent-sdk
Shows how to leverage ChatBotKit platform capabilities, such as integrations and datasets, by specifying a `botId` when calling the `execute` function. This allows agents to access pre-configured features without manual setup.
```javascript
const stream = execute({
client,
tools: localTools, // Your custom tools
botId: 'bot_123', // Bot with configured integrations
messages: [{
type: 'user',
text: 'Check local logs, create Jira ticket if errors found, notify team on Slack'
}]
});
```
--------------------------------
### Example: Creating a Conversation with ChatBotKit API
Source: https://chatbotkit.com/docs/api
Illustrates how to create a conversation using the ChatBotKit API. This request uses the POST method, requires an Authorization header, and expects a JSON payload.
```plain text
POST /v1/conversation/create HTTP/1.1
Host: api.chatbotkit.com
Authorization: Bearer ...
Content-Type: application/json
...
```
--------------------------------
### Create Educational AI Bot with Follow-Up Questions
Source: https://chatbotkit.com/tutorials/index
Learn to build an educational AI bot using ChatBotKit that can answer student questions and provide interactive follow-up questions. This promotes a more engaging and effective learning experience by encouraging deeper exploration of topics.
```python
from chatbotkit.core import ChatBot
# Initialize ChatBotKit (replace with your actual setup)
chatbot = ChatBot(api_key='YOUR_API_KEY', chatbot_id='YOUR_CHATBOT_ID')
async def get_educational_response(user_question):
try:
# Get the primary answer from the chatbot
response = await chatbot.send(user_question)
answer = response['message']
# Logic to determine and append a follow-up question
follow_up_question = "Would you like to know more about a related topic?"
if "photosynthesis" in user_question.lower():
follow_up_question = "Interested in learning about the Calvin cycle?"
return f"{answer}\n\n{follow_up_question}"
except Exception as e:
print(f"Error getting response: {e}")
return "Sorry, I could not provide an answer at this time."
# Example usage:
# question = "What is photosynthesis?"
# print(asyncio.run(get_educational_response(question)))
```
--------------------------------
### Complete Mode: Streaming Agent Responses with Tool Execution (JavaScript)
Source: https://chatbotkit.com/manuals/agent-sdk
Demonstrates how to use the `complete` function to get streaming agent responses, including handling tool calls and their results. It processes events like 'token', 'toolCallStart', and 'toolCallEnd'.
```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);
}
}
```
--------------------------------
### Agent SDK: Execute Local File Scan and Code Analysis
Source: https://chatbotkit.com/manuals/agent-sdk
This example demonstrates defining and using local tools for file scanning and code analysis with the ChatbotKit Agent SDK. It requires '@chatbotkit/agent' and 'fs/promises'. The input is a user message specifying actions, and the output is a stream of agent responses.
```javascript
import { execute } from '@chatbotkit/agent';
import { readFile } from 'fs/promises';
// Define local-only tools
const localTools = {
scanLocalFiles: {
description: 'Scan local directory for specific files',
input: z.object({
directory: z.string(),
pattern: z.string()
}),
handler: async ({ directory, pattern }) => {
// Local file system operations
const { stdout } = await execAsync(`find ${directory} -name "${pattern}"`);
return { files: stdout.trim().split('\\n') };
}
},
analyzeCode: {
description: 'Analyze code quality metrics locally',
input: z.object({
filePath: z.string()
}),
handler: async ({ filePath }) => {
const content = await readFile(filePath, 'utf-8');
// Perform local analysis
return {
lines: content.split('\\n').length,
hasTests: content.includes('describe('),
complexity: calculateComplexity(content)
};
}
}
};
// Agent can use both local tools AND remote integrations
const stream = execute({
client,
tools: localTools,
botId: 'bot_with_jira_and_slack', // Bot has Jira and Slack configured
messages: [{
type: 'user',
text: `Scan src/ for .js files, analyze code quality,
create Jira tickets for files with high complexity,
and notify #dev-team on Slack with summary`
}],
maxIterations: 30
});
```
--------------------------------
### Embed ChatBotKit Widget Inside Notion
Source: https://chatbotkit.com/tutorials/index
Learn the process of embedding a ChatBotKit Widget into a Notion page to enhance its functionality. This tutorial provides step-by-step instructions for creating a widget and integrating it seamlessly into your Notion workspace.
```html
```
--------------------------------
### Create Cost-Effective Vision ChatBot
Source: https://chatbotkit.com/tutorials/index
Learn how to build a cost-effective vision chatbot capable of understanding images and improving user interactions. This tutorial focuses on practical implementation for creating an efficient chatbot that can process visual input.
```python
from chatbotkit.vision import VisionChatBot
# Initialize the vision chatbot (replace with your actual initialization)
vision_bot = VisionChatBot(api_key='YOUR_API_KEY')
async def process_image_and_chat(image_path, user_query):
try:
# Analyze the image
image_analysis = await vision_bot.analyze_image(image_path)
print("Image analysis result:", image_analysis)
# Use the analysis in a chat context
response = await vision_bot.chat(
query=user_query,
context={'image_description': image_analysis['description']}
)
return response['message']
except Exception as e:
print(f"An error occurred: {e}")
return "Sorry, I could not process that."
# Example usage:
# import asyncio
# asyncio.run(process_image_and_chat('path/to/your/image.jpg', 'What is in this image?'))
```
--------------------------------
### Execute Multi-Step Workflows with JavaScript
Source: https://chatbotkit.com/manuals/agent-sdk
This JavaScript example shows how to define and execute complex multi-step workflows. By providing a detailed textual description of sequential phases in the user messages, the agent can orchestrate a series of actions, such as code analysis, report generation, ticket creation, documentation updates, and notifications, with an increased iteration limit for complex tasks.
```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
});
```
--------------------------------
### List Skillsets API Request
Source: https://chatbotkit.com/manuals/skillsets
This HTTP GET request retrieves a list of skillsets, with options for pagination and sorting. It's useful for displaying an overview of available capabilities or for building management interfaces.
```http
GET /api/v1/skillset/list?take=20&order=desc
```
--------------------------------
### Fetch Blueprint by ID using HTTP GET
Source: https://chatbotkit.com/manuals/blueprints
Retrieves a specific blueprint's complete configuration and metadata by its ID or slug. Returns all blueprint properties including name, description, visibility, metadata, and timestamps. Requires blueprint ownership for authorization.
```http
GET /api/v1/blueprint/{blueprintId}/fetch
```
--------------------------------
### Creating Multiple Scenes in ChatBotKit Backstory
Source: https://chatbotkit.com/docs/backstories
Demonstrates how to define multiple scenes within a ChatBotKit backstory using the '<|scene|>' tag. Each scene can represent a different conversational path or scenario. When the conversation starts, one scene is chosen randomly by the chatbot.
```markdown
The backstory here
<|scene|>
This is the beginning of the first scene.
<|scene|>
This is the beginning of the second scene.
<|scene|>
This is the beginning of the third scene.
```
--------------------------------
### Use Messages Feature in ChatBotKit Widget
Source: https://chatbotkit.com/tutorials/index
Explore the messages feature of the ChatBotKit Widget to add contextual information at the beginning of conversations. This enhances user experience and engagement. The guide includes steps for creating, embedding, and initializing the widget with custom messages.
```javascript
```
--------------------------------
### List Datasets API Request
Source: https://chatbotkit.com/manuals/datasets
This snippet demonstrates how to retrieve a list of all created datasets. A GET request to the '/api/v1/dataset/list' endpoint will return the list of datasets.
```http
GET /api/v1/dataset/list
```
--------------------------------
### Create Conversation with Basic Configuration
Source: https://chatbotkit.com/manuals/conversations
Initiates a new conversation session using basic parameters like name, description, and associated bot or contact IDs. This is the standard method for starting a new AI-driven dialogue.
```http
POST /api/v1/conversation/create
Content-Type: application/json
{
"name": "Customer Support Session",
"description": "Support conversation for user inquiry",
"botId": "bot_abc123",
"contactId": "contact_xyz789"
}
```
--------------------------------
### Setup Dynamic Notifications for ChatBotKit Widget
Source: https://chatbotkit.com/docs/widget-sdk
Retrieve notifications from your application and dynamically assign them to the ChatBotKit widget instance using the instancePromise property. Notifications are managed automatically by the widget and appear in the order they were added.
```javascript
// a placeholder function to retrieve the available notifications from the applicaion
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()
```
--------------------------------
### Create Conversation with Initial Messages
Source: https://chatbotkit.com/manuals/conversations
Starts a new conversation and immediately primes it with user messages. This allows the AI to respond to an initial prompt, setting the context for the dialogue from the outset.
```http
POST /api/v1/conversation/create
Content-Type: application/json
{
"botId": "bot_abc123",
"messages": [
{
"type": "user",
"text": "Hello, I need help with my order"
}
]
}
```
--------------------------------
### Example: Subsequent Request for Paginated Conversation List
Source: https://chatbotkit.com/docs/api
A subsequent request to retrieve the next page of conversation results using the cursor parameter, which should be the ID of the last resource from the previous response.
```plain text
GET /v1/conversation/list?cursor={last_resource_id} HTTP/1.1
Host: api.chatbotkit.com
Authorization: Bearer {your_token_here}
```
--------------------------------
### 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 their metadata.
### Method
GET
### Endpoint
https://chatbotkit.com/api/v1/platform/tutorial/list
### Parameters
#### Query Parameters
None
### Response
#### Success Response (200)
- **tutorials** (array) - A list of tutorials, each with metadata.
#### Response Example
```json
{
"tutorials": [
{
"tutorialId": "tutorial789",
"title": "Tutorial Title",
"createdAt": "2023-10-27T10:00:00Z"
}
]
}
```
```
--------------------------------
### Stream Conversation Completion Tokens
Source: https://chatbotkit.com/docs/node-sdk
Shows how to stream tokens generated during a conversation completion. This example sends a user message and then iterates through the streamed 'token' events to log the response data.
```javascript
import { ChatBotKit } from '@chatbotkit/sdk'
const client = new ChatBotKit({
secret: '...your secret here'
})
const messages = [
{
type: 'user',
text: 'Hello!'
}
]
// access all conversations via the .stream() AsyncGenerator
for await (const { type, data } of client.conversation.complete(null, { messages }).stream()) {
if (type === 'token') {
console.log('token', data)
}
}
```
--------------------------------
### Agent SDK: Build Data Processing Pipeline with CSV and Validation
Source: https://chatbotkit.com/manuals/agent-sdk
This example defines local tools for reading CSV files and validating data, then integrates them using the Agent SDK. It requires 'fs/promises' for file reading. The input is a user command to process a CSV, and the output is a stream of agent responses, potentially including updates to a Google Sheet.
```javascript
const dataTools = {
readCSV: {
description: 'Read and parse CSV file',
input: z.object({
filePath: z.string()
}),
handler: async ({ filePath }) => {
const content = await readFile(filePath, 'utf-8');
const lines = content.split('\\n');
const headers = lines[0].split(',');
const rows = lines.slice(1).map(line => {
const values = line.split(',');
return Object.fromEntries(headers.map((h, i) => [h, values[i]]));
});
return { headers, rows, count: rows.length };
}
},
validateData: {
description: 'Validate data against rules',
input: z.object({
data: z.array(z.any()),
rules: z.object({
requiredFields: z.array(z.string()).optional(),
emailFields: z.array(z.string()).optional()
})
}),
handler: async ({ data, rules }) => {
const errors = [];
// Validation logic
return { valid: errors.length === 0, errors };
}
}
};
const stream = execute({
client,
tools: dataTools,
botId: 'bot_with_google_sheets',
messages: [{
type: 'user',
text: 'Read customers.csv, validate email addresses, update Google Sheet with results'
}]
});
```
--------------------------------
### Show Images in ChatBotKit Widget
Source: https://chatbotkit.com/tutorials/index
Learn how to display images within the ChatBotKit Widget using markdown formatting. This enhances the visual appeal and interactivity of chatbot responses by allowing the inclusion of images directly in the bot's output.
```html
Here is an image:
```
--------------------------------
### Add Memory to AI Chatbot
Source: https://chatbotkit.com/tutorials/index
This tutorial demonstrates how to add memory to an AI chatbot using ChatBotKit. It involves creating a dataset, adding records, and utilizing this information during conversations for more accurate responses.
```python
from chatbotkit.chatbot import Chatbot
chatbot = Chatbot(api_key='YOUR_API_KEY')
# Assuming you have a dataset with conversation history or user preferences
dataset_id = 'YOUR_EXISTING_DATASET_ID'
# Example: Adding a record to the dataset
chatbot.datasets.add_record(dataset_id=dataset_id, data={'user_query': 'What is my favorite color?', 'bot_response': 'Your favorite color is blue.'})
# When interacting with the chatbot, you can pass context from the dataset
conversation = chatbot.conversation.create(dataset_ids=[dataset_id])
response = chatbot.message.create(conversation_id=conversation.id, message='What is my favorite color?')
print(response.message)
```
--------------------------------
### Build Interactive Form with ChatBotKit Widget API
Source: https://chatbotkit.com/tutorials/index
This tutorial focuses on building an interactive form using the ChatBotKit Widget API. It covers embedding the widget, implementing form elements, and submitting form data to the widget for processing, enabling dynamic user input collection.
```javascript
```
--------------------------------
### GET /api/v1/blueprint/list
Source: https://chatbotkit.com/manuals/blueprints
Retrieves a paginated list of all blueprints associated with the authenticated user's account. Supports cursor-based pagination and sorting to efficiently handle large blueprint collections. The response includes blueprint metadata and configuration details for display or selection purposes.
```APIDOC
## GET /api/v1/blueprint/list
### Description
Retrrieves a paginated list of all blueprints owned by the authenticated user. This endpoint is useful for displaying available templates, browsing existing configurations, and managing the blueprint collection.
### Method
GET
### Endpoint
/api/v1/blueprint/list
### Query Parameters
- **take** (integer) - Optional - Number of items to retrieve per request (helps manage response size). Default behavior returns all blueprints.
- **order** (string) - Optional - Sort order for results. Accepts "asc" for ascending or "desc" for descending. Default: "desc"
- **cursor** (string) - Optional - Continue pagination from a specific point (obtained from previous responses for cursor-based pagination)
### Request Example
GET /api/v1/blueprint/list?take=10&order=desc
### Response
#### Success Response (200)
- **items** (array) - Array of blueprint objects
- **id** (string) - The unique blueprint identifier
- **name** (string) - The blueprint name
- **description** (string) - The blueprint description
- **visibility** (string) - The visibility setting ("private" or "protected")
- **createdAt** (timestamp) - When the blueprint was created
- **updatedAt** (timestamp) - When the blueprint was last updated
- **cursor** (string) - Pagination cursor for fetching the next set of results
- **hasMore** (boolean) - Indicates if more blueprints are available
### Response Example
{
"items": [
{
"id": "blueprint_123",
"name": "Customer Support Template",
"description": "Complete customer support setup with bot, knowledge base, and integrations",
"visibility": "private",
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:30:00Z"
}
],
"cursor": "next_cursor_value",
"hasMore": false
}
### Notes
- This endpoint only returns blueprints owned by the authenticated user
- To access shared or public blueprints, use the fetch endpoint with a specific blueprint ID
- Cursor-based pagination allows efficient navigation through large blueprint collections
```
--------------------------------
### Defining Skillsets within ChatBotKit Backstory
Source: https://chatbotkit.com/docs/backstories
Illustrates how to define a skillset directly within a ChatBotKit backstory using the '<|skillset|>' tag. This approach embeds specific functionalities, like image generation, into the bot's narrative for contextually relevant responses. It includes a 'Generate Image' skillset example with a placeholder for a prompt.
```markdown
The backstory here
<|skillset|>
- name: Generate Image
description: Generate a new image
instruction: |
```image
$[promt|the prompt for the image]
```
```
--------------------------------
### Manual List API Response Structure - JSON
Source: https://context7_llms
Example JSON response structure from the manual list endpoint containing an array of manual objects with metadata. Each manual object includes id, name, description, category, tags, index, and timestamp information.
```json
{
"items": [
{
"id": "introduction",
"name": "Introduction",
"description": "Getting started with ChatBotKit",
"category": null,
"tags": [],
"index": 1,
"createdAt": 1696118400000,
"updatedAt": 1696118400000
}
]
}
```
--------------------------------
### Export Conversations with ChatBotKit Node SDK
Source: https://chatbotkit.com/tutorials/index
Learn how to export chatbot conversations using the ChatBotKit Node SDK. This script allows developers to retrieve and analyze user interactions to improve chatbot performance and gather insights.
```javascript
import { ChatBotKit } from "chatbotkit";
const chatbotkit = new ChatBotKit({
secret: "YOUR_SECRET_KEY"
});
async function exportConversations(chatbotId) {
try {
const conversations = await chatbotkit.conversations.list(chatbotId, {
limit: 100 // Example limit
});
console.log("Exported conversations:", conversations);
// Further processing to save or analyze conversations
return conversations;
} catch (error) {
console.error("Error exporting conversations:", error);
return [];
}
}
// Example: exportConversations("YOUR_CHATBOT_ID");
```