Lightweight SDK for embedding chat agents powered by multiple LLMs and Contentstack
npm install chat-agent-sdk-csstacktrjavascript
// React Component
import { createChatAgentNow } from 'chat-agent-sdk-csstacktr';
const chatAgent = createChatAgentNow(); // Zero config needed!
const response = await chatAgent.sendMessage("Hello!");
`
`javascript
// Vanilla JavaScript
import { createVanillaSDKNow } from 'chat-agent-sdk-csstacktr';
const chatSDK = createVanillaSDKNow('chat-container'); // Zero config needed!
await chatSDK.sendMessage("Hello!");
`
That's it! The SDK automatically connects to the production server and starts working. See MINIMAL_USAGE.md for complete copy-paste examples.
⨠Key Features
- š Dynamic Contentstack Integration - Connect to ANY Contentstack project with your own credentials
- š¤ Multi-LLM Support - Groq (free), OpenAI, and Google Gemini
- ā” Auto-Discovery - Automatically detects your content structure
- š Multi-Region - Supports all Contentstack regions (US, EU, Azure, GCP)
- āļø React Hooks - useChat, useChatAgent, useStreamingChat
- š¦ Vanilla JS - Works in any HTML/JS application
- š± Responsive UI - Auto-rendering chat interface
- š Real-time Streaming - Live response streaming
- š Legacy Support - Backward compatible with domain-based configs
- Domain-Specific Knowledge: Powered by Contentstack CMS
- Customizable: Flexible configuration and styling options
š¦ Installation
`bash
npm install chat-agent-sdk-csstacktr
`
š Quick Start
$3
The easiest way to get started is with our hosted Chat Agent Platform:
`javascript
import { createSimpleChatAgent } from 'chat-agent-sdk-csstacktr';
// Automatically connects to https://chat-agent-platform-server.vercel.app
const chatAgent = createSimpleChatAgent({
provider: 'openai', // or 'anthropic', 'groq', 'gemini'
// apiKey: 'your-api-key', // Add if authentication is required
});
await chatAgent.connect();
const response = await chatAgent.sendMessage('Hello!');
console.log(response.content);
`
$3
`jsx
import React, { useState } from 'react';
import { createSimpleChatAgent } from 'chat-agent-sdk-csstacktr';
function ChatComponent() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const chatAgent = createSimpleChatAgent({
provider: 'openai'
});
const handleSendMessage = async () => {
try {
const response = await chatAgent.sendMessage(input);
setMessages(prev => [...prev,
{ content: input, role: 'user' },
response
]);
setInput('');
} catch (error) {
console.error('Chat error:', error);
}
};
return (
{messages.map((msg, i) => (
{msg.content}
))}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
/>
);
}
`
$3
`html
`
$3
If you're running your own server:
`javascript
import { ChatAgent } from 'chat-agent-sdk-csstacktr';
const chatAgent = new ChatAgent({
apiEndpoint: 'https://your-custom-api.com', // Your custom endpoint
provider: 'openai',
apiKey: 'your-api-key'
});
`
š Server Status
- Production Server: https://chat-agent-platform-server.vercel.app/ š¢
- Health Check: https://chat-agent-platform-server.vercel.app/api/health
See VERCEL_USAGE.md for complete usage examples with the Vercel deployment.
$3
`tsx
import { useChat } from 'chat-agent-sdk-csstacktr';
function MyCustomChatbot() {
const { messages, sendMessage, isLoading, schema } = useChat({
apiUrl: 'https://your-backend-api.com',
contentstack: {
apiKey: process.env.REACT_APP_CONTENTSTACK_API_KEY,
deliveryToken: process.env.REACT_APP_CONTENTSTACK_DELIVERY_TOKEN,
environment: 'production',
region: 'us'
},
autoDiscoverContentTypes: true, // Automatically detect your content structure
provider: 'groq', // Free and fast!
model: 'llama-3.1-8b-instant'
});
return (
{schema && Connected to {schema.contentTypes.length} content types
}
{messages.map(msg => (
message ${msg.role}}>
{msg.content}
))}
);
}
`
$3
`html
AI Chat Assistant
`
ļæ½ļø Dynamic Content Integration
Unlike traditional chatbots that work with hardcoded domains, our SDK dynamically connects to your Contentstack project:
$3
Before (Hardcoded Domains):
`tsx
const chat = useChat({
apiUrl: 'https://api.example.com',
domain: 'travel', // Limited to predefined domains
provider: 'groq'
});
`
After (Dynamic Contentstack):
`tsx
const chat = useChat({
apiUrl: 'https://api.example.com',
contentstack: {
apiKey: 'your_api_key',
deliveryToken: 'your_token'
},
autoDiscoverContentTypes: true, // Works with ANY content
provider: 'groq'
});
`
š Real-World Examples
$3
`tsx
const travelChat = useChat({
apiUrl: 'https://api.travelcompany.com',
contentstack: {
apiKey: 'blt_travel_api_key',
deliveryToken: 'cs_travel_delivery_token',
environment: 'production'
},
contentTypes: [
{
uid: 'tour_package',
title: 'Tour Package',
searchableFields: ['title', 'description', 'destination'],
filterableFields: [
{ uid: 'price', dataType: 'number' },
{ uid: 'duration', dataType: 'number' }
]
}
],
provider: 'groq'
});
// User asks: "Find tours in Italy under $2000"
// SDK automatically queries your tour_package content
// AI responds with actual tour data from your Contentstack
`
$3
`tsx
const ecommerceChat = useChat({
apiUrl: 'https://api.shopsite.com',
contentstack: {
apiKey: 'blt_ecommerce_api_key',
deliveryToken: 'cs_ecommerce_delivery_token'
},
contentTypes: [
{
uid: 'product',
title: 'Product',
searchableFields: ['title', 'description', 'brand'],
filterableFields: [
{ uid: 'price', dataType: 'number' },
{ uid: 'category', dataType: 'text' }
]
}
],
provider: 'openai'
});
// User asks: "Show me Sony headphones under $200"
// SDK queries your product content with filters
// AI responds with actual products from your inventory
`
ļæ½šÆ Perfect For
- Travel Websites - "Find tours in Italy under $2000"
- E-commerce - "Show me wireless headphones under $100"
- Real Estate - "Find 3-bedroom houses near downtown"
- Healthcare - "Find pediatricians accepting new patients"
- Education - "Find programming courses for beginners"
- Any CMS-powered site - Dynamic content integration
š Ready to Deploy
Your Chat Agent Platform SDK is production-ready with:
ā
Dynamic Contentstack Integration - Works with any Contentstack project
ā
Multi-LLM Support - Groq, OpenAI, Gemini
ā
Auto-Discovery - Detects content structure automatically
ā
React & Vanilla JS - Multiple integration options
ā
TypeScript - Full type safety
ā
Streaming - Real-time responses
ā
Multi-Region - Global Contentstack support
ā
Legacy Compatible - Smooth migration path
Transform any website into an intelligent chat experience powered by your actual content! š
š Links
- š¦ NPM Package: chat-agent-sdk-csstacktr
- š GitHub Repository: tanish435/chat-agent-platform-sdk
- š Documentation: Full Documentation
š Version History
- v1.0.3: Fixed dependency issues for better installation experience
- v1.0.2: Updated repository URLs and improved package metadata
- v1.0.0: Initial release with dynamic Contentstack integration
$3
`tsx
import React from 'react';
import { useChat } from 'chat-agent-sdk-csstacktr';
function ChatComponent() {
const { messages, sendMessage, isLoading, error } = useChat({
apiUrl: 'https://your-api-endpoint.com',
domain: 'travel',
provider: 'groq',
streaming: true
});
const handleSend = async (message: string) => {
await sendMessage(message);
};
return (
{messages.map(msg => (
{msg.role}: {msg.content}
))}
{/ Your input component /}
);
}
`
$3
`javascript
import { ChatAgentSDK } from 'chat-agent-sdk-csstacktr';
const chatAgent = new ChatAgentSDK({
apiUrl: 'https://your-api-endpoint.com',
domain: 'ecommerce',
provider: 'gemini',
containerId: 'chat-container', // Will render UI here
handlers: {
onMessage: (message) => console.log('New message:', message),
onError: (error) => console.error('Chat error:', error)
}
});
// Send a message programmatically
await chatAgent.sendMessage('Hello, I need help with my order');
`
š ļø API Reference
$3
`typescript
interface ChatAgentConfig {
apiUrl: string; // Your chat agent API endpoint
domain: string; // Content domain (travel, ecommerce, etc.)
provider?: 'groq' | 'openai' | 'gemini';
model?: string; // Specific model to use
apiKey?: string; // Optional API key
systemPrompt?: string; // Custom system prompt
maxTokens?: number; // Response length limit
temperature?: number; // Response creativity (0-1)
streaming?: boolean; // Enable streaming responses
}
`
$3
#### useChat(config)
Basic chat functionality with automatic message management.
`typescript
const {
messages, // Array of ChatMessage objects
isLoading, // Boolean: request in progress
isConnected, // Boolean: connection status
error, // Error object or null
sendMessage, // Function to send messages
clearMessages, // Function to clear chat history
reconnect, // Function to reconnect
disconnect // Function to disconnect
} = useChat(config);
`
#### useChatAgent(config)
Advanced chat functionality with session management and configuration updates.
#### useStreamingChat(config)
Optimized for real-time streaming responses.
$3
#### new ChatAgentSDK(options)
Create a new chat agent instance.
`javascript
const chatAgent = new ChatAgentSDK({
...config,
containerId: 'my-chat-div', // Optional: auto-render UI
handlers: { // Optional: event handlers
onMessage: (message) => {},
onError: (error) => {},
onConnect: () => {},
onDisconnect: () => {},
onTyping: (isTyping) => {}
}
});
`
#### Methods
- sendMessage(content, options) - Send a message
- clearMessages() - Clear chat history
- getMessages() - Get all messages
- renderChat(containerId) - Render UI in container
- connect() - Connect to the platform
- disconnect() - Disconnect from the platform
šØ Domains
Choose from pre-configured domains for specialized knowledge:
- travel - Travel & Tourism
- ecommerce - E-Commerce & Shopping
- education - Education & Learning
- healthcare - Healthcare Services
- realestate - Real Estate
- restaurants - Restaurants & Food
š¤ LLM Providers
$3
`javascript
{
provider: 'groq',
model: 'llama-3.1-8b-instant' // Fast and free
}
`
$3
`javascript
{
provider: 'openai',
model: 'gpt-4o-mini', // Cost-effective GPT-4
apiKey: 'your-openrouter-key'
}
`
$3
`javascript
{
provider: 'gemini',
model: 'gemini-1.5-flash', // Fast with generous free tier
apiKey: 'your-gemini-key'
}
`
š§ Advanced Usage
$3
`javascript
const chatAgent = new ChatAgentSDK({
apiUrl: 'https://api.example.com',
domain: 'travel',
handlers: {
onMessage: (message) => {
// Update your custom UI
updateChatUI(message);
},
onStreamChunk: (chunk) => {
// Handle streaming content
appendToMessage(chunk.content);
},
onError: (error) => {
// Handle errors gracefully
showErrorNotification(error.message);
}
}
});
`
$3
`tsx
import { useChat, ChatMessage } from 'chat-agent-sdk-csstacktr';
function CustomChat() {
const chat = useChat({
apiUrl: process.env.REACT_APP_CHAT_API,
domain: 'travel',
provider: 'groq',
systemPrompt: 'You are a helpful travel advisor specializing in adventure tourism.'
});
return (
{chat.error && }
);
}
`
$3
For security, store sensitive configuration in environment variables:
`env
REACT_APP_CHAT_API_URL=https://your-api-endpoint.com
REACT_APP_CHAT_DOMAIN=travel
REACT_APP_CHAT_PROVIDER=groq
`
šØ Error Handling
The SDK provides comprehensive error handling:
`javascript
try {
await chatAgent.sendMessage('Hello');
} catch (error) {
if (error.message.includes('404')) {
console.error('API endpoint not found');
} else if (error.message.includes('rate limit')) {
console.error('Too many requests, please wait');
} else {
console.error('Unexpected error:', error);
}
}
`
šÆ Best Practices
1. Error Boundaries: Use React error boundaries for production apps
2. Loading States: Always show loading indicators during requests
3. Rate Limiting: Implement client-side rate limiting for free tiers
4. Responsive Design: Test chat UI on mobile devices
5. Accessibility: Include proper ARIA labels and keyboard navigation
š± Examples
Check the /examples directory for complete implementations:
- react-example.tsx - Full React component with hooks
- vanilla-example.html - Complete HTML/JS implementation
- next-js-example/ - Next.js integration example
š Authentication
For production use, implement proper authentication:
`javascript
const chatAgent = new ChatAgentSDK({
apiUrl: 'https://api.yourapp.com',
domain: 'travel',
apiKey: await getAuthToken(), // Your auth token
headers: {
'Authorization': Bearer ${userToken}
}
});
``