@tomymaritano/chatbot-sdk
v1.0.0
Published
Customizable React chatbot SDK for FastAPI backends
Downloads
26
Maintainers
Readme
@tomymaritano/chatbot-sdk
Customizable React chatbot SDK for FastAPI backends with MongoDB support.
Features
- ✅ FastAPI Backend Support - Built specifically for FastAPI + MongoDB backends
- 🎨 Fully Customizable - Components, styles, and themes
- 🔐 Authentication Ready - Bearer tokens, API keys, custom auth
- 💾 Persistent Storage - LocalStorage, SessionStorage, Memory, or custom adapters
- 📱 Responsive Design - Mobile-first, works on all screen sizes
- ⚡ TypeScript - Full type safety with TypeScript
- 🎯 Lightweight - Tree-shakeable, optimized bundle size
- 🌍 I18n Ready - Easy to localize
Installation
npm install @tomymaritano/chatbot-sdk
# or
yarn add @tomymaritano/chatbot-sdk
# or
pnpm add @tomymaritano/chatbot-sdkQuick Start
1. Wrap your app with ChatProvider
import { ChatProvider, ChatWidget } from '@tomymaritano/chatbot-sdk';
import '@tomymaritano/chatbot-sdk/dist/styles.css';
function App() {
return (
<ChatProvider
config={{
api: {
baseURL: 'https://api.yourapp.com',
endpoints: { chat: '/chat' },
auth: {
type: 'bearer',
getToken: () => localStorage.getItem('access_token') || '',
},
},
}}
>
<YourApp />
<ChatWidget />
</ChatProvider>
);
}2. Set up your FastAPI backend
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI()
class ChatMessage(BaseModel):
role: str
content: str
timestamp: Optional[str]
class ChatRequest(BaseModel):
message: str
context: Optional[dict] = None
history: Optional[List[ChatMessage]] = []
class ChatResponse(BaseModel):
status: str
message: str
message_type: str = "text"
suggestions: Optional[List[dict]] = []
metadata: Optional[dict] = {}
@app.post("/api/chat")
async def chat(request: ChatRequest):
# Your chatbot logic here
response_text = f"You said: {request.message}"
return ChatResponse(
status="success",
message=response_text,
message_type="text",
suggestions=[
{"id": "1", "label": "Help", "value": "help"},
{"id": "2", "label": "About", "value": "about"}
]
)Configuration
Full Configuration Example
const config: ChatConfig = {
// API Configuration (Required)
api: {
baseURL: 'https://api.yourapp.com',
endpoints: {
chat: '/chat',
history: '/chat/history', // Optional
},
auth: {
type: 'bearer',
getToken: () => localStorage.getItem('token') || '',
headerName: 'Authorization', // Optional, defaults to 'Authorization'
},
headers: {
// Optional custom headers
'X-Custom-Header': 'value',
},
},
// Storage Configuration (Optional)
storage: {
type: 'localStorage', // 'localStorage' | 'sessionStorage' | 'memory' | 'custom'
key: 'my-chat-history',
maxMessages: 100,
// adapter: customStorageAdapter, // For custom storage
},
// UI Configuration (Optional)
ui: {
position: 'bottom-right', // 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'
theme: 'light', // 'light' | 'dark' | 'auto'
locale: 'en-US',
showQuickActions: true,
maxHeight: '600px',
maxWidth: '400px',
},
// Theme Configuration (Optional)
theme: {
colors: {
primary: '#6366f1',
background: '#ffffff',
text: '#1f2937',
userMessage: '#3b82f6',
botMessage: '#f3f4f6',
border: '#e5e7eb',
},
fonts: {
family: 'Inter, sans-serif',
sizes: {
base: '14px',
small: '12px',
large: '16px',
},
},
spacing: {
padding: '1rem',
gap: '0.5rem',
borderRadius: '1rem',
},
},
// Event Callbacks (Optional)
callbacks: {
onMessageSent: (message) => console.log('Sent:', message),
onMessageReceived: (message) => console.log('Received:', message),
onError: (error) => console.error('Error:', error),
onOpen: () => console.log('Chat opened'),
onClose: () => console.log('Chat closed'),
},
// Custom Components (Optional)
components: {
// chatBubble: CustomBubble,
// chatWindow: CustomWindow,
// message: CustomMessage,
// input: CustomInput,
// header: CustomHeader,
},
};Authentication
Bearer Token (JWT)
config={{
api: {
baseURL: 'https://api.yourapp.com',
endpoints: { chat: '/chat' },
auth: {
type: 'bearer',
getToken: async () => {
// Can be async
const token = await getTokenFromSomewhere();
return token;
}
}
}
}}API Key
config={{
api: {
baseURL: 'https://api.yourapp.com',
endpoints: { chat: '/chat' },
auth: {
type: 'api-key',
getToken: () => process.env.REACT_APP_API_KEY || '',
headerName: 'X-API-Key'
}
}
}}No Authentication
config={{
api: {
baseURL: 'https://api.yourapp.com',
endpoints: { chat: '/chat' }
// No auth config needed
}
}}Custom Components
Replace any component with your own:
import { ChatProvider, ChatWidget, MessageProps } from '@tomymaritano/chatbot-sdk';
function CustomMessage({ message }: MessageProps) {
return (
<div className={`custom-message ${message.role}`}>
<img src={message.role === 'user' ? userAvatar : botAvatar} />
<p>{message.content}</p>
<time>{new Date(message.timestamp).toLocaleTimeString()}</time>
</div>
);
}
<ChatProvider
config={{
api: { ... },
components: {
message: CustomMessage
}
}}
>
<ChatWidget />
</ChatProvider>Theming
CSS Variables
All styles are customizable via CSS variables:
:root {
--chatbot-primary: #6366f1;
--chatbot-bg: #ffffff;
--chatbot-text: #1f2937;
--chatbot-userMessage: #3b82f6;
--chatbot-botMessage: #f3f4f6;
--chatbot-border: #e5e7eb;
--chatbot-font-family: 'Inter', sans-serif;
--chatbot-font-size-base: 14px;
--chatbot-borderRadius: 1rem;
--chatbot-transition: 200ms ease-in-out;
}Dark Mode
<ChatProvider
config={{
ui: { theme: 'dark' }
}}
>
<ChatWidget />
</ChatProvider>Or manually:
[data-chatbot-theme="dark"] {
--chatbot-bg: #1f2937;
--chatbot-text: #f9fafb;
--chatbot-botMessage: #374151;
--chatbot-border: #4b5563;
}FastAPI Backend Contract
Required Endpoint
POST /api/chat
Request:
{
"message": "Hello",
"context": {},
"history": [
{ "role": "user", "content": "Hi", "timestamp": "2024-01-15T10:00:00Z" },
{ "role": "assistant", "content": "Hello!", "timestamp": "2024-01-15T10:00:01Z" }
]
}Response:
{
"status": "success",
"message": "Hello! How can I help you?",
"message_type": "text",
"suggestions": [
{ "id": "1", "label": "Help", "action": "command", "value": "help" }
],
"metadata": {
"response_time_ms": 150,
"source": "ai"
}
}Error Response
{
"status": "error",
"message": "Authentication required",
"error_code": "AUTH_REQUIRED",
"details": {}
}Error Codes
AUTH_REQUIRED(401) - Authentication neededRATE_LIMIT(429) - Too many requestsINVALID_INPUT(400) - Bad requestSERVER_ERROR(500) - Server error
Storage
Custom Storage Adapter
import { StorageAdapter } from '@tomymaritano/chatbot-sdk';
const customStorage: StorageAdapter = {
async getItem(key: string) {
return await yourDatabase.get(key);
},
async setItem(key: string, value: string) {
await yourDatabase.set(key, value);
},
async removeItem(key: string) {
await yourDatabase.delete(key);
}
};
<ChatProvider
config={{
api: { ... },
storage: {
type: 'custom',
adapter: customStorage
}
}}
>
<ChatWidget />
</ChatProvider>Examples
See the examples/ directory for complete examples:
- basic/ - Minimal setup
- custom-theme/ - Custom colors and fonts
- custom-components/ - Replace default components
TypeScript
Full TypeScript support with exported types:
import type {
ChatConfig,
ChatMessage,
QuickAction,
ChatResponse,
APIConfig,
AuthConfig
} from '@tomymaritano/chatbot-sdk';Browser Support
- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
License
MIT © Tomy Maritano
Contributing
Contributions are welcome! Please open an issue or submit a pull request.
Support
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
Made with ❤️ for the FastAPI + React community
