-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenizer.ts
More file actions
32 lines (26 loc) · 999 Bytes
/
Copy pathtokenizer.ts
File metadata and controls
32 lines (26 loc) · 999 Bytes
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
// tokenizer.ts
// Simple tokenizer that estimates tokens based on word boundaries and special characters
export function generateTokenString(text: string): string | null {
try {
const estimatedTokens = estimateTokenCount(text);
if (estimatedTokens > 1_000_000) {
return `${(estimatedTokens / 1_000_000).toFixed(1)}M`;
}
if (estimatedTokens > 1_000) {
return `${(estimatedTokens / 1_000).toFixed(1)}k`;
}
return `${estimatedTokens}`;
} catch (error) {
console.error("Error estimating tokens:", error);
return null;
}
}
function estimateTokenCount(text: string): number {
// Split on whitespace and punctuation
const tokens = text.split(/[\s\p{P}]+/u).filter(Boolean);
// Count special tokens (newlines, indentation, etc.)
const specialTokens = (text.match(/[\n\t]/g) || []).length;
// Add some overhead for encoding special characters and subword tokenization
const overhead = Math.floor(tokens.length * 0.2);
return tokens.length + specialTokens + overhead;
}