-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathanalytics-usage.ts
More file actions
93 lines (80 loc) · 2.6 KB
/
Copy pathanalytics-usage.ts
File metadata and controls
93 lines (80 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import {
Analytics,
eq,
gt,
and,
asc,
desc,
sum,
count,
} from "@scrawn/analytics";
import { biller } from "./scrawn/biller.ts";
import { config } from "dotenv";
config({ path: ".env.local" });
async function main() {
const analytics = new Analytics(biller);
const { basicUsage, aiToken, payment } = analytics.query;
const { users, tags, sessions, expressions, metadata } = analytics.data;
// ── Event Queries ──
// List recent SDK call events
const recentSdkCalls = await basicUsage
.where(eq(basicUsage.fields.basicUsageType, "RAW"))
.orderBy(desc(basicUsage.fields.reportedTimestamp))
.limit(10)
.execute();
console.log("Recent SDK calls:", JSON.stringify(recentSdkCalls, null, 2));
// Middleware events with high debit
const expensiveMiddleware = await basicUsage
.where(
and(
eq(basicUsage.fields.basicUsageType, "MIDDLEWARE_CALL"),
gt(basicUsage.fields.debitAmount, 100)
)
)
.orderBy(desc(basicUsage.fields.debitAmount))
.limit(5)
.execute();
console.log(
"Expensive middleware calls:",
JSON.stringify(expensiveMiddleware, null, 2)
);
// AI token usage for a specific model
const gpt4Usage = await aiToken
.where(eq(aiToken.fields.model, "gpt-4"))
.orderBy(desc(aiToken.fields.reportedTimestamp))
.limit(10)
.execute();
console.log("GPT-4 token usage:", JSON.stringify(gpt4Usage, null, 2));
// Total debit per user (aggregation)
const totalByUser = await basicUsage
.where(gt(basicUsage.fields.debitAmount, 0))
.aggregate(sum(basicUsage.fields.debitAmount))
.groupBy(basicUsage.fields.userId)
.limit(10)
.execute();
console.log("Total debit by user:", JSON.stringify(totalByUser, null, 2));
// Count of payment events
const paymentCount = await payment.aggregate(count()).execute();
console.log("Payment events:", JSON.stringify(paymentCount, null, 2));
// ── Data Queries ──
// List production users
const prodUsers = await users
.where(and(eq(users.fields.mode, "production")))
.orderBy(asc(users.fields.id))
.limit(10)
.execute();
console.log("Production users:", JSON.stringify(prodUsers, null, 2));
// List all tags
const allTags = await tags.orderBy(asc(tags.fields.key)).limit(50).execute();
console.log("Tags:", JSON.stringify(allTags, null, 2));
// Unprocessed sessions
const unprocessedSessions = await sessions
.where(eq(sessions.fields.processed, "false"))
.limit(10)
.execute();
console.log(
"Unprocessed sessions:",
JSON.stringify(unprocessedSessions, null, 2)
);
}
main().catch(console.error);