Skip to content

Analytics

ChatCops includes a lightweight analytics collector that tracks conversation metrics server-side.

chatcopsMiddleware({
provider: { type: 'claude', apiKey: '...' },
systemPrompt: '...',
analytics: true, // Enable analytics tracking
});

When analytics: true, the server automatically tracks:

EventWhen
conversation:startedNew conversation ID first seen
message:sentUser sends a message
message:receivedAI responds
lead:capturedLead capture tool fires
import { AnalyticsCollector } from '@chatcops/core/analytics';
const analytics = new AnalyticsCollector();
// Track custom events
analytics.track('custom:event', { key: 'value' });
// Get aggregated stats
const stats = analytics.getStats();
// {
// totalConversations: 150,
// totalMessages: 2340,
// leadsCaptured: 23,
// averageMessagesPerConversation: 15.6,
// eventCounts: { 'conversation:started': 150, ... }
// }
// Get raw events (optionally filter by type)
const allEvents = analytics.getEvents();
const leads = analytics.getEvents('lead:captured');
// Clear all events
analytics.clear();
interface AnalyticsStats {
totalConversations: number;
totalMessages: number;
leadsCaptured: number;
averageMessagesPerConversation: number;
eventCounts: Record<string, number>;
}
interface AnalyticsEvent {
type: string;
data?: Record<string, unknown>;
timestamp: number;
}

The built-in collector stores events in memory (max 1000 events). For production use, export events to your analytics platform:

const collector = new AnalyticsCollector();
// Periodically flush to your analytics service
setInterval(() => {
const events = collector.getEvents();
if (events.length > 0) {
sendToAnalytics(events);
collector.clear();
}
}, 60_000); // Every minute

Combine with widget events for full-stack analytics:

// Client-side
ChatCops.on('open', () => gtag('event', 'chat_opened'));
ChatCops.on('message', (m) => {
if (m.role === 'user') gtag('event', 'chat_message_sent');
});
// Server-side (automatic with analytics: true)
// conversation:started, message:sent, message:received, lead:captured