Token Optimization
Minimize token consumption and API billing through tiktoken counting, context pruning, payload compression, and whitespace minification.
TL;DR
- Count exact request tokens locally before API dispatch using
tiktoken. - Prune redundant conversational turns to conserve available
context-windowcapacity. - Compress structured payloads and eliminate unnecessary
whitespace-indentationacross data requests.
Local Token Counting
Tiktoken EncodingInitialize BPE tokenizer matching target model architecture.
import { get_encoding } from 'tiktoken';
const enc = get_encoding('cl100k_base');
const count = enc.encode('Hello world!').length;
enc.free(); // Free WebAssembly memoryChat Message EstimatorAccount for role tokens and message framing overhead.
function countMessageTokens(msg: ChatMessage): number {
const enc = get_encoding('cl100k_base');
const tokens = enc.encode(msg.content).length + 4;
enc.free();
return tokens;
}Pre-Flight Budget CheckValidate prompt size against hard account limits before dispatch.
const total = countPrompt(prompt);
if (total > 8000) {
throw new Error(
`Tokens exceed limit: ${total}`
);
}Payload Compression
JSON MinificationStrip superfluous indentation whitespace before sending payload.
const minified = JSON.stringify(data);
// Saves ~25% tokens vs JSON.stringify(data, null, 2)Tabular TSV ConversionRepresent row data as tab-separated values instead of JSON.
function toTSV(rows: any[]): string {
const head = Object.keys(rows[0]).join('\t');
const body = rows
.map(r => Object.values(r).join('\t'));
return [head, ...body].join('\n');
}Stopword StrippingRemove low-information conversational filler words from queries.
function pruneFiller(text: string): string {
const pat = /\b(please|kindly|could you)\b/gi;
return text.replace(pat, '');
}Context Window Pruning
Sliding Turn WindowRetain only the most recent N conversational exchanges.
function getRecentHistory(msgs: ChatMessage[], n = 6) {
const system = msgs.filter(m => m.role === 'system');
const recents = msgs.slice(-n);
return [...system, ...recents];
}Token Budget TrimmerTrim history dynamically to fit strict token ceiling.
function trimBudget(
msgs: ChatMessage[],
max = 2000
) {
let cur = 0;
return msgs.reverse().filter(m => {
cur += countTokens(m.content);
return cur <= max;
}).reverse();
}Context SummarizationCondense long dialog histories into compact running summaries.
const prompt = `Summarize: ${oldChat}`;
const summary = await miniModel
.complete(prompt);Prompt Efficiency Hygiene
Concise System PromptsRefactor redundant wordy instructions into compact bullet rules.
// Bad: 'Please act as an expert...'
// Good: 'Role: TS Engineer. Output: Code.'Single-Letter DelimitersReplace verbose XML tags with compact delimiters when tokens matter.
const prompt = `[Q]\n${userQuery}\n[A]\n`;
// Saves tokens over <user_input_question_data>Token Billing AuditRecord token metrics to calculate daily cost attribution.
function auditSpend(tokens: number, ratePerM: number) {
const cost = (tokens / 1000000) * ratePerM;
metrics.gauge('ai.cost.daily', cost);
}Tips
- Convert verbose JSON payloads to compact delimited
tsv-formatrows when transmitting tabular datasets to slash token usage by 40%. - Filter repetitive system reminders out of multi-turn
dialogue-historyarrays to prevent redundant token billing on every exchange.
Warnings
- Do not rely on naive word counts or character estimates because punctuation, code, and whitespace consume disproportionate numbers of
BPE-tokens. - Avoid over-pruning context to the point of stripping critical business rules because
under-promptingtriggers expensive hallucination recovery cycles.
In Practice
Counts tokens locally using tiktoken and trims conversational history to fit inside a strict budget.
- Import tiktoken and initialize encoding model.
- Calculate token consumption for individual message entries.
- Enforce strict token ceiling by trimming older dialogue turns.
- Preserve critical system prompt and return optimized message list.
import { get_encoding } from 'tiktoken';
type M = { role: string; text: string };
function trimChat(msgs: M[]) {
const enc = get_encoding('cl100k_base');
let used = 0;
const kept = msgs.reverse().filter(m => {
const cost = enc.encode(m.text).length + 4;
if (used + cost <= 50) {
used += cost;
return true;
}
return false;
}).reverse();
enc.free();
return kept;
}
const chat = [{ role: 'user', text: 'Hello AI' }];
console.log(trimChat(chat));FAQ
Models process text using Byte Pair Encoding (BPE). Common words represent single tokens, while rare words, code punctuation, numbers, and indentation are split across multiple tokens. One token roughly equals four English characters.
Use the official tiktoken library. Instantiate an encoding like cl100k_base or o200k_base and call encoding.encode(text).length. This calculates exact token counts without making network requests.
Context pruning is the practice of removing older conversational turns, compressing historical messages into summaries, or dropping low-relevance retrieval chunks to keep prompt size within budget limits.