-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtest-ai-gateway-analytics.ts
More file actions
executable file
·1116 lines (1019 loc) · 36.7 KB
/
Copy pathtest-ai-gateway-analytics.ts
File metadata and controls
executable file
·1116 lines (1019 loc) · 36.7 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bun
/**
* Cloudflare AI Gateway Analytics Testing Script
*
* Tests the Cloudflare AI Gateway GraphQL Analytics API and displays comprehensive
* analytics data including costs, tokens, requests, errors, and response times.
*
* Usage:
* bun --env-file .dev.vars scripts/test-ai-gateway-analytics.ts
* bun --env-file .dev.vars scripts/test-ai-gateway-analytics.ts --user-id abc123
* bun --env-file .dev.vars scripts/test-ai-gateway-analytics.ts --chat-id xyz789
* bun --env-file .dev.vars scripts/test-ai-gateway-analytics.ts --days 7
* bun --env-file .dev.vars scripts/test-ai-gateway-analytics.ts --show-models --show-providers
* bun --env-file .dev.vars scripts/test-ai-gateway-analytics.ts --granularity minute --top-models 5
*/
// Types
interface AnalyticsResponse {
data: {
viewer: {
scope: Array<{
totalRequests: Array<{
count: number;
sum: {
cost: number;
cachedRequests: number;
erroredRequests: number;
uncachedTokensIn: number;
uncachedTokensOut: number;
cachedTokensIn: number;
cachedTokensOut: number;
};
}>;
lastRequest: Array<{
dimensions: {
ts: string;
};
}>;
latestRequests: Array<{
count: number;
dimensions: {
ts: string;
};
}>;
}>;
};
};
errors?: any[];
}
// Enhanced types for provider and model analytics
interface ProviderRequestAnalytics {
data: {
viewer: {
accounts: Array<{
data: Array<{
count: number;
dimensions: {
ts: string;
provider: string;
};
}>;
}>;
};
};
errors?: any[];
}
interface ModelTokenAnalytics {
data: {
viewer: {
accounts: Array<{
data: Array<{
count: number;
sum: {
uncachedTokensIn: number;
uncachedTokensOut: number;
cost: number;
};
dimensions: {
ts: string;
provider: string;
model: string;
};
}>;
}>;
};
};
errors?: any[];
}
// Provider summary data structure
interface ProviderSummary {
name: string;
totalRequests: number;
totalTokensIn: number;
totalTokensOut: number;
totalCost: number;
models: ModelSummary[];
}
// Model summary data structure
interface ModelSummary {
name: string;
provider: string;
requests: number;
tokensIn: number;
tokensOut: number;
cost: number;
firstSeen: string;
lastSeen: string;
}
// Enhanced query result types
interface QueryResult {
name: string;
responseTime: number;
data: AnalyticsResponse | ProviderRequestAnalytics | ModelTokenAnalytics | null;
error?: string;
}
// Configuration (will be updated from env vars)
let CONFIG = {
ACCOUNT_TAG: '',
GATEWAY: '',
GRAPHQL_ENDPOINT: 'https://api.cloudflare.com/client/v4/graphql',
IS_STAGING: false,
API_TOKEN: '',
};
// Parse AI Gateway URL to extract account ID and gateway name
function parseGatewayUrl(url: string): { accountId: string; gateway: string; isStaging: boolean } {
try {
const parsedUrl = new URL(url);
const isStaging = url.includes('staging');
// URL format: https://staging.gateway.ai.cfdata.org/v1/{account_id}/{gateway_name}
const pathParts = parsedUrl.pathname.split('/').filter(part => part);
if (pathParts.length >= 3 && pathParts[0] === 'v1') {
return {
accountId: pathParts[1],
gateway: pathParts[2],
isStaging
};
}
throw new Error('Invalid gateway URL format');
} catch (error) {
throw new Error(`Failed to parse gateway URL: ${error}`);
}
}
// Initialize configuration from environment variables
function initializeConfig(): void {
const {
CLOUDFLARE_ACCOUNT_ID,
CLOUDFLARE_AI_GATEWAY,
CLOUDFLARE_API_TOKEN,
CLOUDFLARE_AI_GATEWAY_TOKEN,
CLOUDFLARE_AI_GATEWAY_URL
} = process.env;
// If CLOUDFLARE_AI_GATEWAY_URL is set, parse it and use staging settings
if (CLOUDFLARE_AI_GATEWAY_URL) {
const { accountId, gateway, isStaging } = parseGatewayUrl(CLOUDFLARE_AI_GATEWAY_URL);
CONFIG.ACCOUNT_TAG = accountId;
CONFIG.GATEWAY = gateway;
CONFIG.IS_STAGING = isStaging;
if (isStaging) {
CONFIG.GRAPHQL_ENDPOINT = 'https://api.staging.cloudflare.com/client/v4/graphql';
CONFIG.API_TOKEN = CLOUDFLARE_AI_GATEWAY_TOKEN || '';
} else {
CONFIG.API_TOKEN = CLOUDFLARE_API_TOKEN || '';
}
} else {
// Use direct environment variables
CONFIG.ACCOUNT_TAG = CLOUDFLARE_ACCOUNT_ID || '';
CONFIG.GATEWAY = CLOUDFLARE_AI_GATEWAY || '';
CONFIG.API_TOKEN = CLOUDFLARE_API_TOKEN || '';
}
// Validate required configuration
if (!CONFIG.ACCOUNT_TAG || !CONFIG.GATEWAY || !CONFIG.API_TOKEN) {
console.error('❌ Missing required environment variables:');
if (!CONFIG.ACCOUNT_TAG) console.error(' - Account ID not found');
if (!CONFIG.GATEWAY) console.error(' - Gateway name not found');
if (!CONFIG.API_TOKEN) console.error(' - API token not found');
process.exit(1);
}
}
// GraphQL Queries
const QUERIES = {
totalGateway: (start: string, end: string) => ({
operationName: null,
variables: {
accountTag: CONFIG.ACCOUNT_TAG,
gateway: CONFIG.GATEWAY,
start,
end,
limit: 1
},
query: `{
viewer {
scope: accounts(filter: {accountTag: $accountTag}) {
latestRequests: aiGatewayRequestsAdaptiveGroups(limit: $limit, filter: {gateway: $gateway, datetimeHour_geq: $start, datetimeHour_leq: $end}) {
count
dimensions {
ts: datetimeHour
__typename
}
__typename
}
lastRequest: aiGatewayRequestsAdaptiveGroups(limit: 1, orderBy: [datetimeMinute_DESC], filter: {gateway: $gateway, datetimeHour_geq: $start, datetimeHour_leq: $end}) {
dimensions {
ts: datetimeMinute
__typename
}
__typename
}
totalRequests: aiGatewayRequestsAdaptiveGroups(limit: $limit, filter: {gateway: $gateway, datetimeHour_geq: $start, datetimeHour_leq: $end}) {
count
sum {
cost
cachedRequests
erroredRequests
uncachedTokensIn
uncachedTokensOut
cachedTokensIn
cachedTokensOut
__typename
}
__typename
}
__typename
}
__typename
}
}`
}),
// Provider-level request analytics with minute-level precision
providerRequests: (start: string, end: string, granularity: 'minute' | 'hour' = 'minute') => ({
operationName: 'GetAIRequests',
variables: {
accountTag: CONFIG.ACCOUNT_TAG,
gateway: CONFIG.GATEWAY,
start,
end,
limit: 10000,
orderBy: granularity === 'minute' ? 'datetimeMinute_ASC' : 'datetimeHour_ASC'
},
query: `query GetAIRequests($accountTag: string, $gateway: string, $start: string, $end: string, $limit: Int, $orderBy: [String!]) {
viewer {
accounts(filter: {accountTag: $accountTag}) {
data: aiGatewayRequestsAdaptiveGroups(
filter: {
gateway: $gateway,
metadataKeys_has: "userId",
error: 0,
${granularity === 'minute' ? 'datetimeMinute_geq: $start, datetimeMinute_leq: $end' : 'datetimeHour_geq: $start, datetimeHour_leq: $end'}
},
orderBy: [$orderBy],
limit: $limit
) {
count
dimensions {
ts: ${granularity === 'minute' ? 'datetimeMinute' : 'datetimeHour'}
provider
__typename
}
__typename
}
__typename
}
__typename
}
}`
}),
// Model-level token analytics with minute-level precision
modelTokens: (start: string, end: string, granularity: 'minute' | 'hour' = 'minute') => ({
operationName: 'GetAITokens',
variables: {
accountTag: CONFIG.ACCOUNT_TAG,
gateway: CONFIG.GATEWAY,
start,
end,
limit: 10000,
orderBy: granularity === 'minute' ? 'datetimeMinute_ASC' : 'datetimeHour_ASC'
},
query: `query GetAITokens($accountTag: string, $gateway: string, $start: string, $end: string, $limit: Int, $orderBy: [String!]) {
viewer {
accounts(filter: {accountTag: $accountTag}) {
data: aiGatewayRequestsAdaptiveGroups(
filter: {
gateway: $gateway,
metadataKeys_has: "userId",
error: 0,
${granularity === 'minute' ? 'datetimeMinute_geq: $start, datetimeMinute_leq: $end' : 'datetimeHour_geq: $start, datetimeHour_leq: $end'}
},
orderBy: [$orderBy],
limit: $limit
) {
count
sum {
uncachedTokensIn
uncachedTokensOut
cost
__typename
}
dimensions {
ts: ${granularity === 'minute' ? 'datetimeMinute' : 'datetimeHour'}
provider
model
__typename
}
__typename
}
__typename
}
__typename
}
}`
}),
// Chat-specific provider request analytics
chatProviderRequests: (start: string, end: string, chatId: string, granularity: 'minute' | 'hour' = 'minute') => ({
operationName: 'GetChatAIRequests',
variables: {
accountTag: CONFIG.ACCOUNT_TAG,
gateway: CONFIG.GATEWAY,
start,
end,
limit: 10000,
orderBy: granularity === 'minute' ? 'datetimeMinute_ASC' : 'datetimeHour_ASC'
},
query: `query GetChatAIRequests($accountTag: string, $gateway: string, $start: string, $end: string, $limit: Int, $orderBy: [String!]) {
viewer {
accounts(filter: {accountTag: $accountTag}) {
data: aiGatewayRequestsAdaptiveGroups(
filter: {
gateway: $gateway,
metadataValues_has: "${chatId}",
error: 0,
${granularity === 'minute' ? 'datetimeMinute_geq: $start, datetimeMinute_leq: $end' : 'datetimeHour_geq: $start, datetimeHour_leq: $end'}
},
orderBy: [$orderBy],
limit: $limit
) {
count
dimensions {
ts: ${granularity === 'minute' ? 'datetimeMinute' : 'datetimeHour'}
provider
__typename
}
__typename
}
__typename
}
__typename
}
}`
}),
// Chat-specific model token analytics
chatModelTokens: (start: string, end: string, chatId: string, granularity: 'minute' | 'hour' = 'minute') => ({
operationName: 'GetChatAITokens',
variables: {
accountTag: CONFIG.ACCOUNT_TAG,
gateway: CONFIG.GATEWAY,
start,
end,
limit: 10000,
orderBy: granularity === 'minute' ? 'datetimeMinute_ASC' : 'datetimeHour_ASC'
},
query: `query GetChatAITokens($accountTag: string, $gateway: string, $start: string, $end: string, $limit: Int, $orderBy: [String!]) {
viewer {
accounts(filter: {accountTag: $accountTag}) {
data: aiGatewayRequestsAdaptiveGroups(
filter: {
gateway: $gateway,
metadataValues_has: "${chatId}",
error: 0,
${granularity === 'minute' ? 'datetimeMinute_geq: $start, datetimeMinute_leq: $end' : 'datetimeHour_geq: $start, datetimeHour_leq: $end'}
},
orderBy: [$orderBy],
limit: $limit
) {
count
sum {
uncachedTokensIn
uncachedTokensOut
cost
__typename
}
dimensions {
ts: ${granularity === 'minute' ? 'datetimeMinute' : 'datetimeHour'}
provider
model
__typename
}
__typename
}
__typename
}
__typename
}
}`
}),
userFiltered: (start: string, end: string) => ({
operationName: null,
variables: {
accountTag: CONFIG.ACCOUNT_TAG,
gateway: CONFIG.GATEWAY,
start,
end,
limit: 1
},
query: `{
viewer {
scope: accounts(filter: {accountTag: $accountTag}) {
latestRequests: aiGatewayRequestsAdaptiveGroups(limit: $limit, filter: {gateway: $gateway, metadataKeys_has: "userId", datetimeHour_geq: $start, datetimeHour_leq: $end}) {
count
dimensions {
ts: datetimeHour
__typename
}
__typename
}
lastRequest: aiGatewayRequestsAdaptiveGroups(limit: 1, orderBy: [datetimeMinute_DESC], filter: {gateway: $gateway, metadataKeys_has: "userId", datetimeHour_geq: $start, datetimeHour_leq: $end}) {
dimensions {
ts: datetimeMinute
__typename
}
__typename
}
totalRequests: aiGatewayRequestsAdaptiveGroups(limit: $limit, filter: {gateway: $gateway, metadataKeys_has: "userId", datetimeHour_geq: $start, datetimeHour_leq: $end}) {
count
sum {
cost
cachedRequests
erroredRequests
uncachedTokensIn
uncachedTokensOut
cachedTokensIn
cachedTokensOut
__typename
}
__typename
}
__typename
}
__typename
}
}`
}),
chatFiltered: (start: string, end: string) => ({
operationName: null,
variables: {
accountTag: CONFIG.ACCOUNT_TAG,
gateway: CONFIG.GATEWAY,
start,
end,
limit: 1
},
query: `{
viewer {
scope: accounts(filter: {accountTag: $accountTag}) {
latestRequests: aiGatewayRequestsAdaptiveGroups(limit: $limit, filter: {gateway: $gateway, metadataKeys_has: "chatId", datetimeHour_geq: $start, datetimeHour_leq: $end}) {
count
dimensions {
ts: datetimeHour
__typename
}
__typename
}
lastRequest: aiGatewayRequestsAdaptiveGroups(limit: 1, orderBy: [datetimeMinute_DESC], filter: {gateway: $gateway, metadataKeys_has: "chatId", datetimeHour_geq: $start, datetimeHour_leq: $end}) {
dimensions {
ts: datetimeMinute
__typename
}
__typename
}
totalRequests: aiGatewayRequestsAdaptiveGroups(limit: $limit, filter: {gateway: $gateway, metadataKeys_has: "chatId", datetimeHour_geq: $start, datetimeHour_leq: $end}) {
count
sum {
cost
cachedRequests
erroredRequests
uncachedTokensIn
uncachedTokensOut
cachedTokensIn
cachedTokensOut
__typename
}
__typename
}
__typename
}
__typename
}
}`
}),
specificId: (start: string, end: string, metadataValue: string) => ({
operationName: null,
variables: {
accountTag: CONFIG.ACCOUNT_TAG,
gateway: CONFIG.GATEWAY,
start,
end,
limit: 1
},
query: `{
viewer {
scope: accounts(filter: {accountTag: $accountTag}) {
latestRequests: aiGatewayRequestsAdaptiveGroups(limit: $limit, filter: {gateway: $gateway, metadataValues_has: "${metadataValue}", datetimeHour_geq: $start, datetimeHour_leq: $end}) {
count
dimensions {
ts: datetimeHour
__typename
}
__typename
}
lastRequest: aiGatewayRequestsAdaptiveGroups(limit: 1, orderBy: [datetimeMinute_DESC], filter: {gateway: $gateway, metadataValues_has: "${metadataValue}", datetimeHour_geq: $start, datetimeHour_leq: $end}) {
dimensions {
ts: datetimeMinute
__typename
}
__typename
}
totalRequests: aiGatewayRequestsAdaptiveGroups(limit: $limit, filter: {gateway: $gateway, metadataValues_has: "${metadataValue}", datetimeHour_geq: $start, datetimeHour_leq: $end}) {
count
sum {
cost
cachedRequests
erroredRequests
uncachedTokensIn
uncachedTokensOut
cachedTokensIn
cachedTokensOut
__typename
}
__typename
}
__typename
}
__typename
}
}`
})
};
// Execute GraphQL query
async function executeQuery(query: any): Promise<AnalyticsResponse> {
const response = await fetch(CONFIG.GRAPHQL_ENDPOINT, {
method: 'POST',
headers: {
'Authorization': `Bearer ${CONFIG.API_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(query),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
return response.json();
}
// Enhanced analytics display functions
function processProviderRequestData(data: ProviderRequestAnalytics): ProviderSummary[] {
const providerMap = new Map<string, { requests: number; timestamps: string[] }>();
data.data.viewer.accounts[0]?.data.forEach(item => {
const provider = item.dimensions.provider;
if (!providerMap.has(provider)) {
providerMap.set(provider, { requests: 0, timestamps: [] });
}
const providerData = providerMap.get(provider)!;
providerData.requests += item.count;
providerData.timestamps.push(item.dimensions.ts);
});
return Array.from(providerMap.entries()).map(([name, data]) => ({
name,
totalRequests: data.requests,
totalTokensIn: 0,
totalTokensOut: 0,
totalCost: 0,
models: []
}));
}
function processModelTokenData(data: ModelTokenAnalytics): { providers: ProviderSummary[]; models: ModelSummary[] } {
const providerMap = new Map<string, ProviderSummary>();
const modelMap = new Map<string, ModelSummary>();
data.data.viewer.accounts[0]?.data.forEach(item => {
const { provider, model, ts } = item.dimensions;
const { uncachedTokensIn, uncachedTokensOut, cost } = item.sum;
const modelKey = `${provider}::${model}`;
// Update provider summary
if (!providerMap.has(provider)) {
providerMap.set(provider, {
name: provider,
totalRequests: 0,
totalTokensIn: 0,
totalTokensOut: 0,
totalCost: 0,
models: []
});
}
const providerSummary = providerMap.get(provider)!;
providerSummary.totalRequests += item.count;
providerSummary.totalTokensIn += uncachedTokensIn;
providerSummary.totalTokensOut += uncachedTokensOut;
providerSummary.totalCost += cost;
// Update model summary
if (!modelMap.has(modelKey)) {
modelMap.set(modelKey, {
name: model,
provider,
requests: 0,
tokensIn: 0,
tokensOut: 0,
cost: 0,
firstSeen: ts,
lastSeen: ts
});
}
const modelSummary = modelMap.get(modelKey)!;
modelSummary.requests += item.count;
modelSummary.tokensIn += uncachedTokensIn;
modelSummary.tokensOut += uncachedTokensOut;
modelSummary.cost += cost;
modelSummary.lastSeen = ts > modelSummary.lastSeen ? ts : modelSummary.lastSeen;
modelSummary.firstSeen = ts < modelSummary.firstSeen ? ts : modelSummary.firstSeen;
});
// Group models by provider
const models = Array.from(modelMap.values());
providerMap.forEach(provider => {
provider.models = models.filter(m => m.provider === provider.name);
});
return { providers: Array.from(providerMap.values()), models };
}
function displayProviderSummary(providers: ProviderSummary[]): void {
console.log('\n📊 Provider Summary');
console.log('-'.repeat(80));
const providerTable = providers.map(provider => ({
Provider: provider.name,
Requests: provider.totalRequests.toLocaleString(),
'Tokens In': provider.totalTokensIn.toLocaleString(),
'Tokens Out': provider.totalTokensOut.toLocaleString(),
'Total Cost': `$${provider.totalCost.toFixed(6)}`,
Models: provider.models.length
}));
console.table(providerTable);
}
function displayModelBreakdown(providers: ProviderSummary[], topN?: number): void {
console.log('\n🎯 Model Breakdown by Provider');
console.log('-'.repeat(80));
providers.forEach(provider => {
console.log(`\n📈 ${provider.name.toUpperCase()} Models`);
let models = provider.models.sort((a, b) => b.tokensIn + b.tokensOut - (a.tokensIn + a.tokensOut));
if (topN) {
models = models.slice(0, topN);
}
if (models.length === 0) {
console.log(' No model data available');
return;
}
const modelTable = models.map(model => ({
Model: model.name,
Requests: model.requests.toLocaleString(),
'Tokens In': model.tokensIn.toLocaleString(),
'Tokens Out': model.tokensOut.toLocaleString(),
'Total Tokens': (model.tokensIn + model.tokensOut).toLocaleString(),
'Cost': `$${model.cost.toFixed(6)}`,
'First Seen': new Date(model.firstSeen).toLocaleString(),
'Last Seen': new Date(model.lastSeen).toLocaleString()
}));
console.table(modelTable);
});
}
function displayTopModels(models: ModelSummary[], topN: number): void {
console.log(`\n🏆 Top ${topN} Models by Token Usage`);
console.log('-'.repeat(80));
const sortedModels = models
.sort((a, b) => (b.tokensIn + b.tokensOut) - (a.tokensIn + a.tokensOut))
.slice(0, topN);
const topModelsTable = sortedModels.map((model, index) => ({
Rank: `#${index + 1}`,
Model: model.name,
Provider: model.provider,
'Total Tokens': (model.tokensIn + model.tokensOut).toLocaleString(),
'Tokens In': model.tokensIn.toLocaleString(),
'Tokens Out': model.tokensOut.toLocaleString(),
'Cost': `$${model.cost.toFixed(6)}`,
Requests: model.requests.toLocaleString()
}));
console.table(topModelsTable);
}
// Enhanced main display function
function displayResults(results: QueryResult[], options: {
showProviders?: boolean;
showModels?: boolean;
topModels?: number;
}): void {
console.log('\n🚀 Cloudflare AI Gateway Analytics Results\n');
console.log('=' .repeat(80));
let providerData: ProviderSummary[] = [];
let modelData: ModelSummary[] = [];
results.forEach(result => {
console.log(`\n📊 ${result.name}`);
console.log(`⏱️ Response Time: ${result.responseTime}ms`);
console.log('-'.repeat(50));
if (result.error) {
console.log(`❌ Error: ${result.error}`);
return;
}
// Handle different response types
if (result.name.includes('Provider Request Analytics')) {
const data = result.data as ProviderRequestAnalytics;
if (data?.data?.viewer?.accounts?.[0]?.data) {
providerData = processProviderRequestData(data);
const totalRequests = providerData.reduce((sum, p) => sum + p.totalRequests, 0);
console.log(`✅ Found ${providerData.length} providers with ${totalRequests.toLocaleString()} total requests`);
}
} else if (result.name.includes('Model Token Analytics')) {
const data = result.data as ModelTokenAnalytics;
if (data?.data?.viewer?.accounts?.[0]?.data) {
const processed = processModelTokenData(data);
providerData = processed.providers;
modelData = processed.models;
const totalCost = processed.providers.reduce((sum, p) => sum + p.totalCost, 0);
console.log(`✅ Found ${processed.providers.length} providers and ${modelData.length} models with $${totalCost.toFixed(4)} total cost`);
}
} else {
// Legacy analytics display
const data = result.data as AnalyticsResponse;
if (!data?.data?.viewer?.scope?.[0]) {
console.log('❌ No data available');
return;
}
const scope = data.data.viewer.scope[0];
const totalRequests = scope.totalRequests?.[0];
const lastRequest = scope.lastRequest?.[0];
const latestRequests = scope.latestRequests?.[0];
if (totalRequests) {
const {
cost,
cachedRequests,
erroredRequests,
uncachedTokensIn,
uncachedTokensOut,
cachedTokensIn,
cachedTokensOut
} = totalRequests.sum;
const totalTokensIn = uncachedTokensIn + cachedTokensIn;
const totalTokensOut = uncachedTokensOut + cachedTokensOut;
const errorRate = totalRequests.count > 0 ? ((erroredRequests / totalRequests.count) * 100).toFixed(2) : '0.00';
const cacheHitRate = totalRequests.count > 0 ? ((cachedRequests / totalRequests.count) * 100).toFixed(2) : '0.00';
const analytics = [
{
Metric: 'Total Requests',
Value: totalRequests.count.toLocaleString(),
Details: `${cachedRequests} cached, ${erroredRequests} errors`
},
{
Metric: 'Total Cost',
Value: `$${cost.toFixed(6)}`,
Details: 'Estimated cost'
},
{
Metric: 'Tokens In',
Value: totalTokensIn.toLocaleString(),
Details: `${uncachedTokensIn.toLocaleString()} uncached, ${cachedTokensIn.toLocaleString()} cached`
},
{
Metric: 'Tokens Out',
Value: totalTokensOut.toLocaleString(),
Details: `${uncachedTokensOut.toLocaleString()} uncached, ${cachedTokensOut.toLocaleString()} cached`
},
{
Metric: 'Error Rate',
Value: `${errorRate}%`,
Details: `${erroredRequests} errors out of ${totalRequests.count} requests`
},
{
Metric: 'Cache Hit Rate',
Value: `${cacheHitRate}%`,
Details: `${cachedRequests} cached out of ${totalRequests.count} requests`
}
];
if (lastRequest?.dimensions?.ts) {
analytics.push({
Metric: 'Last Request',
Value: new Date(lastRequest.dimensions.ts).toLocaleString(),
Details: 'Most recent request timestamp'
});
}
if (latestRequests?.count && latestRequests?.dimensions?.ts) {
analytics.push({
Metric: 'Latest Hour Activity',
Value: `${latestRequests.count} requests`,
Details: `At ${new Date(latestRequests.dimensions.ts).toLocaleString()}`
});
}
console.table(analytics);
} else {
console.log('❌ No request data available');
}
}
});
// Display enhanced analytics if requested
if (options.showProviders && providerData.length > 0) {
displayProviderSummary(providerData);
}
if (options.showModels && providerData.length > 0) {
displayModelBreakdown(providerData, options.topModels);
}
if (options.topModels && modelData.length > 0) {
displayTopModels(modelData, options.topModels);
}
console.log('\n' + '='.repeat(80));
console.log('✅ Analysis complete!');
}
// Parse command line arguments
function parseArgs(): {
userId?: string;
chatId?: string;
days?: number;
showModels?: boolean;
showProviders?: boolean;
granularity?: 'minute' | 'hour';
topModels?: number;
} {
const args = process.argv.slice(2);
const result: {
userId?: string;
chatId?: string;
days?: number;
showModels?: boolean;
showProviders?: boolean;
granularity?: 'minute' | 'hour';
topModels?: number;
} = {};
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case '--user-id':
result.userId = args[i + 1];
i++;
break;
case '--chat-id':
result.chatId = args[i + 1];
i++;
break;
case '--days':
result.days = parseInt(args[i + 1]) || 1;
i++;
break;
case '--show-models':
result.showModels = true;
break;
case '--show-providers':
result.showProviders = true;
break;
case '--granularity':
const granularity = args[i + 1];
if (granularity === 'minute' || granularity === 'hour') {
result.granularity = granularity;
}
i++;
break;
case '--top-models':
result.topModels = parseInt(args[i + 1]) || 10;
i++;
break;
}
}
return result;
}
// Generate time range (using format from your examples)
function getTimeRange(days: number = 1, granularity: 'minute' | 'hour' = 'hour'): { start: string; end: string } {
const end = new Date();
const start = new Date(end.getTime() - (days * 24 * 60 * 60 * 1000));
if (granularity === 'minute') {
// For minute-level queries, use ISO format as shown in examples
return {
start: start.toISOString(),
end: end.toISOString()
};
} else {
// Use the timezone-aware format for hour-level queries
const offsetMinutes = end.getTimezoneOffset();
const offsetHours = Math.floor(Math.abs(offsetMinutes) / 60);
const offsetMins = Math.abs(offsetMinutes) % 60;
const offsetSign = offsetMinutes <= 0 ? '+' : '-';
const offsetStr = `${offsetSign}${offsetHours.toString().padStart(2, '0')}:${offsetMins.toString().padStart(2, '0')}`;
// Set start time to beginning of the day
const startOfDay = new Date(start);
startOfDay.setHours(0, 0, 0, 0);
return {
start: startOfDay.toISOString().slice(0, 19) + offsetStr,
end: end.toISOString().slice(0, 19) + offsetStr
};
}
}
// Main function
async function main(): Promise<void> {
try {
console.log('🔍 Initializing configuration from environment variables...');
initializeConfig();
console.log(`🔧 Configuration:`);
console.log(` Account: ${CONFIG.ACCOUNT_TAG}`);
console.log(` Gateway: ${CONFIG.GATEWAY}`);
console.log(` Endpoint: ${CONFIG.GRAPHQL_ENDPOINT}`);
console.log(` Environment: ${CONFIG.IS_STAGING ? 'Staging' : 'Production'}`);
console.log(` Token: ${CONFIG.API_TOKEN.substring(0, 8)}... (${CONFIG.IS_STAGING ? 'AI Gateway token' : 'API token'})`);
const args = parseArgs();
const granularity = args.granularity || 'hour';
const timeRange = getTimeRange(args.days || 1, granularity);
console.log(`📅 Analyzing data from ${timeRange.start} to ${timeRange.end}`);
console.log(`⚙️ Granularity: ${granularity}-level precision`);
const queries: Array<{ name: string; query: any }> = [];
// Enhanced query selection based on user input and options
if (args.userId) {
queries.push({
name: `User Analytics (${args.userId})`,
query: QUERIES.specificId(timeRange.start, timeRange.end, args.userId)
});
// Add enhanced queries if requested - using generic queries for user ID (user-specific filtering would need different implementation)
if (args.showProviders || args.showModels) {
queries.push(
{ name: 'User Provider Request Analytics', query: QUERIES.providerRequests(timeRange.start, timeRange.end, granularity) },
{ name: 'User Model Token Analytics', query: QUERIES.modelTokens(timeRange.start, timeRange.end, granularity) }
);
}
} else if (args.chatId) {
queries.push({
name: `Chat Analytics (${args.chatId})`,
query: QUERIES.specificId(timeRange.start, timeRange.end, args.chatId)
});