LevelUpWith

Explore / Context Engineering and Memory for LLM Agents / Lesson 2

Lesson 2: Anatomy of an Agent Request

Take apart a real agent call into its parts (system prompt, tool definitions, conversation history, tool results and the user turn) and log how many tokens each part uses.

Free to read, no account needed. Part of Context Engineering and Memory for LLM Agents.

By the end of this level you'll be able to

  • Wrap an agent's model client so that every request records a per-part token ledger
  • Find which parts of a coding agent's context grow with each turn and which stay fixed
  • Read the usage fields that each provider returns and match them against your own counts

Why take a request apart?

When you call a model from an agent, it feels like you're sending "a message". You're actually sending a whole bundle, and the full bundle goes out again on every turn. The model has no memory between calls. Each request re-sends everything the model needs to see.

Think of it like a shipping container. Before you can make the load lighter, you need a packing list showing what's inside and how heavy each item is. This level builds that packing list: a per-part token ledger.

Every agent request is made of five parts:

Part What it is How it behaves over a session
System prompt Instructions, persona, rules Fixed (unless you template it)
Tool definitions Names, descriptions, JSON schemas Fixed (unless you add or remove tools)
Conversation history Earlier user and assistant messages, including the model's tool calls Grows every turn
Tool results File contents, command output, search hits fed back in Grows, often in big jumps
User turn The newest message Varies

The split between fixed and growing parts matters more than anything else in that table. Fixed parts cost the same on turn 1 and on turn 40. Growing parts are why a coding agent that reads a few files ends up with a huge request.

Walkthrough 1: a ledger wrapper (Python)

We'll measure each part with one fixed local tokenizer, used as a ruler. The ruler won't match every provider's tokenizer exactly. That's fine, because we only need consistent relative sizes, and we'll check the totals against the provider afterwards.

import json, tiktoken

enc = tiktoken.get_encoding("o200k_base")  # one ruler for every provider

def toks(obj) -> int:
    # Strings are measured directly; schemas and content blocks as JSON
    text = obj if isinstance(obj, str) else json.dumps(obj, ensure_ascii=False)
    return len(enc.encode(text))

def kind(msg) -> str:
    # Anthropic-style: tool results arrive as user messages with tool_result blocks
    c = msg["content"]
    if isinstance(c, list) and any(b.get("type") == "tool_result" for b in c):
        return "tool_results"
    return "history"

def ledger(system, tools, messages) -> dict:
    parts = {"system": toks(system), "tools": toks(tools),
             "history": 0, "tool_results": 0, "user_turn": 0}
    for m in messages[:-1]:
        parts[kind(m)] += toks(m["content"])
    last = messages[-1]  # the newest message: a fresh user turn or a tool result
    parts["user_turn" if kind(last) == "history" else "tool_results"] += toks(last["content"])
    return parts

class LedgerClient:
    """Wraps a client; every request appends one JSON line to ledger.jsonl."""
    def __init__(self, client, path="ledger.jsonl"):
        self.client, self.path, self.turn = client, path, 0

    def create(self, **req):
        est = ledger(req.get("system", ""), req.get("tools", []), req["messages"])
        resp = self.client.messages.create(**req)
        u = resp.usage
        # Anthropic splits input three ways; add them up for the full input size
        reported = (u.input_tokens + (u.cache_creation_input_tokens or 0)
                    + (u.cache_read_input_tokens or 0))
        self.turn += 1
        row = {"turn": self.turn, **est, "est_total": sum(est.values()),
               "reported_input": reported, "output": u.output_tokens}
        with open(self.path, "a") as f:
            f.write(json.dumps(row) + "\n")
        return resp

Gotcha: SDK responses hold typed objects, not dicts. When you append resp.content to your history, convert it first (for example [b.model_dump() for b in resp.content]), or json.dumps will fail.

Here's what a small coding-agent session might produce (illustrative numbers):

turn system tools history tool_results user_turn est_total reported_input
1    1210   2380  0       0            42        3632      4105
2    1210   2380  160     3900         0         7650      8320
3    1210   2380  410     9850         0         13850     14940
4    1210   2380  700     10300        35        14625     15790

Read it column by column. system and tools never change: together they're a fixed cost of about 3.6k tokens on every call. tool_results grows fastest, because every file the agent reads stays in the history. You'll usually see a pattern like this.

Walkthrough 2: reading each provider's usage fields (TypeScript)

The providers report input differently, and the gaps are easy to miss. The biggest one is whether cached tokens are included in the main input number.

type Usage = { input: number; cached: number; output: number };

// Anthropic Messages: input_tokens counts only tokens AFTER the last cache
// breakpoint, so add cache writes and cache reads back in.
function fromAnthropic(u: any): Usage {
  const cached = (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
  return { input: u.input_tokens + cached, cached, output: u.output_tokens };
}

// OpenAI Responses: input_tokens already INCLUDES cached_tokens (and cache writes).
function fromOpenAI(u: any): Usage {
  return { input: u.input_tokens, cached: u.input_tokens_details?.cached_tokens ?? 0,
           output: u.output_tokens }; // includes output_tokens_details.reasoning_tokens
}

// Gemini generateContent: promptTokenCount INCLUDES cachedContentTokenCount.
// Thinking tokens are reported separately from candidates.
function fromGemini(m: any): Usage {
  return { input: (m.promptTokenCount ?? 0) + (m.toolUsePromptTokenCount ?? 0),
           cached: m.cachedContentTokenCount ?? 0,
           output: (m.candidatesTokenCount ?? 0) + (m.thoughtsTokenCount ?? 0) };
}

If you read Anthropic's input_tokens on its own once caching is switched on, the number looks tiny. That's not a saving. It just leaves out the cached tokens. Write a normaliser like this once, and log the raw usage object next to it. Open-weight servers report usage in their own formats, so check the docs for your server before you trust its numbers.

Why your total never matches theirs

In the table above, est_total sits 10–15% below reported_input. That's normal, and it has three causes:

  • Hidden framing. Providers wrap your parts in their own templates. With tools enabled, Anthropic adds a tool-use system prompt that you never see. Its size depends on the model: 286 tokens for Claude Opus 5.5 with tool_choice auto.
  • Different tokenizers. Your ruler isn't the model's tokenizer. Anthropic says Claude Opus 4.7 and later models produce roughly 30% more tokens than earlier models for the same text.
  • Estimates. Even the official counters are estimates. Anthropic's counter can include tokens the system adds, which you aren't billed for.

When you want an exact number for a single part, use the provider's counting endpoint. Anthropic has client.messages.count_tokens(...), which is free but rate-limited. OpenAI has POST /v1/responses/input_tokens. Gemini has client.models.count_tokens(...). To measure the tools on their own, count the request with them and without them, then subtract.

Best practice: Treat the provider's usage as the truth for totals, and your ledger as the truth for proportions. If the gap between them suddenly jumps, something you can't see changed, such as a new SDK version, a different model or new tools.

Hands-on exercise

  1. Wrap the client of a small tool-using agent with LedgerClient (or write a TypeScript port). Give it at least read_file and list_dir tools.
  2. Run a 6-turn task, such as "find where config is loaded and explain it".
  3. Chart each column of ledger.jsonl against the turn number. Label each part as fixed or growing.
  4. Work out reported_input - est_total for each turn. Is the gap steady, or does it grow with the number of turns?
  5. Bonus: run the same task on a second provider and normalise both with the functions above.

Key takeaways

  • An agent request has five parts: system prompt, tool definitions, history, tool results and the user turn. All five are re-sent on every call.
  • System prompt and tools are a fixed cost on every turn. History and tool results grow, and tool results usually grow fastest.
  • Measure the parts with one consistent ruler, then check the totals against the provider's usage.
  • Anthropic's input_tokens leaves out cached tokens. OpenAI's input_tokens and Gemini's promptTokenCount include them.
  • A steady gap between your count and the reported count is normal, caused by hidden templates and tokenizer differences. A sudden change in the gap means something changed.

A 6-question knowledge check follows this lesson in the app, free and without an account.

Keep going: levels 3 and 4 are free

Create a free account to open the next two levels, try the AI tutor, save your progress and pick up where you left off. No card needed.

Next: Level 3, Input Tokens Drive Cost and Latency.

Create a free account →See the whole course

More like this