Node SDK

Getting Started

The Chatbotkit Node.js SDK provides a powerful interface for building and managing AI-powered chatbots. This comprehensive guide covers all major endpoints, features, and best practices for integrating Chatbotkit into your Node.js applications.

Key Features

  • Bot creation and management
  • Dataset handling for training and fine-tuning
  • Conversation management and history
  • Partner API for multi-tenant applications
  • Usage monitoring and analytics
  • Error handling and debugging

Getting Started

Installation

npm install @chatbotkit/sdk # or yarn add @chatbotkit/sdk

shell

Prerequisites

  • Node.js 14.x or higher
  • A Chatbotkit API key
  • Basic understanding of async/await patterns

Authentication

Authentication is handled through your API key, which should be stored securely in environment variables.

import { ChatBotKit } from '@chatbotkit/sdk'; // Basic initialization const cbk = new ChatBotKit({ secret: process.env.CHATBOTKIT_API_KEY }); // With custom configuration const cbk = new ChatBotKit({ secret: process.env.CHATBOTKIT_API_KEY, timeout: 30000, // 30 seconds baseURL: '<https://api.chatbotkit.com/v1>' });

javascript

Best practices for API key management:

  • Never hardcode API keys in your source code
  • Use environment variables or secure secret management
  • Rotate API keys periodically
  • Use different API keys for development and production

Bot Management

Creating a Bot

The bot creation API supports various configuration options to customize your chatbot's behavior.

const bot = await cbk.bot.create({ name: 'SupportBot', model: 'gpt-4', backstory: 'A helpful customer support assistant with expertise in technical troubleshooting', instructions: 'Always maintain a professional tone. Ask clarifying questions when needed.', temperature: 0.7, maxTokens: 2048 }); console.log(bot.id); // Access the new bot's ID

javascript

Configuration options:

  • name: Identifier for your bot
  • model: AI model to use (e.g., 'gpt-4', 'gpt-3.5-turbo')
  • backstory: Context and personality definition
  • instructions: Specific behavioral guidelines
  • temperature: Controls response randomness (0-1)
  • maxTokens: Maximum response length

Managing Bots

// List all bots with pagination const bots = await cbk.bot.list({ skip: 0, take: 20, order: 'desc' }); // Fetch specific bot const bot = await cbk.bot.fetch('bot-id'); // Update bot configuration await cbk.bot.update('bot-id', { name: 'Updated Name', instructions: 'New instructions for behavior' }); // Delete bot await cbk.bot.delete('bot-id');

javascript

Dataset Management

Datasets are essential for training your bot with custom knowledge.

Creating and Managing Datasets

// Create a new dataset const dataset = await cbk.dataset.create({ name: 'Product FAQs', visibility: 'private', description: 'Frequently asked questions about our products' }); // Add entries to dataset await cbk.dataset.record.create(dataset.id, { type: 'qa', question: 'What is your return policy?', answer: 'We offer a 30-day return policy for unused items.' }); // Search dataset const results = await cbk.dataset.search(dataset.id, 'return policy', { limit: 10, threshold: 0.7 });

javascript

Dataset types:

  • QA pairs
  • Conversational examples
  • Product information
  • Company policies

Conversations

Manage ongoing conversations and chat history.

// Start a new conversation const conversation = await cbk.conversation.create({ model: 'gpt-4', context: 'Customer support interaction', metadata: { userId: 'user123', sessionId: 'session456' } }); // Add messages to conversation await cbk.conversation.message.create(conversation.id, { role: 'user', content: 'How can I reset my password?' }); // Get conversation history const messages = await cbk.conversation.message.list(conversation.id);

javascript

Partner API

The Partner API enables multi-tenant applications and sub-account management.

// Create a sub-account const subAccount = await cbk.partner.user.create({ email: 'client@example.com', name: 'Client Organization', metadata: { plan: 'premium', industry: 'healthcare' } }); // Run operations as sub-account const partnerCbk = new ChatBotKit({ secret: process.env.CHATBOTKIT_API_KEY, runAsChildUserId: subAccount.id }); // Manage sub-account resources const clientBots = await partnerCbk.bot.list();

javascript

Usage Monitoring

Track API usage and manage resources effectively.

// Get overall usage statistics const usage = await cbk.usage.fetch(); // Get detailed usage breakdown const details = await cbk.usage.fetch({ startDate: '2024-01-01', endDate: '2024-01-31', granularity: 'daily' });

javascript

Error Handling

try { const bot = await cbk.bot.create({ name: 'NewBot' }); } catch (error) { if (error.status === 429) { // Handle rate limiting console.log('Rate limit exceeded. Retry after:', error.headers['retry-after']); } else if (error.status === 401) { // Handle authentication errors console.log('Invalid API key'); } else { // Handle other errors console.error('Operation failed:', error.message); } }

javascript

Common error codes:

  • 400: Bad Request
  • 401: Unauthorized
  • 403: Forbidden
  • 429: Too Many Requests
  • 500: Internal Server Error

Best Practices

  1. Error Handling
    • Implement proper try-catch blocks
    • Handle rate limiting gracefully
    • Log errors for debugging
  2. Security
    • Store API keys securely
    • Implement proper access controls
    • Validate user inputs
  3. Performance
    • Use pagination for large datasets
    • Implement caching where appropriate
    • Monitor API usage
  4. Development
    • Use TypeScript for better type safety
    • Follow API versioning guidelines
    • Maintain comprehensive tests

References

Support Resources