DEV Community

Yashvardhan Thanvi
Yashvardhan Thanvi

Posted on • Originally published at yashvardhanthanvi.hashnode.dev

Building LLMSlim: Architecture Deep-Dive into Deterministic Prompt Compression

Most prompt compression discussions focus on the happy path: you have a long RAG context, you trim it to 50% of tokens, and your API bill halves. What rarely gets discussed are the failure modes: dropped system instructions, truncated JSON schemas, broken code fences, and entity names that get quietly pruned because they scored low in some similarity metric.

LLMSlim (https://www.llmslim.app) is a Python library I've spent the last few months building to handle these edge cases properly. This post goes deep on the architecture decisions that make it work.

The Core Problem: Information vs. Filler

LLM input prompts have a structural problem. The instructions that govern model behavior (system roles, JSON schemas, MUST/NEVER directives) are typically a tiny fraction of the total token count. The rest is context: retrieved documents, conversation history, background information. And within that context, a significant fraction is prose that exists for human readability, not informational density.

The challenge is distinguishing high-value informational sentences from low-value filler without a model call, without embeddings, and in under 30ms.

The 6-Step Pipeline

LLMSlim processes prompts through a deterministic DAG (Directed Acyclic Graph) with six stages:

1. Protected Sentence Splitting

Naive sentence splitting on periods breaks code blocks and URLs. The first stage uses regex-based splitting that respects:

  • AST code fences (triple backticks) - treated as atomic units
  • Markdown heading markers
  • URLs (no splitting on periods within URLs)
  • Common abbreviations (e.g., U.S., etc.)
# Pseudocode: core split logic
sentences = regex_split(text)
for i, sent in enumerate(sentences):
    if is_code_fence(sent): protected[i] = True  # immune to scoring
Enter fullscreen mode Exit fullscreen mode

2. TF-IDF Vector Graph Construction

Each sentence becomes a TF-IDF vector. We compute the full pairwise cosine similarity matrix over these vectors to build a weighted undirected graph where edge weight(i,j) = cosine_similarity(v_i, v_j).

The choice of TF-IDF over neural embeddings was deliberate. TF-IDF runs in microseconds per sentence. It captures vocabulary overlap well, which is exactly what matters for identifying redundant prose. Neural embeddings add 50-100ms of latency and model loading overhead that isn't justified for this task.

3. LexRank Centrality Scoring

We apply the LexRank algorithm: convert the similarity graph to a stochastic transition matrix M, then find the stationary distribution via power iteration:

p_t+1 = d * M * p_t + (1-d) / n
Enter fullscreen mode Exit fullscreen mode

where d is a damping factor (typically 0.85) and n is the sentence count. Convergence typically happens in 20-30 iterations. The resulting stationary probability vector gives each sentence a centrality score representing how informationally central it is to the document.

4. Priority Tier Hard Locking

This is the stage that separates LLMSlim from naive extraction approaches. Before any sentence can be pruned, a deterministic rule pass classifies every sentence into one of four tiers:

Tier 4 (Inviolable): Sentences containing:

  • Role markers: system:, developer:, user:
  • Imperative keywords: MUST, NEVER, ALWAYS, REQUIRED, DO NOT
  • JSON/XML schema delimiters

Tier 3 (Protected): Sentences containing:

  • Numerical entities (currency, percentages, measurements)
  • Proper nouns and named entities
  • URL references
  • Code identifiers

Tier 2 (Standard): Regular content sentences

Tier 1 (Candidate for removal): Filler phrases, transition sentences

Tier 4 sentences are hardcoded to survive the compression pass regardless of their LexRank score. A sentence saying "You MUST respond only in JSON" will score low in a document full of prose paragraphs - but it's the most important sentence in the prompt.

5. Two-Pass Budget Allocation

Pass 1 divides the document into semantic chunks and allocates token budgets proportionally:

chunk_budget_i = target_tokens * (chunk_tokens_i / total_tokens)
Enter fullscreen mode Exit fullscreen mode

Pass 2 applies a global rebalancing step. Each chunk may have selected sentences that, together, slightly exceed or undershoot its budget. The second pass collects the surplus/deficit across all chunks and redistributes tokens using a priority-aware greedy knapsack:

  • Sort remaining unselected sentences by (tier, lexrank_score) descending
  • Greedily include sentences until global token target is hit

This two-pass approach is why the library consistently hits within 2-3% of the target ratio even on highly variable document structures.

6. Ordered Reassembly

Selected sentences are sorted by their original document position and concatenated. Original ordering is preserved because causal reasoning and logical flow in documents depends on sequence, not just content.

The Hybrid Strategy (v0.3.0)

v0.3.0 adds a generative compression layer on top of the extractive pipeline. The flow:

  • Extractive pre-pruning reduces the context to ~130% of target (intentionally slightly over)
  • A RewriteRequest is passed to a pluggable CallableProvider
  • The LLM rewrites the pre-pruned context targeting the final ratio
  • A validation pass checks that all Tier 4 sentences survived
  • If validation fails, the extractive output is returned as fallback

The pluggable provider model means you don't need a specific LLM API key:

from llmslim import compress, CallableProvider, RewriteRequest

def my_provider(req: RewriteRequest) -> str:
    # req.system_prompt, req.user_prompt, req.target_ratio all available
    return your_llm_function(req.user_prompt)

provider = CallableProvider(my_provider)
result = compress(context, target_ratio=0.4, strategy="hybrid", provider=provider)
Enter fullscreen mode Exit fullscreen mode

Benchmarks

All benchmarks are reproducible. Hardware: AMD EPYC 7763, 64GB RAM, Ubuntu 24.04, Python 3.12.3, tiktoken cl100k_base. N=500 prompts per dataset, 100 iterations per sample.

Dataset Token Reduction Latency (mean) Directive Retention Entity Preservation
System Directives 51.4% ± 1.2% 24.8ms ± 2.1ms 100.0% 95.1% ± 1.1%
50k Context (GPT-5) 55.0% ± 1.1% 26.0ms ± 2.4ms 100.0% 94.9% ± 1.2%
XML Mode (Claude 3.5) 50.0% ± 0.8% 24.0ms ± 1.9ms 100.0% 96.4% ± 0.9%
100k RAG (Gemini) 65.0% ± 1.3% 38.0ms ± 3.1ms 100.0% 94.8% ± 1.3%

What Didn't Work

Attempt 1: Pure TF-IDF cutoff. Setting a similarity threshold and dropping sentences below it sounds simple. In practice, document sections with specialized vocabulary score low across the board even when they contain critical information. Threshold tuning became document-specific.

Attempt 2: Summarization for compression. Running a smaller model to summarize chunks seems appealing. It adds a full model inference call (50-500ms), requires an API dependency, and summaries tend to drop entity specifics that matter for downstream model performance.

Attempt 3: Single-pass budget allocation. Works fine for uniform documents. Fails badly on documents with mixed density: technical specs mixed with background narrative. The two-pass approach emerged from debugging these failures.

Installation and Links

pip install llmslim
Enter fullscreen mode Exit fullscreen mode

The benchmark scripts, raw JSON payloads, and full methodology are open. If you find issues with the numbers, open an issue - I'd genuinely like to know.

Top comments (1)

Collapse
 
hannune profile image
Tae Kim

The failure modes you list at the top are exactly what made me distrust pure TF-IDF or embedding-based compression — a MUST NOT instruction scores low on similarity to the query but removing it breaks the entire agent's safety contract. The architecture decision that helped most was separating the prompt into structural segments before any scoring: system prompt, schema definitions, and tool specs get a protected flag and bypass compression entirely, leaving only the retrieved context section for scoring. The entity-name pruning problem is subtle and underreported — when two sentences reference the same entity chain (A to B to C), dropping the middle sentence kills the reasoning path even if each individual sentence scored above the cutoff. For JSON schema specifically, block-level preservation works better than sentence-level: compress the surrounding prose but keep schema blocks verbatim since model schema adherence degrades non-linearly when even one property description gets truncated.