DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Using Middleware in LangChain: Recovering From Tool Failures
  • AI Coding Agent Guardrails: Finding Gaps in Tool Permissions
  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software
  • 5 Identity Patterns Your AI Agents Need Before They Touch Production

Trending

  • Using Middleware in LangChain: Recovering From Tool Failures
  • Vision-Language Models in 2026: From Research Breakthroughs to Cloud-Native Production Systems
  • To Switch, or Not to Switch the AI Model
  • LangChainGo vs Genkit Go: Where Genkit Shines

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. AI/ML
  4. What's Really in an Agent's Context Window

What's Really in an Agent's Context Window

deepagents' /context-doctor estimates context before any model call. I compared it to real `usage_metadata` from a live run to see how the numbers relate.

By 
Ninaad Rao
DZone Core CORE ·
Nov. 27, 26 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
93 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Context Engineering Needs a Way to Measure Itself

"Context engineering" is the phrase doing the most work in agentic-AI discourse right now. The idea is that what you inject into a model's context window (system prompt, memory, tools, prior turns) matters as much as the model itself, and that letting it grow unmanaged degrades an agent long before it runs out of room. The natural next question for anyone building on this is: how do I know what I'm actually sending?

deepagents-code (dcode) ships an answer: /context-doctor, a read-only command that audits a session and reports an estimated token cost per component: system prompt, project memory, skills, tool schemas, MCP servers without ever calling the model. It shipped in PR #5830 and was recently ported to Talon, the project's Discord bot, in PR #6557, which is what put it back on my radar.

I wanted to see how a zero-cost, no-model-call estimate actually relates to what a live request really bills. So I ran it on this exact repository, sent one real message, and checked the number against what Anthropic reported back.

What /context-doctor Measures, and How

The estimator is one function, used everywhere in the report:

Python
 
# libs/code/deepagents_code/context_doctor.py:41-47
def estimate_text_tokens(text: str) -> int:
    """Estimate tokens using the same four-characters-per-token rule as whip.

    Returns:
        Estimated token count.
    """
    return math.ceil(len(text) / 4)


build_context_doctor_report (same file, line 177) runs every component through it: the resolved system prompt, the formatted AGENTS.md memory block, the skills index, and the compact-JSON serialization of every built-in and MCP tool schema. Each becomes one row. When a live checkpoint exists, two more rows appear, and this is the detail that makes the tool genuinely self-auditing rather than just self-reported:

Python
 
# libs/code/deepagents_code/context_doctor.py:259-269
if report.provider_tokens is not None:
    explained = report.injected_tokens + (report.conversation_tokens or 0)
    remainder = report.provider_tokens - explained
    provider_label = "Provider-reported context"
    delta_label = "Unattributed / estimation delta"
    lines.extend(
        [
            f"{provider_label:<{width}}  {report.provider_tokens:>11,}",
            f"{delta_label:<{width}}  {remainder:>+11,}",
        ]
    )


When the last assistant message carries real usage_metadata, the report subtracts its own estimate from what the provider actually reported and shows you the difference, right there in the output. That's a nice design choice where most estimators just print a number and let you assume it's exact. This one tells you, in the same breath, how far off it might be once there's real data to check against. I wanted to see what that comparison actually looks like in practice.

Running It for Real

I started a real dcode session in this repo (libs/code), with its real AGENTS.md, two configured MCP servers (docs-langchain, reference-langchain), and the skills this very session already had loaded. First command, before any conversation:

Shell
 
Fresh-session context audit (estimated tokens)

System prompt (base)                     ~2,634
AGENTS.md memory (2 files)               ~3,867
Skills index (4 loaded)                  ~1,230  largest: skill-creator ~186, deepagents-thread-inspector ~134, remember ~112, textual-screenshot ~98
Built-in tool schemas (15 tools)         ~4,630  sent with every request
MCP: docs-langchain (3 tools)            ~1,364
MCP: reference-langchain (2 tools)         ~314
TOTAL injected before conversation  ~    14,039

Approximate: section counts use about four characters per token.
Trim skills or disable an MCP server, then run /context-doctor again.


Then I sent one real message: "In one sentence, what does this repo's libs/deepagents package do?" and let it run. It made one tool call (read_file on libs/deepagents/README.md) and answered. Real cost, from dcode's own status bar:

Shell
 
Cache 49% hit • 29K read / 30K write
Context: 3% / Tokens: 30.1K • $0.21


Then /context-doctor again, same session:

Shell
 
Fresh-session context audit (estimated tokens)

System prompt (base)                     ~2,634
AGENTS.md memory (2 files)               ~3,867
Skills index (4 loaded)                  ~1,230  largest: skill-creator ~186, deepagents-thread-inspector ~134, remember ~112, textual-screenshot ~98
Built-in tool schemas (15 tools)         ~4,630  sent with every request
MCP: docs-langchain (3 tools)            ~1,364
MCP: reference-langchain (2 tools)         ~314
TOTAL injected before conversation  ~    14,039
Conversation history                ~       701
Provider-reported context                30,064
Unattributed / estimation delta         +15,324

Approximate: section counts use about four characters per token.
Trim skills or disable an MCP server, then run /context-doctor again.


The report itself flags a 15,324-token "unattributed/estimation delta" larger than its own injected-context estimate. The tool is upfront about this being possible; I wanted to understand where that number actually comes from.

Reading the Real usage_metadata

Rather than guess, I pulled the actual checkpoint, using Deep Agents' built-in deepagents-thread-inspector skill -> the same tool anyone can point at ~/.deepagents/.state/sessions.db and a thread ID:

Shell
 
python3 "$SKILL_DIR/scripts/inspect_sessions.py" 01a192d4-1148-7b02-a0ba-4033b82f03fd --mode transcript


That gets you a clean transcript, but it deliberately strips reasoning/thinking blocks for privacy (inspect_sessions.py:399-402). To see the raw usage_metadata on every message, I imported its lower-level loader directly instead of shelling out:

Python
 
import importlib.util

spec = importlib.util.spec_from_file_location(
    "inspect_sessions",
    "deepagents_code/built_in_skills/deepagents-thread-inspector/scripts/inspect_sessions.py",
)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)

conn = mod._connect_read_only(mod._default_db_path())
thread_id = mod._resolve_thread_id(conn, "01a192d4-1148-7b02-a0ba-4033b82f03fd")
messages = mod._reconstruct_messages(conn, thread_id, [])
for m in messages:
    print(type(m).__name__, getattr(m, "usage_metadata", None))


The real per-call numbers:

Call Message input_tokens cache_creation cache_read output_tokens
1 AI - decides to call read_file 29,014 29,008 0 124
2 AI - final answer 29,972 963 29,008 92


Call 1 is the one that matters. At that point, "conversation" is nothing but a 66-character human question - call it 20 tokens by any formula. Everything else in that 29,014-token input is the static prefix: system prompt, memory, skills, built-in tools, MCP tools. Anthropic wrote essentially all of it fresh to cache (cache_creation: 29,008, cache_read: 0  a brand-new thread, nothing to reuse yet). Call 2, moments later, reads nearly that entire prefix back from cache (cache_read: 29,008) and pays full price only for the ~963 new tokens the first turn's tool-call-and-result added, which lines up with the "Conversation history ~701" row being roughly the right order of magnitude. 29,972 + 92 = 30,064, exactly the figure /context-doctor printed as "Provider-reported context."

So the same static content /context-doctor estimated at 14,039 tokens is what Anthropic actually billed ~29,008–29,014 tokens to write to cache, the first time it saw it. That's the real relationship between a free, pre-call estimate and a live billed total, read straight off usage_metadata rather than projected.


Where the Estimate's Numbers Actually Come From

One possibility is that some middleware injects system text /context-doctor doesn't have a row for -> TodoListMiddleware, SubAgentMiddleware's task-tool description, HITL instructions, content the tool's own disclaimer already names as out of scope ("Middleware additions and provider overhead are not included"). Before attributing the delta to that, I checked whether the rows the report does compute reproduce cleanly, by calling the exact same internal helpers app.py's /context-doctor handler calls (_handle_context_doctor_command, app.py:13771), with the live session's real config:

Python
 
from deepagents_code.agent import get_system_prompt

prompt = get_system_prompt(
    assistant_id="agent", sandbox_type=None, interactive=True,
    cwd=Path("/Users/ninaadrao/Documents/opensource/forked/deepagents/libs/code"),
    fs_tools=None,
)
len(prompt), math.ceil(len(prompt) / 4)
# (10293, 2574)  — the live report said ~2,634. Matches.
Python
 
from deepagents_code.context_doctor import format_memory_prompt
from deepagents.middleware.memory import MEMORY_SYSTEM_PROMPT
# ... load the real AGENTS.md ...
memory_prompt = format_memory_prompt(contents, MEMORY_SYSTEM_PROMPT)
len(memory_prompt), math.ceil(len(memory_prompt) / 4)
# (15467, 3867) — the live report said ~3,867. Exact match.


Both reproduce the live numbers exactly. The report is summing real, correctly-collected content including all 15 tool schemas: build_context_doctor_report only prints "sent with every request" (rather than "N of M schemas available") when every schema serialized successfully, which is exactly what the live report showed.

So the rows are internally consistent. What they share is the formula. count_tokens_approximately - the function that produces the "Conversation history" row carries the identical constant as its own default, and says so in its own docstring:

Python
 
# langchain_core/messages/utils.py
def count_tokens_approximately(
    messages: Iterable[MessageLikeRepresentation],
    *,
    chars_per_token: float = 4.0,
    ...
) -> int:
    """...
    chars_per_token: Number of characters per token to use for the approximation.
        One token corresponds to ~4 chars for common English text.
    ...
    """


"Common English text." The single largest row in the report built-in tool schemas, ~4,630 of the 14,039 estimated tokens is the opposite of that: 17,965 characters of compact, whitespace-stripped JSON ({"type":"function","function":{...), the kind of punctuation-dense, low-redundancy text that a real BPE tokenizer packs more densely than four characters per token. AGENTS.md memory and the skills index sit somewhere in between. Both of the report's formulas share one constant, calibrated for the one kind of text that makes up the smallest share of what a coding agent actually injects.

I can't cleanly split the 15,324-token delta by row without an independent, standalone Anthropic tokenizer call on each component in isolation - I don't have one. What I can show, precisely, is that /context-doctor's two formulas agree with each other (char-count math checked against char-count math), and that the one place I have independent ground truth: real usage_metadata from the actual API that says the true number for the same content runs meaningfully higher.

Takeaways

The interesting part here isn't that a fast, no-model-call estimate diverges from a live token count. Any estimator that skips a real tokenizer will, by construction,  /context-doctor says so in its own closing line. What's worth learning from is the design: the "Provider-reported context" and "Unattributed / estimation delta" rows mean the tool checks itself the moment real data becomes available, instead of printing one number and letting you assume it's exact. count_tokens_approximately even ships a use_usage_metadata_scaling parameter built for exactly this kind of self-correction. 

The broader lesson travels past this one tool: a context estimate computed before a model call is necessarily calibrated on some assumed content mix — plain English prose, in this case and knowing how far your own injected context (tool schemas, markdown, structured memory) drifts from that assumption is the useful thing to check, in any framework, not just this one.

AI Tool

Opinions expressed by DZone contributors are their own.

Related

  • Using Middleware in LangChain: Recovering From Tool Failures
  • AI Coding Agent Guardrails: Finding Gaps in Tool Permissions
  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software
  • 5 Identity Patterns Your AI Agents Need Before They Touch Production

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook