ai-chatbot-agent
v0.2.3
Published
A customizable AI-powered chatbot widget for React apps.
Readme
AI Chatbot Agent
A customizable, modern AI-powered chatbot widget for React applications. Built with Chakra UI and TypeScript for seamless integration and full customization.
🚀 Features
- Easy Integration: Drop-in component for any React app
- Fully Customizable: Colors, themes, and styling options
- Flexible API: GET/POST methods, custom request builder for full control
- Multiple Display Modes: Popup overlay or side panel with content push option
- TypeScript Support: Built-in type definitions
- Responsive Design: Works on desktop and mobile
- Modern UI: Clean, professional interface with Chakra UI
- Message Formatting: Built-in support for formatted bot responses
- Auto-scroll: Smooth scrolling to latest messages
- Keyboard Support: Enter to send, Shift+Enter for new line
📦 Installation
npm install ai-chatbot-agent @chakra-ui/react react-icons🎯 Quick Start
import React from 'react';
import { ChakraProvider } from '@chakra-ui/react';
import { ChatbotWidget } from 'ai-chatbot-agent';
function App() {
return (
<ChakraProvider>
<div>
<ChatbotWidget
apiEndpoint="/api/chatbot"
aiName="Assistant"
/>
</div>
</ChakraProvider>
);
}
export default App;🔧 Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| aiName | string | "AI Chatbot" | Name displayed in chat header |
| apiEndpoint | string | "/api/chatbot" | Your chatbot API endpoint |
| apiMethod | 'GET' \| 'POST' | "GET" | HTTP method for API requests |
| apiRequestBuilder | function | undefined | Custom function to build API requests (full control) |
| apiResponseTransformer | function | undefined | Custom function to extract bot reply from API response |
| bgColor | string | "white" | Chat window background color |
| textColor | string | "gray.800" | Text color for headers |
| buttonBgColor | string | "black" | Send button background color |
| buttonTextColor | string | "white" | Send button text color |
| launcherColorScheme | string | "blue" | Color scheme for launcher button |
| userMessageBg | string | "blue" | Background color for user messages |
| botMessageBg | string | "gray.50" | Background color for bot messages |
| botGreeting | string | "Hi! I'm your AI assistant..." | Initial bot greeting message |
| displayMode | 'popup' \| 'sidepanel' | "popup" | Display as popup overlay or side panel |
| position | 'bottom-right' \| 'bottom-left' \| 'top-right' \| 'top-left' | "bottom-right" | Position of launcher button |
| sidePanelWidth | string | "400px" | Width of side panel (when displayMode is 'sidepanel') |
| sidePanelHeight | string | "100vh" | Height of side panel (when displayMode is 'sidepanel') |
| sidePanelPushContent | boolean | false | Push page content instead of overlaying (sidepanel mode only) |
| popupWidth | string | "380px" | Width of popup (when displayMode is 'popup') |
| popupHeight | string | "500px" | Max height of popup (when displayMode is 'popup') |
| showOverlay | boolean | false | Show dark overlay/backdrop behind chat |
| closeOnClickOutside | boolean | true | Close chat when clicking overlay (requires showOverlay) |
| defaultOpen | boolean | false | Open chat by default on page load |
| enableAnimation | boolean | true | Enable smooth animations for open/close |
| botIcon | React.ReactNode | undefined | Custom icon component for the launcher button |
| botIconSrc | string | undefined | Image URL for the bot icon |
| botIconSrcSet | string | undefined | Responsive image srcset for bot icon (best practice) |
| botIconAlt | string | "Chatbot" | Alt text for bot icon image |
| botIconSize | string | "24px" | Size of the bot icon (width and height) |
| onMessageSent | function | undefined | Callback when user sends a message |
| onMessageReceived | function | undefined | Callback when bot responds |
| onOpen | function | undefined | Callback when chat opens |
| onClose | function | undefined | Callback when chat closes |
💡 Usage Examples
Basic Setup
<ChatbotWidget
apiEndpoint="/api/chatbot"
aiName="Sarah"
/>Custom Styling
<ChatbotWidget
aiName="Support Bot"
apiEndpoint="/api/support"
bgColor="blue.50"
textColor="blue.800"
buttonBgColor="blue.500"
buttonTextColor="white"
launcherColorScheme="blue"
userMessageBg="blue"
botMessageBg="white"
botGreeting="Hello! I'm here to help with your questions."
/>Purple Theme Example
<ChatbotWidget
aiName="Alex Assistant"
apiEndpoint="/api/chatbot"
bgColor="purple.50"
textColor="purple.800"
buttonBgColor="purple.600"
userMessageBg="purple"
botMessageBg="white"
launcherColorScheme="purple"
/>With Event Callbacks
<ChatbotWidget
aiName="Customer Support"
apiEndpoint="/api/chatbot"
onMessageSent={(message) => {
console.log('User sent:', message);
// Track user interactions
}}
onMessageReceived={(reply) => {
console.log('Bot replied:', reply);
// Handle bot responses
}}
/>Custom Bot Icon - Image with Srcset (Recommended)
<ChatbotWidget
aiName="Helper Bot"
apiEndpoint="/api/chatbot"
botIconSrc="/icons/bot-icon.png"
botIconSrcSet="/icons/bot-icon.png 1x, /icons/[email protected] 2x, /icons/[email protected] 3x"
botIconAlt="Helper Bot"
botIconSize="28px"
/>Custom Bot Icon - Simple Image
<ChatbotWidget
aiName="Support Bot"
apiEndpoint="/api/chatbot"
botIconSrc="https://your-domain.com/bot-avatar.png"
botIconAlt="Support Bot"
/>Custom Bot Icon - React Component
import { FaComments } from 'react-icons/fa';
<ChatbotWidget
aiName="Chat Assistant"
apiEndpoint="/api/chatbot"
botIcon={<FaComments size={24} />}
/>Side Panel Mode (Like Stripe Docs)
<ChatbotWidget
aiName="Assistant"
apiEndpoint="/api/chatbot"
displayMode="sidepanel"
sidePanelWidth="450px"
sidePanelHeight="100vh"
/>Side Panel with Content Push (No Overlay)
<ChatbotWidget
aiName="Assistant"
apiEndpoint="/api/chatbot"
displayMode="sidepanel"
sidePanelWidth="400px"
sidePanelPushContent={true}
/>Side Panel with Custom Position
<ChatbotWidget
aiName="Support"
apiEndpoint="/api/chatbot"
displayMode="sidepanel"
position="bottom-left"
sidePanelWidth="400px"
bgColor="gray.50"
/>Popup Mode with Custom Position
<ChatbotWidget
aiName="Helper"
apiEndpoint="/api/chatbot"
displayMode="popup"
position="bottom-left"
/>Popup with Overlay and Custom Size
<ChatbotWidget
aiName="Support"
apiEndpoint="/api/chatbot"
showOverlay={true}
closeOnClickOutside={true}
popupWidth="450px"
popupHeight="600px"
/>Auto-Open Chat on Page Load
<ChatbotWidget
aiName="Assistant"
apiEndpoint="/api/chatbot"
defaultOpen={true}
showOverlay={true}
/>No Animations (Instant Open/Close)
<ChatbotWidget
aiName="Quick Chat"
apiEndpoint="/api/chatbot"
enableAnimation={false}
/>With Open/Close Callbacks
<ChatbotWidget
aiName="Tracked Chat"
apiEndpoint="/api/chatbot"
onOpen={() => {
console.log('Chat opened');
// Track analytics, show welcome message, etc.
}}
onClose={() => {
console.log('Chat closed');
// Save state, track session duration, etc.
}}
/>🔌 Backend API Integration
Default Behavior (GET method)
<ChatbotWidget apiEndpoint="/api/chatbot" />By default, the widget sends GET requests with automatically constructed query parameters:
GET /api/chatbot?message=Hello&sessionId=abc123Key Features:
- ✅ Automatic query parameter construction
- ✅ Proper URL encoding with
encodeURIComponent() - ✅ Handles special characters, spaces, and unicode
- ✅ No manual URL building required
Example requests:
User message: "hello"
→ GET /api/chatbot?message=hello&sessionId=abc123
User message: "What's the weather?"
→ GET /api/chatbot?message=What%27s%20the%20weather%3F&sessionId=abc123
User message: "Tell me about AI 🤖"
→ GET /api/chatbot?message=Tell%20me%20about%20AI%20%F0%9F%A4%96&sessionId=abc123Server-side examples:
// Express.js
app.get('/api/chatbot', (req, res) => {
const { message, sessionId } = req.query;
res.json({ reply: `You said: ${message}` });
});
// Next.js API Route
export default function handler(req, res) {
const { message, sessionId } = req.query;
res.json({ reply: `You said: ${message}` });
}POST Method
<ChatbotWidget
apiEndpoint="/api/chatbot"
apiMethod="POST"
/>Sends POST requests with JSON body:
// Request
{
"message": "User's question here",
"sessionId": "abc123"
}
// Response
{
"reply": "Bot's response here"
}Custom API Request Builder (Full Control)
<ChatbotWidget
apiRequestBuilder={(message, sessionId) => ({
url: '/api/custom',
options: {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_TOKEN',
'Content-Type': 'application/json'
},
body: JSON.stringify({
query: message,
userId: sessionId,
context: 'additional-data'
})
}
})}
/>Custom API Response Format
If your API returns a different response format (e.g., Answer instead of reply), use apiResponseTransformer:
<ChatbotWidget
apiRequestBuilder={(message, sessionId) => ({
url: 'https://your-api.com/chat',
options: {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: message,
conversation_id: sessionId
})
}
})}
apiResponseTransformer={(data) => {
// Your API returns: { "Answer": "...", "conversation_id": "..." }
return data.Answer || "Sorry, I couldn't understand that.";
}}
/>Example API Response Formats:
// Standard format (default - no transformer needed)
{ "reply": "Bot response here" }
// Custom format 1 - use transformer
{ "Answer": "Bot response here", "conversation_id": "123" }
// Custom format 2 - use transformer
{ "response": { "text": "Bot response here" }, "status": "success" }
// Transformer for format 2:
apiResponseTransformer={(data) => data.response?.text || "Error"}Example Express.js Backend (POST)
app.post('/api/chatbot', async (req, res) => {
const { message, sessionId } = req.body;
try {
// Process with your AI service (OpenAI, etc.)
const botReply = await processWithAI(message, sessionId);
res.json({ reply: botReply });
} catch (error) {
res.status(500).json({
reply: "Sorry, I'm having trouble right now. Please try again."
});
}
});Example Express.js Backend (GET)
app.get('/api/chatbot', async (req, res) => {
const { message, sessionId } = req.query;
try {
const botReply = await processWithAI(message, sessionId);
res.json({ reply: botReply });
} catch (error) {
res.status(500).json({
reply: "Sorry, I'm having trouble right now. Please try again."
});
}
});🎨 Message Formatting
The chatbot supports basic message formatting for bot responses:
- Bold text: Use
**text**for bold formatting - Line breaks: Use
\nfor line breaks - Lists: Natural list formatting with line breaks
Example bot response:
**Welcome!** Here are some options:
1. Check your account
2. View recent orders
3. Contact support
How can I help you today?🛠️ Troubleshooting
Common Issues
Component not rendering?
- Check that all peer dependencies are installed
API calls failing?
- Verify your
apiEndpointis correct - Check network tab in browser dev tools
- Ensure your backend returns the expected JSON format
Styling issues?
- Check for CSS conflicts with existing styles
📱 Responsive Design
The chatbot is fully responsive and will adapt to different screen sizes:
- Desktop: 380px width with full features
- Mobile: Adjusts to 90% viewport width
- The launcher button remains accessible on all devices
🤝 Contributing
We welcome contributions! Please feel free to submit issues, feature requests, or pull requests.
👩💻 Author
Nneka Ezema
- Email: [email protected]
📄 License
MIT License - feel free to use in your projects!
📞 Support
Having issues? Please check the troubleshooting section above or contact:
- Email: [email protected]
- Issues: Open an issue on our GitHub repository
Made with ❤️ by Nneka Ezema for the React community
