Context Compressor
Prerequisites & Dependencies
- Python 3.10+ with
pip install tiktoken openai
- Model provider API key for summarization (a cheap, fast model suffices)
- Known token budget of the target model (e.g., 128k window; plan for 60-70% utilization to reserve space)
Execution Steps
- Measure token count of the full context with the model's tokenizer, computing headroom against the budget while reserving tokens for the system prompt and expected output.
- Segment the context into compression units: per-turn conversation pairs, per-file code blocks, per-document sections.
- Classify each unit as verbatim (active task code, explicit constraints, accepted decisions, last N turns) or compressible (exploration output, verbose tool logs, already-resolved debugging).
- Summarize compressible units with a fixed extraction template (topic, outcome, constraints, open questions); prefer maps/diffs over free prose.
- Reassemble in order: pinned verbatim units first, followed by compact summaries, then the most recent verbatim turns; oldest-to-newest ordering preserves recency bias.
- Verify: compare total token count against budget and run a faithfulness check — does a fresh model answer key questions from the original content correctly using the compressed version?
import tiktoken
from openai import OpenAI
enc = tiktoken.encoding_for_model("gpt-4o")
count = lambda s: len(enc.encode(s))
TEMPLATE = ("Compress into terse notes. Keep: decisions, constraints, code identifiers, "
"open questions. Drop: pleasantries, repetition, failed attempts.\n\n{text}")
def compress(units: list[str], budget: int, client: OpenAI) -> list[str]:
out, used = [], 0
for u in units:
if count(u) <= 120: # keep short verbatim units as-is
kept = u
else:
kept = client.chat.completions.create(
model="gpt-4o-mini", temperature=0,
messages=[{"role": "user", "content": TEMPLATE.format(text=u)}],
).choices[0].message.content
if used + count(kept) > budget:
break
used += count(kept); out.append(kept)
return out
1---2name: context-compressor3description: Compress long conversation histories or documents to save context window token limits.4---56# Context Compressor78## Prerequisites & Dependencies9- Python 3.10+ with `pip install tiktoken openai`10- Model provider API key for summarization (a cheap, fast model suffices)11- Known token budget of the target model (e.g., 128k window; plan for 60-70% utilization to reserve space)1213## Execution Steps141. Measure token count of the full context with the model's tokenizer, computing headroom against the budget while reserving tokens for the system prompt and expected output.152. Segment the context into compression units: per-turn conversation pairs, per-file code blocks, per-document sections.163. Classify each unit as verbatim (active task code, explicit constraints, accepted decisions, last N turns) or compressible (exploration output, verbose tool logs, already-resolved debugging).174. Summarize compressible units with a fixed extraction template (topic, outcome, constraints, open questions); prefer maps/diffs over free prose.185. Reassemble in order: pinned verbatim units first, followed by compact summaries, then the most recent verbatim turns; oldest-to-newest ordering preserves recency bias.196. Verify: compare total token count against budget and run a faithfulness check — does a fresh model answer key questions from the original content correctly using the compressed version?2021```python22import tiktoken23from openai import OpenAI2425enc = tiktoken.encoding_for_model("gpt-4o")26count = lambda s: len(enc.encode(s))2728TEMPLATE = ("Compress into terse notes. Keep: decisions, constraints, code identifiers, "29 "open questions. Drop: pleasantries, repetition, failed attempts.\n\n{text}")3031def compress(units: list[str], budget: int, client: OpenAI) -> list[str]:32 out, used = [], 033 for u in units:34 if count(u) <= 120: # keep short verbatim units as-is35 kept = u36 else:37 kept = client.chat.completions.create(38 model="gpt-4o-mini", temperature=0,39 messages=[{"role": "user", "content": TEMPLATE.format(text=u)}],40 ).choices[0].message.content41 if used + count(kept) > budget:42 break43 used += count(kept); out.append(kept)44 return out45```