Managing and Reducing Costs › Strategy 6: Use Prompt Compression
Michael BrenndoerferAugust 26, 20252 min read
AI Agent HandbookAll chapters Part 15 of 15Performance and Cost Optimization - Doing More with Less
Managing and Reducing Costs › Strategy 6: Use Prompt CompressionOne section · Sections in this chapter9 / 15 ↓
Sections in this chapter15
For agents that need to include large amounts of context (like retrieved documents or long system prompts), consider compressing that information.
Example: Context Summarization (Claude Sonnet 4.5)
In[10]:
Codeimport os
from anthropic import Anthropic
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
def summarize_context(long_context, max_length=500):
"""Compress long context into a shorter summary."""
if len(long_context) <= max_length:
return long_context
# Use the model to create a concise summary
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=200,
messages=[{
"role": "user",
"content": f"Summarize this in {max_length//4} words or less:\n\n{long_context}"
}]
)
return response.content[0].text
def respond_with_context(query, long_context):
"""Answer query using compressed context."""
# Compress the context first
compressed_context = summarize_context(long_context, max_length=500)
# Use compressed context in the actual query
full_prompt = f"Context: {compressed_context}\n\nQuestion: {query}"
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=512,
messages=[{"role": "user", "content": full_prompt}]
)
return response.content[0].text
## Example: Long document that needs to be included
long_document = """
[Imagine a 5000-word document about machine learning here...]
Machine learning is a field of artificial intelligence that focuses on...
[... many more paragraphs ...]
"""
## Without compression: ~5000 tokens input
## With compression: ~500 tokens input
## Savings: ~90% on input tokens for this context
query = "What are the key concepts in this document?"
answer = respond_with_context(query, long_document)
print(answer)Out[10]:
ConsoleI don't actually have access to a real 5000-word document about machine learning - you've only provided a placeholder indicating where such a document would be. From what you've shown me, I can only see: - A fragment mentioning "Machine learning is a field of artificial intelligence that focuses on..." - Placeholders indicating there would be more content To provide you with the key concepts from a document, I would need the actual full text. If you'd like me to analyze a document about machine learning, please paste the complete content, and I'll be happy to: 1. Identify the main concepts covered 2. Summarize key themes 3. Highlight important terminology and ideas 4. Note any significant examples or applications mentioned Would you like to share the actual document text?
You pay for the summarization call, but if you use that compressed context multiple times, you save money overall. This is especially valuable for retrieval-augmented generation (RAG) systems where you're including retrieved documents in every query.