Mental model
Browser prompt compression turns a long text passage into a smaller textual context before a request leaves the device, then measures that text as tokens for the destination model. It is lossy: the original remains authoritative, and the compressed passage is accepted only when its retained facts support the downstream task within an explicit request budget.
Learning outcomes
- Separate model distillation, tokenizer compression, and prompt-context compression.
- Calculate the remaining context budget after system instructions, tools, the user query, and an answer reserve.
- Design a local compression path that preserves the source, checks the destination request, and measures task quality.
Theory
“Token distillation” can describe two different operations. Model distillation transfers a teacher model’s behavior into a smaller student model during training. Prompt compression shortens the text supplied to a model for one request. A browser summarizer performs the second operation; it does not make token IDs smaller, and its output is not interchangeable with the destination model’s tokens.
The runtime boundary is text. A local sequence-to-sequence model may summarize a transcript or rank which spans to retain, but the receiving model tokenizes the final serialized request with its own vocabulary and message format. A local tokenizer can estimate size, yet hidden tool schemas, framing tokens, model revisions, or provider-side transformations can change the final count. The target provider’s counter, when available, is the check for a hard context limit.
Compression also changes meaning. An abstractive summarizer can paraphrase, omit a negation, or invent a connective claim. An extractive compressor keeps original spans and is easier to audit, but it may retain awkward fragments and can still remove a crucial qualifier. LLMLingua-2 is a trained, token-level extractive compressor whose training process uses teacher-produced compressed examples and preservation labels; it is not the same algorithm as calling a browser summarization pipeline. Choose the approach according to whether the task tolerates paraphrase, and record that choice with the request.
Budget model and worked example
Let be the destination-model token count for the original context, the count for its compressed text, and the context allowance after system text, tool definitions, the user’s question, the answer reserve, and a safety margin have been accounted for. The fractional token reduction is dimensionless:
r_{ ext{saved}} = rac{T_s - T_c}{T_s}, qquad T_c leq B_r
If a request has an 8,192-token window, 600 tokens of system instructions, 1,400 tokens of tool schemas, a 320-token question, a 1,000-token output reserve, and a 400-token margin, then the context allowance is 4,472 tokens. A 7,600-token retrieved passage compressed to 2,350 target-model tokens saves and fits with 2,122 tokens of headroom. The example counts only hold if those values use the destination model’s request format; a browser-side BPE estimate alone cannot certify the limit.
Token reduction is not a quality score. In a held-out set of 200 support questions, an original context might answer 190 correctly while a compressed version answers 184 correctly. That is a reduction from 95% to 92% task accuracy, even though the request is smaller. Keep both measurements: context reduction explains resource use, while an application metric such as exact-field accuracy, answer recall, or citation coverage tells whether the reduced context still serves the task.
Trade-offs
Extractive selection is a better fit for legal clauses, identifiers, quoted user text, or passages where a paraphrase would alter a commitment. Abstractive summaries often read better and can combine redundant sentences, but they need stronger checks for dropped numbers, negation, names, dates, and attribution. Query-conditioned compression spends more tokens on the facts likely to answer the current request; task-agnostic compression can be reused, but may throw away the one detail a later question needs.
Browser execution keeps the uncompressed passage on the client during the transform and can reduce transmitted text. It still consumes battery, memory, download bandwidth for model weights, and main-thread or worker time. A first-use model download can cost more than the saved request, while a weak device may make local compression slower than sending the original. Cache a versioned compressor only when consent, storage limits, and model update policy allow it. Keep the original locally until the request is accepted or explicitly discarded so that a failed transform has a safe fallback.
Failure modes and misconceptions
- Treating the compressed token count as a portable token-ID stream. Send text, then let the destination tokenizer count it.
- Trusting a compression ratio as evidence of semantic retention. A 4× reduction says nothing about whether a product ID, exception, or negative condition survived.
- Summarizing a long document in one call. Some models overcompress long inputs; bounded paragraph or sentence chunks limit that drift, but chunk boundaries can still hide cross-section dependencies.
- Uploading the source after a local failure without telling the user. The fallback changes the privacy boundary and may increase cost; make it an explicit policy branch.
- Caching a summary under only a document ID. Include source version, compressor model revision, task/query fingerprint, and target tokenizer/model version, or invalidation can reuse a summary for a changed passage.
- Assuming “on device” means private forever. The compressed output is still transmitted, and embeddings or summaries may preserve sensitive facts. Apply the same data handling rules to both representations.
Decision scenario
A browser assistant must answer a question from an 11,000-token product manual. Its request leaves 3,200 tokens for context after tools, question, output reserve, and margin. A local compressor produces 2,700 tokens, but in a 150-question held-out set it drops model numbers in 9 answers, compared with 2 errors on the uncompressed baseline. The request now fits, but the compression policy does not meet the product’s identifier accuracy target. Preserve exact model-number spans, rerun the downstream evaluation, and use the original path or ask for a narrower question when the revised context exceeds the budget. Do not ship because the average summary looks readable.
Implementation pattern
This example summarizes short chunks locally, keeps the input intact, and asks an application adapter to count the complete request for the destination model. The adapter must include the actual system, tool, and message framing; its result is the gate, not the summarizer’s generated-length parameter.
typescriptimport { pipeline } from "@huggingface/transformers";const summarizer = await pipeline("summarization", "Xenova/distilbart-cnn-6-6");type CountRequest = (messages: Array<{ role: string; content: string }>) => Promise<number>;function splitSentences(text: string, maxChars = 2500): string[] {const sentences = text.match(/[^.!?]+[.!?]+(?:\s+|$)|[^.!?]+$/g) ?? [text];const chunks: string[] = [];let current = "";for (const sentence of sentences) {if (sentence.length > maxChars) throw new RangeError("split an oversized sentence safely");if (current && current.length + sentence.length > maxChars) {chunks.push(current.trim());current = "";}current += sentence;}if (current.trim()) chunks.push(current.trim());return chunks;}export async function compressContext(messages: Array<{ role: string; content: string }>,contextIndex: number,maxInputTokens: number,countRequest: CountRequest,) {const source = messages[contextIndex];if (!source || source.role !== "user" || !source.content.trim()) throw new Error("context message is missing");const pieces: string[] = [];for (const chunk of splitSentences(source.content)) {const result = await summarizer(chunk, { max_new_tokens: 112, do_sample: false });const summary = result[0]?.summary_text?.trim();if (!summary) throw new Error("compressor returned no text");pieces.push(summary);}const candidate = messages.map((message, index) =>index === contextIndex ? { ...message, content: pieces.join(" ") } : message,);const targetTokens = await countRequest(candidate);if (targetTokens > maxInputTokens) throw new RangeError("compressed request still exceeds its target budget");return { messages: candidate, targetTokens, sourceText: source.content };}
The returned source text lets the caller keep a recoverable record while the request is being prepared. Pin the model revision in the application, compare compression against an uncompressed baseline on representative tasks, and reject a candidate that fails either the context limit or the quality target.