Elffuss BraidHub

kikocis/continue public

29862bc4ae5f · 2.5 KiBRawPermalink
1import { Telemetry } from "./posthog.js";
2
3interface TokenBatch {
4 model: string;
5 provider: string;
6 count: number;
7 totalPromptTokens: number;
8 totalGeneratedTokens: number;
9 lastEventTime: number;
10}
11
12export class TokensBatchingService {
13 private static instance: TokensBatchingService;
14 private batches = new Map<string, TokenBatch>();
15 private flushTimer: NodeJS.Timeout | null = null;
16
17 private readonly BATCH_SIZE_LIMIT = 25;
18 private readonly FLUSH_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
19
20 static getInstance(): TokensBatchingService {
21 if (!TokensBatchingService.instance) {
22 TokensBatchingService.instance = new TokensBatchingService();
23 }
24 return TokensBatchingService.instance;
25 }
26
27 private constructor() {
28 this.startFlushTimer();
29 }
30
31 addTokens(model: string, provider: string, promptTokens: number, generatedTokens: number): void {
32 const key = `${provider}:${model}`;
33
34 if (!this.batches.has(key)) {
35 this.batches.set(key, {
36 model,
37 provider,
38 count: 0,
39 totalPromptTokens: 0,
40 totalGeneratedTokens: 0,
41 lastEventTime: Date.now(),
42 });
43 }
44
45 const batch = this.batches.get(key)!;
46 batch.count++;
47 batch.totalPromptTokens += promptTokens;
48 batch.totalGeneratedTokens += generatedTokens;
49 batch.lastEventTime = Date.now();
50
51 // Flush if batch is full
52 if (batch.count >= this.BATCH_SIZE_LIMIT) {
53 this.flushBatch(key, batch);
54 }
55 }
56
57 private flushBatch(key: string, batch: TokenBatch): void {
58 if (batch.count === 0) return;
59
60 void Telemetry.capture(
61 "tokens_generated_batch",
62 {
63 model: batch.model,
64 provider: batch.provider,
65 eventCount: batch.count,
66 totalPromptTokens: batch.totalPromptTokens,
67 totalGeneratedTokens: batch.totalGeneratedTokens,
68 avgPromptTokens: Math.round(batch.totalPromptTokens / batch.count),
69 avgGeneratedTokens: Math.round(batch.totalGeneratedTokens / batch.count),
70 },
71 true,
72 );
73
74 this.batches.delete(key);
75 }
76
77 private startFlushTimer(): void {
78 this.flushTimer = setInterval(() => {
79 this.flushAllBatches();
80 }, this.FLUSH_INTERVAL_MS);
81 }
82
83 private flushAllBatches(): void {
84 for (const [key, batch] of this.batches.entries()) {
85 this.flushBatch(key, batch);
86 }
87 }
88
89 shutdown(): void {
90 if (this.flushTimer) {
91 clearInterval(this.flushTimer);
92 this.flushTimer = null;
93 }
94 this.flushAllBatches();
95 }
96}