Profiling an AI agent’s context window: where the tokens actually go

When an agent’s requests get slow, expensive, or less accurate, the cause is often a context window packed with repeated or irrelevant content. ctxlens is a dependency-light CLI that parses session transcripts and attributes every token to a segment so you can see what to trim and how much you might save.

Key takeaways

  • ctxlens parses agent session transcripts and assigns every message to one of seven segments to show where tokens are spent.
  • It flags four sources of avoidable tokens: duplicates, tool-result bloat, stale tool outputs, and tool-definition overage, and reports estimated savings.
  • Default token counts use a fast heuristic; enable tiktoken for exact BPE counts when billing parity is required.
  • The CLI supports CI integration (fail-on-ratio), JSON output, diffing runs, and HTML reports for human review.
  • ctxlens quantifies token waste but does not automatically produce compaction edits; suggested compaction plans were proposed as an extension.

Quick summary: what ctxlens does

ctxlens treats an agent session like a CPU profiler treats a program: it parses a transcript, assigns each message to a fixed set of segments, counts tokens per segment and per turn, and runs deterministic, rule-based checks to flag avoidable tokens. It supports Claude Code JSONL sessions, OpenAI rollout sessions and generic OpenAI chat arrays; format detection is automatic but can be forced with a flag.

How the analysis is organized

Every message is placed into one of seven buckets: system, tool_definitions, user, assistant, thinking, tool_call, and tool_result. Once tokens have homes, you can answer practical questions: which segment dominates the window, when did the context spike, and what is paid on every turn versus once.

Waste categorization

ctxlens reports a waste_ratio = total_waste / total_tokens. Total waste is the sum of four disjoint sources, each with a clear, deterministic definition:

  • Duplicate tokens: exact-body duplicates or repeated references (for example Read:file_path=config.py). Every copy after the first counts as waste.
  • Tool-result bloat: tokens in a tool result above a per-result cap (default 400). Only the over-cap portion counts, and each unique result is charged once.
  • Stale tool outputs: when an earlier read is superseded by a later read of the same reference, the older copy is considered dead weight.
  • Tool-definition overage: tool schema tokens above a budget (default 800). These are notable because tool definitions often recur and are effectively paid on every turn.

What the CLI looks like in practice

Install and run the analyzer as a simple one-liner:

<code>pip install ctxlens-cli
ctxlens analyze session.jsonl</code>

Output includes a summary panel, a breakdown of context composition by segment, sparklines showing how context grew over the run, and a list of actionable recommendations. Recommendations quantify potential savings; for example, the tool will report an exact estimate like “‘Read:file_path=config.py’ appears 6 times, ~2,410 tokens” rather than vague advice.

Usage patterns that commonly show up

According to the tool’s author, tool_result is the segment that surprises most users: large tool outputs commonly occupy the largest share of the context and are frequently avoidable because they matter for only one turn. The composition view immediately highlights this: you’ll see token counts and percentage share for each segment so you can focus edits where they matter.

CI and reporting: integrating ctxlens into development workflows

Because the heuristics are deterministic and the analyzer is script-friendly, ctxlens is designed to fit into CI pipelines. You can fail a build when a captured session’s waste ratio exceeds a threshold:

<code>ctxlens analyze session.jsonl --fail-over-ratio 0.30</code>

The CLI uses exit codes to indicate status: 0 means within threshold, 2 means the threshold was exceeded, and 1 means an error. For machine-readable output there is a –json flag, and you can compare runs with ctxlens diff before.jsonl after.jsonl to detect regressions after a prompt or tool change. There is also HTML reporting via ctxlens report session.jsonl –html -o report.html for interactive review.

Token counting: heuristic by default, exact with tiktoken

By default ctxlens employs a deterministic heuristic tokenizer that avoids network calls and heavy dependencies. This design choice aims for reproducible relative profiling in CI and fast local runs rather than provider-billing precision. If you need counts that match a provider’s BPE billing, installing tiktoken activates an exact tokenizer with the –tokenizer auto option.

The author stresses that the heuristic is an approximation: percentages, dominance of segments, duplicate detection and spikes are reliable without tiktoken, but absolute token numbers should be treated as estimates unless you enable exact BPE counting.

When ctxlens flags waste, common remediation strategies include:

  • Deduplicate reads: avoid re-reading the same file or tool result multiple times; cache a single canonical reference and reuse it.
  • Cap or summarize large tool results: if a 12k-token tool output is only needed for one turn, replace it with a short summary for subsequent turns or store the full output outside the context window and recall it via a link or reference token only when necessary.
  • Prevent schema churn: avoid re-sending large tool schemas on every turn; load them once or send a compact schema reference instead.
  • Prune stale outputs: remove earlier reads that have been superseded by later ones so only the most recent copy remains in the window.

Limitations and unresolved points

ctxlens is explicit about its limits. The default tokenizer is intentionally approximate and will not match provider billing exactly; that is a design trade-off for speed and reproducibility. Estimates for token savings are arithmetic calculations based on the tool’s rules rather than predictions about downstream model behavior or accuracy improvement.

The tool flags waste and quantifies potential token savings, but the current evidence does not show automated compaction (for example, producing a suggested edit that replaces a large result with a summary). The author mentions the idea of emitting suggested compaction plans — drop these segments or summarize those — as a possible extension, but that is not described as a shipped feature.

Timeline and provenance

The analysis and feature descriptions come from the ctxlens project announcement and documentation. The GitHub repository is published as AgentPostmortem/ctxlens and the package available on PyPI as ctxlens-cli. The tool’s CLI flags, defaults and exit-code behavior are documented in the announcement and shipped CLI.

Who should try this

ctxlens is aimed at engineers and teams running multi-step agents who want a deterministic, CI-friendly way to understand where tokens in their context windows are going. It is particularly useful when you suspect repeated file reads, oversized tool outputs or tool-definition churn are inflating costs and latency.

Troubleshooting and common mistakes

  • Expect approximate counts by default. If your aim is billing parity, install tiktoken and enable the exact tokenizer.
  • Make sure you point ctxlens at a real session transcript (Claude JSONL or OpenAI formats) — format auto-detection usually works but can be overridden with –format.
  • Interpret recommendations as token accounting actions, not model-performance guarantees. Removing tokens reduces cost and request size, but effects on model accuracy are context-dependent and not predicted by ctxlens.

Bottom line

ctxlens fills a practical gap between raw token dashboards and manual transcript inspection by attributing tokens to semantic segments and providing deterministic, rule-based waste estimates. For teams running agents, it makes the invisible taxes in a context window visible and actionable, and it is designed to slot into CI so regressions in context bloat can be caught automatically.

Stay in Touch

spot_img

Related Articles