Chat Widget Integration
Embed Datix xAgents's natural language query interface directly into your application.
🎯 Overview
The Chat Widget allows you to:
- Embed querying: Add AI-powered data insights to your app
- Customize appearance: Match your brand and design
- Control access: Secure with API keys and agent permissions
- Handle events: React to queries and results
📦 Installation
Option 1: CDN (Recommended)
<script src="https://cdn.datixlab.com/chat-widget.js"></script>
Option 2: NPM Package
npm install @datixxagents/chat-widget
import DatixxAgentsWidget from '@datixxagents/chat-widget';
Option 3: Self-Hosted
Download from the chat-widget/ folder in the repository.
🚀 Quick Start
Basic HTML Implementation
<!DOCTYPE html>
<html>
<head>
<title>My App with Datix xAgents</title>
</head>
<body>
<div id="datixxagents-widget"></div>
<script src="https://cdn.datixlab.com/chat-widget.js"></script>
<script>
DatixxAgentsWidget.init({
containerId: 'datixxagents-widget',
apiKey: 'your-api-key-here',
agentId: 'your-agent-id'
});
</script>
</body>
</html>
React Integration
import React, { useEffect, useRef } from 'react';
import DatixxAgentsWidget from '@datixxagents/chat-widget';
function DataInsights() {
const widgetRef = useRef(null);
useEffect(() => {
if (widgetRef.current) {
DatixxAgentsWidget.init({
containerId: 'datixxagents-widget',
apiKey: process.env.REACT_APP_DATIXXAGENTS_KEY,
agentId: 'agent-123',
theme: 'light'
});
}
return () => {
DatixxAgentsWidget.destroy();
};
}, []);
return <div id="datixxagents-widget" ref={widgetRef} />;
}
export default DataInsights;
Vue Integration
<template>
<div id="datixxagents-widget" ref="widget"></div>
</template>
<script>
import DatixxAgentsWidget from '@datixxagents/chat-widget';
export default {
name: 'DataInsights',
mounted() {
DatixxAgentsWidget.init({
containerId: 'datixxagents-widget',
apiKey: process.env.VUE_APP_DATIXXAGENTS_KEY,
agentId: 'agent-123',
});
},
beforeUnmount() {
DatixxAgentsWidget.destroy();
}
};
</script>
⚙️ Configuration Options
Required Parameters
{
containerId: 'datixxagents-widget', // DOM element ID
apiKey: 'your-api-key', // Your API key
agentId: 'agent-123' // Agent to use
}
Appearance Options
{
theme: 'light', // 'light' | 'dark' | 'auto'
primaryColor: '#5D87FF', // Brand color
height: '600px', // Widget height
width: '100%', // Widget width
borderRadius: '12px', // Corner radius
fontFamily: 'Inter, sans-serif', // Custom font
}
Behavior Options
{
placeholder: 'Ask a question...', // Input placeholder
welcomeMessage: 'Hi! Ask me anything about your data.',
showSuggestions: true, // Show follow-ups
enableExport: true, // Allow CSV export
enableSQL: false, // Show SQL toggle
maxQueries: 100, // Daily query limit
queryTimeout: 30000, // Timeout in ms
}
🎨 Customization
Custom Styling
DatixxAgentsWidget.init({
containerId: 'datixxagents-widget',
apiKey: 'your-api-key',
agentId: 'agent-123',
// Custom colors
primaryColor: '#0066FF',
backgroundColor: '#F5F5F5',
textColor: '#333333',
// Custom spacing
padding: '20px',
borderRadius: '16px',
// Custom font
fontFamily: 'Roboto, sans-serif',
fontSize: '14px'
});
CSS Override
/* Override widget styles */
#datixxagents-widget {
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
border: 1px solid #e0e0e0;
}
#datixxagents-widget .message {
font-size: 15px;
line-height: 1.6;
}
#datixxagents-widget .button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
📡 Event Handling
Available Events
DatixxAgentsWidget.init({
// ... config options ...
// Event handlers
onReady: () => {
console.log('Widget loaded');
},
onQuery: (question) => {
console.log('User asked:', question);
// Track analytics
},
onResult: (result) => {
console.log('Got result:', result);
// Display notification
},
onError: (error) => {
console.error('Error:', error);
// Show error message
},
onExport: (data, format) => {
console.log('User exported data as', format);
// Track export
}
});
Example: Google Analytics Tracking
DatixxAgentsWidget.init({
containerId: 'datixxagents-widget',
apiKey: 'your-api-key',
agentId: 'agent-123',
onQuery: (question) => {
gtag('event', 'datixxagents_query', {
'event_category': 'engagement',
'event_label': question
});
},
onResult: (result) => {
gtag('event', 'datixxagents_result', {
'event_category': 'engagement',
'event_label': 'success'
});
}
});
🔒 Security
API Key Management
Important
Never expose API keys in client-side code for public applications.
Secure Implementation (Recommended)
// Backend endpoint (Node.js/Express)
app.post('/api/datixxagents/query', async (req, res) => {
const { question } = req.body;
// Authenticate user first
if (!req.user) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Proxy to Datix xAgents
const response = await fetch('https://api.datixlab.com/query', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.DATIXXAGENTS_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
question,
agent_id: 'agent-123'
})
});
const data = await response.json();
res.json(data);
});
// Frontend widget config
DatixxAgentsWidget.init({
containerId: 'datixxagents-widget',
apiEndpoint: '/api/datixxagents/query', // Your backend proxy
// No API key needed in frontend
});
Row-Level Security
Pass user context to filter data:
DatixxAgentsWidget.init({
containerId: 'datixxagents-widget',
apiKey: 'your-api-key',
agentId: 'agent-123',
// User context for filtering
context: {
userId: currentUser.id,
companyId: currentUser.companyId,
role: currentUser.role
}
});
📊 Example Use Cases
1. SaaS Dashboard
// Embed in analytics dashboard
DatixxAgentsWidget.init({
containerId: 'analytics-widget',
apiKey: 'key',
agentId: 'analytics-agent',
theme: 'dark',
welcomeMessage: 'Ask questions about your metrics',
enableExport: true,
showSuggestions: true
});
2. Customer Support Portal
// Help customers query their own data
DatixxAgentsWidget.init({
containerId: 'support-widget',
apiKey: 'key',
agentId: 'customer-agent',
context: {
customerId: currentCustomer.id
},
placeholder: 'Ask about your orders, invoices, or account...'
});
3. Internal Admin Tool
// Power tool for admins
DatixxAgentsWidget.init({
containerId: 'admin-widget',
apiKey: 'key',
agentId: 'admin-agent',
enableSQL: true,
enableExport: true,
height: '800px'
});
🎓 Best Practices
✅ Proxy API Calls
Use backend to protect API keys
✅ Set Limits
Configure query limits per user
✅ Track Usage
Monitor with event handlers
✅ Error Handling
Implement graceful error messages
✅ Responsive Design
Test on mobile devices
✅ Loading States
Show progress indicators
🔧 API Methods
Initialize Widget
DatixxAgentsWidget.init(config)
Send Query Programmatically
DatixxAgentsWidget.query('Show me sales for Q4')
Clear Chat History
DatixxAgentsWidget.clear()
Destroy Widget
DatixxAgentsWidget.destroy()
Update Configuration
DatixxAgentsWidget.updateConfig({
theme: 'dark',
primaryColor: '#FF5722'
})