@ariaflowagents/analytics-sdk
v1.0.0
Published
Type-safe SDK for sending analytics events to AriaFlow Analytics Platform
Maintainers
Readme
@ariaflowagents/analytics-sdk
Type-safe SDK for sending analytics events to AriaFlow Analytics Platform.
Installation
npm install @ariaflowagents/analytics-sdk
# or
bun add @ariaflowagents/analytics-sdk
# or
yarn add @ariaflowagents/analytics-sdkQuick Start
1. Initialize the Client
import { createAnalyticsClient } from '@ariaflowagents/analytics-sdk';
const analytics = createAnalyticsClient({
apiKey: 'your-api-key',
workspaceId: 'your-workspace-id',
endpoint: 'https://analytics.ariaflow.dev/api/v1', // optional
flushInterval: 5000, // optional, default: 5000ms
maxBatchSize: 20, // optional, default: 20
enableDebug: true, // optional, default: false
});2. Track Events
// Track a single event
await analytics.track({
sessionId: 'session-123',
agentId: 'hospital-agent',
workspaceId: 'workspace-456',
type: 'conversation.started',
data: { channel: 'web' }
});
// Track batch events
await analytics.trackBatch([
{ sessionId: 'session-123', agentId: 'hospital-agent', workspaceId: 'workspace-456', type: 'node.entered', data: { nodeName: 'triage' } },
{ sessionId: 'session-123', agentId: 'hospital-agent', workspaceId: 'workspace-456', type: 'tool.called', data: { toolName: 'create_booking' } },
]);3. Track Voice Calls
// Start a voice call
await analytics.trackVoiceCall({
sessionId: 'call-123',
workspaceId: 'workspace-456',
agentId: 'voice-agent',
userName: 'John Doe',
startedAt: new Date(),
});
// Update call metrics during the call
await analytics.updateVoiceCall('call-123', {
interruptions: 2,
userTurns: 5,
agentTurns: 4,
currentNode: 'booking_flow',
});
// End the call
await analytics.updateVoiceCall('call-123', {
endedAt: new Date(),
durationSeconds: 180,
outcome: 'booking_completed',
ttfMs: 850,
});4. Set Context
// Set global context (applied to all events)
analytics.setContext({
userId: 'user-789',
conversationId: 'conv-abc',
agentId: 'hospital-agent',
});
// Identify user
analytics.identify('user-789', {
name: 'John Doe',
email: '[email protected]',
plan: 'pro',
});5. Flush Events
// Manually flush pending events
await analytics.flush();React Integration
AnalyticsProvider
import { AnalyticsProvider } from '@ariaflowagents/analytics-sdk/react';
function App() {
return (
<AnalyticsProvider config={{
apiKey: process.env.ANALYTICS_API_KEY!,
workspaceId: 'workspace-456',
}}>
<YourApp />
</AnalyticsProvider>
);
}useAnalytics Hook
import { useAnalytics } from '@ariaflowagents/analytics-sdk/react';
function MyComponent() {
const { track, setContext, identify } = useAnalytics();
const handleClick = async () => {
await track({
type: 'custom',
sessionId: 'session-123',
agentId: 'hospital-agent',
workspaceId: 'workspace-456',
data: { button: 'submit_form' }
});
};
return <button onClick={handleClick}>Submit</button>;
}usePageView Hook
import { usePageView } from '@ariaflowagents/analytics-sdk/react';
function DashboardPage() {
usePageView('dashboard', { section: 'analytics' });
return <div>Dashboard</div>;
}useVoiceCallTracker Hook
import { useVoiceCallTracker } from '@ariaflowagents/analytics-sdk/react';
function VoiceCallComponent({ sessionId, workspaceId }) {
const { startCall, endCall, trackInterruption, trackUserSpeech, trackAgentSpeech } =
useVoiceCallTracker(sessionId, workspaceId);
useEffect(() => {
startCall('voice-agent');
return () => {
endCall('completed');
};
}, []);
return (
<div>
<button onClick={trackInterruption}>User Interrupted</button>
</div>
);
}Event Types
| Event Type | Description |
|------------|-------------|
| conversation.started | Conversation began |
| conversation.ended | Conversation ended |
| node.entered | Flow node entered |
| node.exited | Flow node exited |
| tool.called | Tool execution started |
| tool.completed | Tool finished successfully |
| tool.error | Tool execution failed |
| booking.completed | Booking action completed |
| handoff.initiated | Agent handoff triggered |
| emergency.detected | Emergency condition detected |
| call.started | Voice call started |
| call.ended | Voice call ended |
| user.spoke | User spoke (voice) |
| agent.spoke | Agent spoke (voice) |
| user.interrupted | User interrupted agent |
| silence.detected | Silence detected |
| latency.stt | Speech-to-text latency |
| latency.ttf | Time to first response |
| latency.e2e | End-to-end latency |
| latency.tts | Text-to-speech latency |
| error.occurred | Error occurred |
| custom | Custom event |
Integration with AriaFlow Runtime
import { Runtime, createTelemetryHooks } from '@ariaflowagents/core';
import { createAnalyticsClient } from '@ariaflowagents/analytics-sdk';
const analytics = createAnalyticsClient({
apiKey: process.env.ANALYTICS_API_KEY!,
workspaceId: 'workspace-456',
});
// Create telemetry hooks that forward events to analytics
const telemetryHooks = {
onAgentStart: async (context, agentId) => {
await analytics.track({
sessionId: context.session.id,
agentId,
workspaceId: 'workspace-456',
type: 'conversation.started',
data: {}
});
},
onToolCall: async (context, call) => {
await analytics.track({
sessionId: context.session.id,
agentId: context.agentId,
workspaceId: 'workspace-456',
type: 'tool.called',
data: {
toolName: call.toolName,
toolCallId: call.toolCallId,
}
});
},
onToolResult: async (context, call) => {
await analytics.track({
sessionId: context.session.id,
agentId: context.agentId,
workspaceId: 'workspace-456',
type: 'tool.completed',
data: {
toolName: call.toolName,
success: call.success,
durationMs: call.durationMs,
}
});
},
onHandoff: async (context, from, to, reason) => {
await analytics.track({
sessionId: context.session.id,
agentId: from,
workspaceId: 'workspace-456',
type: 'handoff.initiated',
data: { from, to, reason }
});
},
};
const runtime = new Runtime({
agents: [...],
hooks: telemetryHooks,
});API Reference
createAnalyticsClient(config: AnalyticsConfig): AnalyticsClient
Creates a new analytics client instance.
AnalyticsClient Methods
| Method | Description |
|--------|-------------|
| track(event) | Track a single event |
| trackBatch(events) | Track multiple events |
| trackVoiceCall(data) | Create a voice call record |
| updateVoiceCall(sessionId, data) | Update voice call metrics |
| flush() | Flush pending events |
| setContext(context) | Set global context |
| identify(userId, traits?) | Identify user |
AnalyticsConfig
| Option | Type | Required | Default |
|--------|------|----------|---------|
| apiKey | string | ✅ | - |
| workspaceId | string | ✅ | - |
| endpoint | string | ❌ | https://analytics.ariaflow.dev/api/v1 |
| flushInterval | number | ❌ | 5000 (ms) |
| maxBatchSize | number | ❌ | 20 |
| enableDebug | boolean | ❌ | false |
Best Practices
- Initialize Once: Create a single client instance and reuse it
- Batch Events: The SDK automatically batches events for performance
- Context First: Set context and user identity early in the session
- Flush on Exit: Call
flush()before page unload or app shutdown - Error Handling: Wrap calls in try-catch for production use
License
MIT
