@snap-agent/analytics 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +465 -0
- package/dist/index.d.mts +625 -0
- package/dist/index.d.ts +625 -0
- package/dist/index.js +1182 -0
- package/dist/index.mjs +1143 -0
- package/package.json +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 ViloTech
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
# @snap-agent/analytics
|
|
2
|
+
|
|
3
|
+
Comprehensive analytics plugin for SnapAgent SDK - Track performance, RAG, cost, conversation, and error metrics.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
**5 Metric Categories:**
|
|
8
|
+
1. **Performance** - Latency, timing breakdown, percentiles (P50, P95, P99)
|
|
9
|
+
2. **RAG** - Retrieval stats, cache rates, similarity scores
|
|
10
|
+
3. **Cost & Tokens** - Usage tracking, cost calculation by model
|
|
11
|
+
4. **Conversation** - Engagement, session quality, abandonment
|
|
12
|
+
5. **Errors** - Error rates, component breakdown, reliability
|
|
13
|
+
|
|
14
|
+
- **Real-time Tracking** - Event callbacks for live dashboards
|
|
15
|
+
- **Time Series** - Historical data with grouping (hour/day/week)
|
|
16
|
+
- **Cost Calculation** - Pre-configured pricing for major models
|
|
17
|
+
- **Auto-Cleanup** - Configurable data retention
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install @snap-agent/analytics @snap-agent/core
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Quick Start
|
|
26
|
+
|
|
27
|
+
```typescript
|
|
28
|
+
import { createClient, MemoryStorage } from '@snap-agent/core';
|
|
29
|
+
import { SnapAgentAnalytics } from '@snap-agent/analytics';
|
|
30
|
+
|
|
31
|
+
const analytics = new SnapAgentAnalytics({
|
|
32
|
+
// All categories enabled by default
|
|
33
|
+
enablePerformance: true,
|
|
34
|
+
enableRAG: true,
|
|
35
|
+
enableCost: true,
|
|
36
|
+
enableConversation: true,
|
|
37
|
+
enableErrors: true,
|
|
38
|
+
|
|
39
|
+
// Real-time event handler
|
|
40
|
+
onMetric: (event) => {
|
|
41
|
+
console.log(`[${event.type}]`, event.data);
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const client = createClient({
|
|
46
|
+
storage: new MemoryStorage(),
|
|
47
|
+
providers: {
|
|
48
|
+
openai: { apiKey: process.env.OPENAI_API_KEY! },
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const agent = await client.createAgent({
|
|
53
|
+
name: 'Analytics Demo',
|
|
54
|
+
instructions: 'You are helpful.',
|
|
55
|
+
model: 'gpt-4o',
|
|
56
|
+
userId: 'user-123',
|
|
57
|
+
plugins: [analytics],
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
// Use the agent normally...
|
|
61
|
+
// Analytics are collected automatically
|
|
62
|
+
|
|
63
|
+
// Get metrics
|
|
64
|
+
const metrics = await analytics.getMetrics({
|
|
65
|
+
agentId: agent.id,
|
|
66
|
+
startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // Last 7 days
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
console.log('Performance:', metrics.performance);
|
|
70
|
+
console.log('RAG:', metrics.rag);
|
|
71
|
+
console.log('Cost:', metrics.cost);
|
|
72
|
+
console.log('Conversation:', metrics.conversation);
|
|
73
|
+
console.log('Errors:', metrics.errors);
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Configuration
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
const analytics = new SnapAgentAnalytics({
|
|
80
|
+
// Enable/disable categories
|
|
81
|
+
enablePerformance: true,
|
|
82
|
+
enableRAG: true,
|
|
83
|
+
enableCost: true,
|
|
84
|
+
enableConversation: true,
|
|
85
|
+
enableErrors: true,
|
|
86
|
+
|
|
87
|
+
// Custom model costs (per 1K tokens)
|
|
88
|
+
modelCosts: {
|
|
89
|
+
'my-custom-model': { input: 0.001, output: 0.002 },
|
|
90
|
+
},
|
|
91
|
+
|
|
92
|
+
// Embedding cost (per 1K tokens)
|
|
93
|
+
embeddingCost: 0.0001,
|
|
94
|
+
|
|
95
|
+
// Data retention (days, 0 = forever)
|
|
96
|
+
retentionDays: 30,
|
|
97
|
+
|
|
98
|
+
// Real-time callback
|
|
99
|
+
onMetric: (event) => {
|
|
100
|
+
// Send to your monitoring system
|
|
101
|
+
sendToDataDog(event);
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Metric Categories
|
|
107
|
+
|
|
108
|
+
### 1. Performance Metrics
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
const perf = analytics.getPerformanceMetrics({ agentId: 'agent-123' });
|
|
112
|
+
|
|
113
|
+
// Returns:
|
|
114
|
+
{
|
|
115
|
+
totalRequests: 1500,
|
|
116
|
+
avgLatency: 450, // ms
|
|
117
|
+
p50Latency: 380,
|
|
118
|
+
p95Latency: 850,
|
|
119
|
+
p99Latency: 1200,
|
|
120
|
+
minLatency: 120,
|
|
121
|
+
maxLatency: 5000,
|
|
122
|
+
|
|
123
|
+
// Component breakdown
|
|
124
|
+
avgLLMTime: 350,
|
|
125
|
+
avgRAGTime: 80,
|
|
126
|
+
avgPluginTime: 15,
|
|
127
|
+
avgDbTime: 5,
|
|
128
|
+
|
|
129
|
+
// Streaming
|
|
130
|
+
avgTimeToFirstToken: 150,
|
|
131
|
+
avgTimeToLastToken: 420,
|
|
132
|
+
|
|
133
|
+
// Distribution
|
|
134
|
+
latencyDistribution: {
|
|
135
|
+
under100ms: 50,
|
|
136
|
+
under500ms: 1200,
|
|
137
|
+
under1s: 200,
|
|
138
|
+
under5s: 45,
|
|
139
|
+
over5s: 5
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### 2. RAG Metrics
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
const rag = analytics.getRAGMetrics({ agentId: 'agent-123' });
|
|
148
|
+
|
|
149
|
+
// Returns:
|
|
150
|
+
{
|
|
151
|
+
totalQueries: 800,
|
|
152
|
+
avgDocumentsRetrieved: 4.2,
|
|
153
|
+
avgVectorSearchTime: 45, // ms
|
|
154
|
+
avgEmbeddingTime: 30,
|
|
155
|
+
cacheHitRate: 0.72, // 72%
|
|
156
|
+
cacheMissRate: 0.28,
|
|
157
|
+
avgSimilarityScore: 0.85,
|
|
158
|
+
avgRerankTime: 25,
|
|
159
|
+
avgContextLength: 2500, // chars
|
|
160
|
+
avgContextTokens: 650,
|
|
161
|
+
avgSourcesCount: 3.8,
|
|
162
|
+
retrievalSuccessRate: 0.95 // 95%
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### 3. Cost & Token Metrics
|
|
167
|
+
|
|
168
|
+
```typescript
|
|
169
|
+
const cost = analytics.getCostMetrics({ agentId: 'agent-123' });
|
|
170
|
+
|
|
171
|
+
// Returns:
|
|
172
|
+
{
|
|
173
|
+
totalCost: 45.67, // USD
|
|
174
|
+
totalTokens: 2500000,
|
|
175
|
+
totalPromptTokens: 1800000,
|
|
176
|
+
totalCompletionTokens: 700000,
|
|
177
|
+
avgTokensPerRequest: 1667,
|
|
178
|
+
avgCostPerRequest: 0.03,
|
|
179
|
+
tokenEfficiency: 0.39, // output/input ratio
|
|
180
|
+
|
|
181
|
+
// Breakdowns
|
|
182
|
+
costByModel: {
|
|
183
|
+
'gpt-4o': 35.50,
|
|
184
|
+
'gpt-4o-mini': 10.17
|
|
185
|
+
},
|
|
186
|
+
costByAgent: {
|
|
187
|
+
'agent-123': 45.67
|
|
188
|
+
},
|
|
189
|
+
tokensByModel: {
|
|
190
|
+
'gpt-4o': 1800000,
|
|
191
|
+
'gpt-4o-mini': 700000
|
|
192
|
+
},
|
|
193
|
+
|
|
194
|
+
// Embeddings
|
|
195
|
+
totalEmbeddingTokens: 500000,
|
|
196
|
+
totalEmbeddingCost: 0.05,
|
|
197
|
+
|
|
198
|
+
// Time-based
|
|
199
|
+
dailyCosts: {
|
|
200
|
+
'2024-01-15': 5.20,
|
|
201
|
+
'2024-01-16': 6.10,
|
|
202
|
+
// ...
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### 4. Conversation Metrics
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
const conv = analytics.getConversationMetrics({ agentId: 'agent-123' });
|
|
211
|
+
|
|
212
|
+
// Returns:
|
|
213
|
+
{
|
|
214
|
+
totalThreads: 450,
|
|
215
|
+
totalMessages: 3200,
|
|
216
|
+
avgMessagesPerThread: 7.1,
|
|
217
|
+
avgThreadDuration: 180000, // ms (~3 min)
|
|
218
|
+
avgSessionLength: 180000,
|
|
219
|
+
userReturnRate: 0.65, // 65% of users come back
|
|
220
|
+
threadAbandonmentRate: 0.12, // 12% abandon after 1 message
|
|
221
|
+
|
|
222
|
+
// Message characteristics
|
|
223
|
+
avgInputLength: 125, // chars
|
|
224
|
+
avgOutputLength: 450,
|
|
225
|
+
inputLengthDistribution: {
|
|
226
|
+
short: 800, // < 50 chars
|
|
227
|
+
medium: 1500, // 50-200 chars
|
|
228
|
+
long: 700, // 200-500 chars
|
|
229
|
+
veryLong: 200 // > 500 chars
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### 5. Error Metrics
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
const errors = analytics.getErrorMetrics({ agentId: 'agent-123' });
|
|
238
|
+
|
|
239
|
+
// Returns:
|
|
240
|
+
{
|
|
241
|
+
totalErrors: 45,
|
|
242
|
+
errorRate: 0.03, // 3%
|
|
243
|
+
|
|
244
|
+
// By type
|
|
245
|
+
errorsByType: {
|
|
246
|
+
'rate_limit': 20,
|
|
247
|
+
'timeout': 15,
|
|
248
|
+
'api_error': 10
|
|
249
|
+
},
|
|
250
|
+
|
|
251
|
+
// By component
|
|
252
|
+
llmErrors: 30,
|
|
253
|
+
ragErrors: 5,
|
|
254
|
+
pluginErrors: 5,
|
|
255
|
+
dbErrors: 3,
|
|
256
|
+
networkErrors: 2,
|
|
257
|
+
timeoutErrors: 15,
|
|
258
|
+
rateLimitHits: 20,
|
|
259
|
+
|
|
260
|
+
// Reliability
|
|
261
|
+
successRate: 0.97,
|
|
262
|
+
retryCount: 50,
|
|
263
|
+
fallbackUsage: 5,
|
|
264
|
+
|
|
265
|
+
// Recent errors
|
|
266
|
+
recentErrors: [
|
|
267
|
+
{ timestamp: Date, type: 'rate_limit', message: '...', agentId: '...' },
|
|
268
|
+
// ...
|
|
269
|
+
]
|
|
270
|
+
}
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
## Time Series Data
|
|
274
|
+
|
|
275
|
+
```typescript
|
|
276
|
+
// Get latency over time
|
|
277
|
+
const latencySeries = analytics.getTimeSeries('latency', {
|
|
278
|
+
agentId: 'agent-123',
|
|
279
|
+
startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
|
|
280
|
+
groupBy: 'day',
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
// Returns:
|
|
284
|
+
[
|
|
285
|
+
{ timestamp: Date, value: 450, metadata: { count: 200 } },
|
|
286
|
+
{ timestamp: Date, value: 420, metadata: { count: 185 } },
|
|
287
|
+
// ...
|
|
288
|
+
]
|
|
289
|
+
|
|
290
|
+
// Available metrics: 'latency' | 'tokens' | 'cost' | 'errors' | 'requests'
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
## Extended Tracking
|
|
294
|
+
|
|
295
|
+
For detailed metrics, use the extended tracking methods:
|
|
296
|
+
|
|
297
|
+
```typescript
|
|
298
|
+
// Track request with full context
|
|
299
|
+
await analytics.trackRequestExtended({
|
|
300
|
+
agentId: 'agent-123',
|
|
301
|
+
threadId: 'thread-456',
|
|
302
|
+
userId: 'user-789',
|
|
303
|
+
organizationId: 'org-abc',
|
|
304
|
+
message: 'User message',
|
|
305
|
+
messageLength: 50,
|
|
306
|
+
timestamp: new Date(),
|
|
307
|
+
model: 'gpt-4o',
|
|
308
|
+
provider: 'openai',
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
// Track response with all metrics
|
|
312
|
+
await analytics.trackResponseExtended({
|
|
313
|
+
agentId: 'agent-123',
|
|
314
|
+
threadId: 'thread-456',
|
|
315
|
+
userId: 'user-789',
|
|
316
|
+
response: 'Assistant response',
|
|
317
|
+
responseLength: 200,
|
|
318
|
+
timestamp: new Date(),
|
|
319
|
+
|
|
320
|
+
// Performance timings
|
|
321
|
+
timings: {
|
|
322
|
+
total: 450,
|
|
323
|
+
llmApiTime: 350,
|
|
324
|
+
ragRetrievalTime: 80,
|
|
325
|
+
pluginExecutionTime: 15,
|
|
326
|
+
dbQueryTime: 5,
|
|
327
|
+
timeToFirstToken: 150,
|
|
328
|
+
timeToLastToken: 420,
|
|
329
|
+
},
|
|
330
|
+
|
|
331
|
+
// Token usage
|
|
332
|
+
tokens: {
|
|
333
|
+
promptTokens: 500,
|
|
334
|
+
completionTokens: 150,
|
|
335
|
+
totalTokens: 650,
|
|
336
|
+
},
|
|
337
|
+
|
|
338
|
+
// RAG metrics (if enabled)
|
|
339
|
+
rag: {
|
|
340
|
+
enabled: true,
|
|
341
|
+
documentsRetrieved: 5,
|
|
342
|
+
vectorSearchTime: 45,
|
|
343
|
+
embeddingTime: 30,
|
|
344
|
+
cacheHit: true,
|
|
345
|
+
avgSimilarityScore: 0.85,
|
|
346
|
+
contextLength: 2500,
|
|
347
|
+
contextTokens: 600,
|
|
348
|
+
sourcesCount: 4,
|
|
349
|
+
},
|
|
350
|
+
|
|
351
|
+
// Status
|
|
352
|
+
success: true,
|
|
353
|
+
model: 'gpt-4o',
|
|
354
|
+
provider: 'openai',
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
// Track errors
|
|
358
|
+
await analytics.trackError({
|
|
359
|
+
agentId: 'agent-123',
|
|
360
|
+
threadId: 'thread-456',
|
|
361
|
+
timestamp: new Date(),
|
|
362
|
+
errorType: 'rate_limit',
|
|
363
|
+
errorMessage: 'Rate limit exceeded',
|
|
364
|
+
component: 'llm',
|
|
365
|
+
});
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
## Pre-configured Model Costs
|
|
369
|
+
|
|
370
|
+
The plugin comes with pre-configured costs for major models:
|
|
371
|
+
|
|
372
|
+
| Model | Input (per 1K) | Output (per 1K) |
|
|
373
|
+
|-------|----------------|-----------------|
|
|
374
|
+
| gpt-4o | $0.005 | $0.015 |
|
|
375
|
+
| gpt-4o-mini | $0.00015 | $0.0006 |
|
|
376
|
+
| gpt-4-turbo | $0.01 | $0.03 |
|
|
377
|
+
| gpt-4 | $0.03 | $0.06 |
|
|
378
|
+
| gpt-3.5-turbo | $0.0005 | $0.0015 |
|
|
379
|
+
| claude-3-5-sonnet | $0.003 | $0.015 |
|
|
380
|
+
| claude-3-opus | $0.015 | $0.075 |
|
|
381
|
+
| claude-3-haiku | $0.00025 | $0.00125 |
|
|
382
|
+
| gemini-1.5-pro | $0.00125 | $0.005 |
|
|
383
|
+
| gemini-1.5-flash | $0.000075 | $0.0003 |
|
|
384
|
+
|
|
385
|
+
Add custom models via config:
|
|
386
|
+
```typescript
|
|
387
|
+
new SnapAgentAnalytics({
|
|
388
|
+
modelCosts: {
|
|
389
|
+
'my-custom-model': { input: 0.001, output: 0.002 },
|
|
390
|
+
},
|
|
391
|
+
});
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
## Export & Utility
|
|
395
|
+
|
|
396
|
+
```typescript
|
|
397
|
+
// Get raw data for export
|
|
398
|
+
const data = analytics.exportData();
|
|
399
|
+
// { requests: [...], responses: [...], errors: [...] }
|
|
400
|
+
|
|
401
|
+
// Get summary
|
|
402
|
+
const summary = analytics.getSummary();
|
|
403
|
+
// { totalRequests: 1500, totalErrors: 45, ... }
|
|
404
|
+
|
|
405
|
+
// Clear all data
|
|
406
|
+
analytics.clear();
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
## Integration Examples
|
|
410
|
+
|
|
411
|
+
### Send to DataDog
|
|
412
|
+
|
|
413
|
+
```typescript
|
|
414
|
+
import { datadogLogs } from '@datadog/browser-logs';
|
|
415
|
+
|
|
416
|
+
new SnapAgentAnalytics({
|
|
417
|
+
onMetric: (event) => {
|
|
418
|
+
datadogLogs.logger.info('snap-agent.metric', {
|
|
419
|
+
type: event.type,
|
|
420
|
+
...event.data,
|
|
421
|
+
});
|
|
422
|
+
},
|
|
423
|
+
});
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
### Send to PostHog
|
|
427
|
+
|
|
428
|
+
```typescript
|
|
429
|
+
import posthog from 'posthog-js';
|
|
430
|
+
|
|
431
|
+
new SnapAgentAnalytics({
|
|
432
|
+
onMetric: (event) => {
|
|
433
|
+
posthog.capture(`snapagent_${event.type}`, event.data);
|
|
434
|
+
},
|
|
435
|
+
});
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
### Custom Dashboard
|
|
439
|
+
|
|
440
|
+
```typescript
|
|
441
|
+
import express from 'express';
|
|
442
|
+
|
|
443
|
+
const app = express();
|
|
444
|
+
const analytics = new SnapAgentAnalytics();
|
|
445
|
+
|
|
446
|
+
app.get('/metrics', async (req, res) => {
|
|
447
|
+
const metrics = await analytics.getMetrics({
|
|
448
|
+
startDate: new Date(Date.now() - 24 * 60 * 60 * 1000),
|
|
449
|
+
});
|
|
450
|
+
res.json(metrics);
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
app.get('/metrics/timeseries/:metric', (req, res) => {
|
|
454
|
+
const series = analytics.getTimeSeries(
|
|
455
|
+
req.params.metric as any,
|
|
456
|
+
{ groupBy: 'hour' }
|
|
457
|
+
);
|
|
458
|
+
res.json(series);
|
|
459
|
+
});
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
## License
|
|
463
|
+
|
|
464
|
+
MIT © ViloTech
|
|
465
|
+
|