chat-agent-sdk-csstacktr
Version:
Lightweight SDK for embedding chat agents powered by multiple LLMs and Contentstack
671 lines (540 loc) ⢠19.1 kB
Markdown
# Chat Agent Platform SDK
[](https://badge.fury.io/js/chat-agent-sdk-csstacktr)
[](https://opensource.org/licenses/MIT)
[](http://www.typescriptlang.org/)
A powerful, lightweight SDK for embedding AI chat agents powered by multiple LLMs (Groq, OpenAI, Gemini) with **dynamic Contentstack integration**. Perfect for creating domain-specific chat experiences that work with any Contentstack project.
> š **ZERO CONFIGURATION REQUIRED** - Just install and start chatting! See [Minimal Usage Guide](./MINIMAL_USAGE.md) for instant setup.
## š Table of Contents
- [Zero Config Quick Start](#-zero-config-quick-start)
- [Key Features](#-key-features)
- [Installation](#-installation)
- [Advanced Configuration](#-advanced-configuration)
- [Dynamic Content Integration](#ļø-dynamic-content-integration)
- [Real-World Examples](#-real-world-examples)
- [API Reference](#ļø-api-reference)
- [LLM Providers](#-llm-providers)
- [Advanced Usage](#-advanced-usage)
- [Error Handling](#-error-handling)
- [Browser Support](#-browser-support)
- [Contributing](#-contributing)
- [Support](#-support)
## š Zero Config Quick Start
**Just want to get chatting? Use these ultra-minimal functions:**
```javascript
// 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](./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
### Using with Vercel Deployment (Recommended)
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);
```
### React Component Example
```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 (
<div>
<div className="messages">
{messages.map((msg, i) => (
<div key={i} className={msg.role}>{msg.content}</div>
))}
</div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
/>
<button onClick={handleSendMessage}>Send</button>
</div>
);
}
```
### Vanilla JavaScript Example
```html
<!DOCTYPE html>
<html>
<body>
<div id="chat-container"></div>
<script type="module">
import { createSimpleVanillaSDK } from 'https://cdn.skypack.dev/chat-agent-sdk-csstacktr';
// Automatically connects to Vercel deployment
const chat = createSimpleVanillaSDK({
containerId: 'chat-container',
provider: 'openai'
});
</script>
</body>
</html>
```
### Custom API Endpoint
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`](./VERCEL_USAGE.md) for complete usage examples with the Vercel deployment.
### React Integration with Dynamic Contentstack
```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 (
<div className="chat-container">
{schema && <p>Connected to {schema.contentTypes.length} content types</p>}
<div className="messages">
{messages.map(msg => (
<div key={msg.id} className={`message ${msg.role}`}>
{msg.content}
</div>
))}
</div>
<form onSubmit={async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
await sendMessage(formData.get('message'));
e.target.reset();
}}>
<input
name="message"
placeholder="Ask about your content..."
disabled={isLoading}
/>
<button type="submit">{isLoading ? 'Sending...' : 'Send'}</button>
</form>
</div>
);
}
```
### Vanilla JavaScript
```html
<!DOCTYPE html>
<html>
<head>
<title>AI Chat Assistant</title>
</head>
<body>
<div id="chat-widget"></div>
<script type="module">
import { ChatAgentSDK } from 'chat-agent-sdk-csstacktr';
const chat = new ChatAgentSDK({
apiUrl: 'https://your-backend-api.com',
contentstack: {
apiKey: 'your_contentstack_api_key',
deliveryToken: 'your_contentstack_delivery_token',
environment: 'production'
},
provider: 'gemini', // Free Google AI
containerId: 'chat-widget' // Auto-renders here!
});
</script>
</body>
</html>
```
## ļæ½ļø Dynamic Content Integration
Unlike traditional chatbots that work with hardcoded domains, our SDK **dynamically connects to your Contentstack project**:
### Before vs After
**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
### Travel Company
```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
```
### E-commerce Store
```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](https://www.npmjs.com/package/chat-agent-sdk-csstacktr)
- **š GitHub Repository**: [tanish435/chat-agent-platform-sdk](https://github.com/tanish435/chat-agent-platform-sdk)
- **š Documentation**: [Full Documentation](https://github.com/tanish435/chat-agent-platform-sdk#readme)
## š 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
### React Hook Usage
```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 (
<div>
{messages.map(msg => (
<div key={msg.id}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
{/* Your input component */}
</div>
);
}
```
### Vanilla JavaScript Usage
```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
### Configuration Options
```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
}
```
### React Hooks
#### `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.
### Vanilla JavaScript SDK
#### `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
### Groq (Free)
```javascript
{
provider: 'groq',
model: 'llama-3.1-8b-instant' // Fast and free
}
```
### OpenAI via OpenRouter (Paid)
```javascript
{
provider: 'openai',
model: 'gpt-4o-mini', // Cost-effective GPT-4
apiKey: 'your-openrouter-key'
}
```
### Google Gemini (Free Tier)
```javascript
{
provider: 'gemini',
model: 'gemini-1.5-flash', // Fast with generous free tier
apiKey: 'your-gemini-key'
}
```
## š§ Advanced Usage
### Custom Event Handling
```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);
}
}
});
```
### React with Custom Styling
```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 (
<div className="my-custom-chat">
<MessageList messages={chat.messages} />
<ChatInput onSend={chat.sendMessage} disabled={chat.isLoading} />
{chat.error && <ErrorDisplay error={chat.error} />}
</div>
);
}
```
### Environment Variables
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}`
}
});
```
## š Browser Support
- Chrome 60+
- Firefox 55+
- Safari 11+
- Edge 79+
## š License
MIT License - see LICENSE file for details.
## š¤ Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request
## š Support
- š§ Email: support@chat-agent-platform.com
- š Issues: [GitHub Issues](https://github.com/tanish435/chat-agent-platform-sdk/issues)
- š Docs: [Full Documentation](https://chat-agent-platform.dev/docs)
---
Made with ā¤ļø by the Chat Agent Platform team