Node SDK

The ChatBotKit Node.js SDK is a powerful, production-ready library for building conversational AI applications. It provides full TypeScript support, streaming capabilities optimized for Edge and Serverless environments, and comprehensive access to all ChatBotKit platform features.

Key Features

  • Full TypeScript Support: Complete type definitions for all API operations
  • Streaming by Default: Optimized for real-time responses in Edge and Serverless environments
  • Comprehensive API Coverage: Access to all ChatBotKit resources and operations
  • Modern Architecture: Built on ES modules with async/await patterns
  • Flexible Client System: Specialized clients for each resource type
  • Production Ready: Battle-tested with retry logic and error handling

Installation

Install the SDK using npm or your preferred package manager:

npm install @chatbotkit/sdk

bash

Requirements:

  • Node.js 14.x or higher
  • ES modules support
  • A ChatBotKit API secret key

Quick Start

The simplest way to get started is with stateless conversation completion:

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) } }

javascript

This example demonstrates the SDK's streaming capabilities, perfect for building responsive chat interfaces.

Client Architecture

The SDK is organized into specialized clients, each handling a specific resource type. You can use individual clients or the main ChatBotKit client that provides access to all resources.

SDK Structure Maps to API Routes

Important: The SDK follows the exact structure of the API routes. This means that every API endpoint has a direct corresponding method in the SDK, making it intuitive to translate between REST API calls and SDK method calls.

The mapping pattern is straightforward:

  • API route: /api/v1/bot/list → SDK method: cbk.bot.list()
  • API route: /api/v1/bot/create → SDK method: cbk.bot.create()
  • API route: /api/v1/dataset/fetch → SDK method: cbk.dataset.fetch()
  • API route: /api/v1/conversation/complete → SDK method: cbk.conversation.complete()

This 1:1 mapping applies to all resources and operations, making it easy to:

  • Reference API documentation when using the SDK
  • Convert curl commands or HTTP requests to SDK calls
  • Understand the SDK structure based on the API reference

For example, if you see an API endpoint /api/v1/skillset/ability/create, you can immediately know the SDK method is cbk.skillset.ability.create(). This consistent structure extends to all nested resources and operations throughout the SDK.

Main Client

import ChatBotKit from '@chatbotkit/sdk' const cbk = new ChatBotKit({ secret: process.env.CHATBOTKIT_API_SECRET }) // Access all resources through the main client const bots = await cbk.bot.list() const datasets = await cbk.dataset.list() const conversations = await cbk.conversation.list()

javascript

Individual Clients

For tree-shaking and smaller bundle sizes, import only the clients you need:

import { BotClient } from '@chatbotkit/sdk/bot/index.js' import { DatasetClient } from '@chatbotkit/sdk/dataset/index.js' import { ConversationClient } from '@chatbotkit/sdk/conversation/index.js' const botClient = new BotClient({ secret: process.env.CHATBOTKIT_API_SECRET }) const bots = await botClient.list()

javascript

Available Clients

The SDK provides clients for all ChatBotKit resources:

  • Platform: platform - Platform-wide operations and settings
  • Bots: bot - Bot creation and management with sessions
  • Conversations: conversation - Conversation management with messages, sessions, and attachments
  • Datasets: dataset - Knowledge base management with records and files
  • Skillsets: skillset - Skillset management with abilities
  • Files: file - File upload, download, and management
  • Tasks: task - Scheduled task automation
  • Contacts: contact - Contact management with conversations, secrets, spaces, and tasks
  • Secrets: secret - Secure credential storage
  • Integrations: integration - Third-party service integrations (Discord, Slack, Widget, etc.)
  • Memory: memory - Conversation memory management
  • Spaces: space - Organizational spaces
  • Teams: team - Team collaboration features
  • Partners: partner - Multi-tenant account management
  • Channels: channel - Real-time pub/sub messaging
  • Magic: magic - Simplified integrations
  • Policies: policy - Access control and policies
  • Portal: portal - Portal management
  • Usage: usage - Usage statistics and monitoring
  • Reports: report - Analytics and reporting
  • GraphQL: graphql - GraphQL query interface
  • Blueprints: blueprint - Template management

Configuration Options

All clients accept the same configuration options:

const cbk = new ChatBotKit({ // Required: Your API secret key secret: process.env.CHATBOTKIT_API_SECRET, // Optional: Run operations as a child user (Partner API) runAsUserId: 'user_123', // Optional: Custom fetch function fetch: customFetch, // Optional: Custom timeout (milliseconds) timeout: 30000, // Optional: Retry configuration retries: 3, retryDelay: 250, retryTimeout: true })

javascript

Working with Bots

Bots are AI agents configured with specific behaviors, models, and capabilities.

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')

javascript

Bot Sessions

Bot sessions provide isolated conversation contexts:

// Create a session const session = await cbk.bot.session.create('bot_abc123', { durationInSeconds: 3600 }) // Use session for conversations const response = await cbk.conversation.complete(null, { botId: 'bot_abc123', messages: [ { type: 'user', text: 'Hello!' } ] })

javascript

Bot Ratings

Collect feedback on bot interactions:

// Upvote a bot await cbk.bot.upvote('bot_abc123', { value: 1 }) // Downvote a bot await cbk.bot.downvote('bot_abc123', { value: 1 })

javascript

Conversations

Conversations are the core of chat interactions, supporting both stateless and stateful patterns.

Stateless Conversations

Perfect for one-off interactions without persistent storage:

// 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) } }

javascript

Stateful Conversations

Create persistent conversation records:

// Create a conversation const conversation = await cbk.conversation.create({ botId: 'bot_abc123', model: 'gpt-4o', privacy: true, moderation: true, meta: { userId: 'user_123', source: 'web-app' } }) // Send messages and receive responses for await (const { type, data } of cbk.conversation .complete(conversation.id, { messages: [ { type: 'user', text: 'I need help with my order' } ] }) .stream()) { if (type === 'token') { process.stdout.write(data.token) } else if (type === 'result') { console.log('\\nUsage:', data.usage) } }

javascript

Conversation Messages

Manage message history:

// List messages const messages = await cbk.conversation.message.list(conversation.id) // Create a message await cbk.conversation.message.create(conversation.id, { type: 'user', text: 'Additional question' }) // Update a message await cbk.conversation.message.update(conversation.id, 'message_123', { text: 'Updated message content' }) // Delete a message await cbk.conversation.message.delete(conversation.id, 'message_123')

javascript

Conversation Attachments

Add files to conversations:

// Create an attachment const attachment = await cbk.conversation.attachment.create(conversation.id, { name: 'document.pdf', type: 'application/pdf', data: fileBuffer }) // List attachments const attachments = await cbk.conversation.attachment.list(conversation.id) // Delete attachment await cbk.conversation.attachment.delete(conversation.id, attachment.id)

javascript

Conversation Ratings

Track conversation quality:

// Upvote conversation await cbk.conversation.upvote(conversation.id, { value: 1 }) // Downvote conversation await cbk.conversation.downvote(conversation.id, { value: 1 })

javascript

Datasets

Datasets provide knowledge bases that bots can reference during conversations.

Creating and Managing Datasets

// Create dataset const dataset = await cbk.dataset.create({ name: 'Product Documentation', description: 'Technical documentation for our products', type: 'text', visibility: 'private' }) // Update dataset await cbk.dataset.update(dataset.id, { description: 'Updated description' }) // Search dataset const results = await cbk.dataset.search(dataset.id, 'installation guide') console.log('Search results:', results) // Delete dataset await cbk.dataset.delete(dataset.id)

javascript

Dataset Records

Add and manage individual entries:

// Create record const record = await cbk.dataset.record.create(dataset.id, { text: 'Installation Guide: Follow these steps to install the software...', meta: { category: 'installation', version: '2.0' } }) // List records for await (const { type, data } of cbk.dataset.record .list(dataset.id) .stream()) { if (type === 'item') { console.log('Record:', data) } } // Update record await cbk.dataset.record.update(dataset.id, record.id, { text: 'Updated content' }) // Delete record await cbk.dataset.record.delete(dataset.id, record.id)

javascript

Dataset Files

Bulk import data from files:

import { createReadStream } from 'fs' // Create file reference const file = await cbk.dataset.file.create(dataset.id, { name: 'knowledge-base.txt', type: 'text/plain' }) // Upload file data const fileStream = createReadStream('./knowledge-base.txt') await cbk.dataset.file.upload(dataset.id, file.id, { data: fileStream }) // Attach file to dataset for processing await cbk.dataset.file.attach(dataset.id, file.id) // Detach when done await cbk.dataset.file.detach(dataset.id, file.id)

javascript

Skillsets

Skillsets provide bots with custom abilities and function-calling capabilities.

Managing Skillsets

// Create skillset const skillset = await cbk.skillset.create({ name: 'Customer Service Tools', description: 'Tools for handling customer inquiries' }) // Update skillset await cbk.skillset.update(skillset.id, { description: 'Updated description' }) // Delete skillset await cbk.skillset.delete(skillset.id)

javascript

Skillset Abilities

Add specific abilities to skillsets:

// Create ability const ability = await cbk.skillset.ability.create(skillset.id, { name: 'check_order_status', description: 'Check the status of a customer order', instruction: 'Call this function when a customer asks about their order', type: 'function', meta: { parameters: { type: 'object', properties: { orderId: { type: 'string' } } } } }) // List abilities const abilities = await cbk.skillset.ability.list(skillset.id) // Update ability await cbk.skillset.ability.update(skillset.id, ability.id, { instruction: 'Updated instruction' }) // Delete ability await cbk.skillset.ability.delete(skillset.id, ability.id)

javascript

Files

Manage file uploads and downloads.

File Operations

import { createReadStream, createWriteStream } from 'fs' // Create file reference const file = await cbk.file.create({ name: 'document.pdf', type: 'application/pdf', meta: { source: 'user-upload' } }) // Upload file data const fileStream = createReadStream('./document.pdf') await cbk.file.upload(file.id, { data: fileStream }) // Download file data const downloadedData = await cbk.file.download(file.id) const writeStream = createWriteStream('./downloaded-document.pdf') downloadedData.pipe(writeStream) // Sync file for processing await cbk.file.sync(file.id) // Delete file await cbk.file.delete(file.id)

javascript

Tasks

Create scheduled or on-demand automated workflows.

Task Management

// Create task const task = await cbk.task.create({ name: 'Daily Report', description: 'Generate daily performance report', botId: 'bot_abc123', contactId: 'contact_xyz789', schedule: 'daily', // or cron: '0 9 * * *' sessionDuration: 3600000 }) // List tasks const tasks = await cbk.task.list() // Update task await cbk.task.update(task.id, { schedule: 'weekly' }) // Trigger task manually await cbk.task.trigger(task.id) // Delete task await cbk.task.delete(task.id)

javascript

Contacts

Manage user contacts and associate them with conversations.

Contact Operations

import { createHash } from 'crypto' // Create contact with fingerprint for automatic deduplication const fingerprint = createHash('sha256') .update(`email:user@example.com`) .digest('hex') .substring(0, 32) const contact = await cbk.contact.create({ fingerprint, name: 'John Doe', email: 'user@example.com', meta: { plan: 'premium', userId: 'internal-123' } }) // List contacts const contacts = await cbk.contact.list() // Update contact await cbk.contact.update(contact.id, { name: 'John Smith' }) // Delete contact await cbk.contact.delete(contact.id)

javascript

Streaming Responses

The SDK is optimized for streaming, essential for real-time chat experiences.

Understanding Stream Types

Streaming responses emit different event types:

for await (const { type, data } of cbk.conversation .complete(null, { model: 'gpt-4o', messages }) .stream()) { switch (type) { case 'token': // Individual token from the AI's response process.stdout.write(data.token) break case 'message': // Complete message object console.log('Message:', data) break case 'result': // Final result with usage stats console.log('Usage:', data.usage) break case 'error': // Error occurred console.error('Error:', data) break } }

javascript

Non-Streaming Responses

For simpler use cases, await the complete response:

const result = await cbk.conversation.complete(null, { model: 'gpt-4o', messages: [ { type: 'user', text: 'Hello!' } ] }) console.log('Response:', result.text) console.log('Usage:', result.usage)

javascript

Partner API

Build multi-tenant applications with account management.

Managing Partner Users

// Create sub-account const user = await cbk.partner.user.create({ email: 'client@company.com', name: 'Client Name', meta: { plan: 'enterprise', companyId: 'comp_123' } }) // List partner users const users = await cbk.partner.user.list() // Update user await cbk.partner.user.update(user.id, { meta: { plan: 'pro' } }) // Delete user await cbk.partner.user.delete(user.id)

javascript

Running Operations as Partner User

// Create client with runAsUserId const clientCbk = new ChatBotKit({ secret: process.env.CHATBOTKIT_API_SECRET, runAsUserId: user.id }) // All operations run under the partner user's account const clientBots = await clientCbk.bot.list() const clientConversations = await clientCbk.conversation.list()

javascript

Secrets

Securely store credentials for integrations.

// Create secret const secret = await cbk.secret.create({ name: 'API_KEY', value: 'sensitive-credential-value', description: 'Third-party API key' }) // List secrets (values are not returned) const secrets = await cbk.secret.list() // Update secret await cbk.secret.update(secret.id, { value: 'new-credential-value' }) // Delete secret await cbk.secret.delete(secret.id)

javascript

Integration Management

Configure third-party service integrations.

Widget Integration

const widget = await cbk.integration.widget.create({ botId: 'bot_abc123', name: 'Website Chat Widget', sessionDuration: 3600 }) await cbk.integration.widget.update(widget.id, { sessionDuration: 7200 })

javascript

Slack Integration

const slack = await cbk.integration.slack.create({ botId: 'bot_abc123', name: 'Support Bot', token: 'xoxb-your-slack-token' })

javascript

Discord Integration

const discord = await cbk.integration.discord.create({ botId: 'bot_abc123', name: 'Community Bot', token: 'your-discord-token' })

javascript

Usage Monitoring

Track API usage and resource consumption.

// Fetch overall usage const usage = await cbk.usage.fetch() console.log('Token usage:', usage.token) console.log('Message count:', usage.message) console.log('Storage used:', usage.storage) // Get usage for specific time period const periodUsage = await cbk.usage.fetch({ startDate: '2025-01-01', endDate: '2025-01-31' })

javascript

Error Handling

The SDK provides structured error handling:

try { const bot = await cbk.bot.create({ name: 'New Bot', model: 'gpt-4o' }) } catch (error) { // HTTP status code console.error('Status:', error.status) // Error message console.error('Message:', error.message) // Error code console.error('Code:', error.code) // Full response body console.error('Body:', error.body) // Handle specific errors if (error.status === 401) { console.error('Invalid API secret') } else if (error.status === 429) { console.error('Rate limit exceeded') } else if (error.status === 413) { console.error('Request too large') } }

javascript

TypeScript Support

The SDK includes comprehensive TypeScript definitions:

import ChatBotKit from '@chatbotkit/sdk' import type { BotCreateRequest, BotCreateResponse, ConversationCompleteRequest, ConversationCompleteResponse } from '@chatbotkit/sdk' const cbk = new ChatBotKit({ secret: process.env.CHATBOTKIT_API_SECRET! }) // Type-safe bot creation const request: BotCreateRequest = { name: 'Support Bot', model: 'gpt-4o', backstory: 'You are a helpful assistant' } const bot: BotCreateResponse = await cbk.bot.create(request)

typescript

Best Practices

Security

  • Never commit API secrets: Use environment variables or secret management services
  • Rotate credentials regularly: Change API keys periodically
  • Use separate keys per environment: Different keys for development, staging, and production
  • Enable privacy and moderation: Protect user data and filter inappropriate content
  • Validate user inputs: Sanitize data before passing to the SDK

Performance

  • Use streaming for chat interfaces: Provides better user experience
  • Implement pagination: Don't fetch all records at once
  • Cache static data: Store frequently accessed bots, datasets, etc.
  • Use individual clients: Import only what you need for smaller bundles
  • Monitor token usage: Track consumption to optimize costs

Architecture

  • Use stateless conversations for simple use cases: Reduces overhead
  • Use stateful conversations for complex flows: Enables history tracking
  • Implement proper error handling: Gracefully handle API errors
  • Use TypeScript: Catch errors at compile time
  • Leverage contact fingerprints: Automatic contact creation with deduplication

Edge and Serverless

The SDK is optimized for Edge and Serverless environments:

// Vercel Edge Function export const config = { runtime: 'edge' } export default async function handler(request) { const client = new ConversationClient({ secret: process.env.CHATBOTKIT_API_SECRET }) const stream = new ReadableStream({ async start(controller) { for await (const { type, data } of client .complete(null, { model: 'gpt-4o', messages }) .stream()) { if (type === 'token') { controller.enqueue(data.token) } } controller.close() } }) return new Response(stream) }

javascript

Additional Resources

Support