LLM API Request Compression: How to Reduce Tokens Without Quality Loss
Summary
Compressing LLM API requests allows reducing token usage and call costs without significant quality loss.
When to Compress Requests
Request compression is relevant in three scenarios:
- Long context (documents, logs, conversations) does not fit within the model's window;
- Token costs become a significant expense;
- Response latency increases due to a large number of input tokens.
Compression does not replace context window management and prompt caching, but complements them.
Compression Methods
1. Extracting Key Fragments
Before sending the request, highlight relevant parts of the text. Use:
- embeddings and semantic search;
- BM25;
- regular expression rules.
Example extraction using embeddings:
from sentence_transformers import SentenceTransformer
import numpy as np
model = SentenceTransformer('all-MiniLM-L6-v2')
def extract_relevant(text: str, query: str, top_k: int = 3) -> str:
sentences = text.split('. ')
query_emb = model.encode(query)
sent_embs = model.encode(sentences)
scores = np.dot(sent_embs, query_emb)
top_idx = np.argsort(scores)[-top_k:][::-1]
return '. '.join(sentences[i] for i in top_idx)
2. Summarization
For large documents, use a separate LLM call to create a summary. This adds one request but saves tokens on all subsequent calls.
from openai import OpenAI
client = OpenAI()
def summarize(text: str, max_tokens: int = 500) -> str:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "Summarize the text to key facts. Keep numbers, names, and dates."},
{"role": "user", "content": text}
],
max_tokens=max_tokens
)
return response.choices[0].message.content
3. Removing Stop Words and Noise
For technical texts, remove stop words, repeated headers, and boilerplate phrases. Use the nltk library:
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
stop_words = set(stopwords.words('russian'))
def remove_stopwords(text: str) -> str:
tokens = word_tokenize(text.lower())
filtered = [t for t in tokens if t not in stop_words and t.isalnum()]
return ' '.join(filtered)
Caution: Removing stop words may degrade quality for models trained on full texts. Use only for long documents.
4. Structured Compression
Transform text into a compact structure: tables, JSON, lists. This reduces the number of tokens and simplifies structured output.
Example:
{
"summary": "Brief description",
"key_points": ["point 1", "point 2"],
"metrics": {"accuracy": 0.95, "latency_ms": 120}
}
Compression Evaluation Metrics
Before implementing compression, fix metrics:
| Metric | Description | Target Value |
|---|---|---|
| Compression Ratio | Original tokens / compressed tokens | > 2 |
| Answer Relevancy | Answer relevance | > 0.8 |
| Faithfulness | Fact alignment | > 0.9 |
| Cost per request | USD for 1000 requests | reduction > 40% |
For evaluation, use RAGAS or LLM-as-a-Judge.
Step-by-Step Implementation
Step 1. Request Profiling
Collect real requests from logs. Determine:
- average prompt size in tokens;
- percentage of repeated fragments;
- content types (documents, chats, code).
Step 2. Strategy Selection
For each content type, choose a method:
| Content Type | Method |
|---|---|
| Documents > 10K tokens | Summarization |
| Logs | Key line extraction |
| Conversations | Quote and signature removal |
| Code | Comment and blank line removal |
Step 3. Pipeline Implementation
Create a compression module before API call:
class RequestCompressor:
def __init__(self, strategy: str):
self.strategy = strategy
def compress(self, text: str, query: str) -> str:
if self.strategy == "extract":
return extract_relevant(text, query)
elif self.strategy == "summarize":
return summarize(text)
elif self.strategy == "stopwords":
return remove_stopwords(text)
else:
return text
Step 4. A/B Testing
Conduct A/B testing: compare responses with and without compression on a control sample. Evaluate quality and cost.
Step 5. Monitoring
Add metrics to observability system:
- compression ratio per request;
- percentage of requests where compression degraded the response;
- token savings per day.
Compression Errors
- Compressing context critical for accuracy (legal texts, medical data).
- Applying summarization to short requests — overhead outweighs benefits.
- Ignoring token limits after compression.