Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 3

Building a Per-Step Context Assembler

Build a context assembler that rebuilds the prompt before each model call: static instructions and tool definitions first so caching works, then a progress summary, facts retrieved for this step and the last few turn groups, all within a fixed token budget.

Contentsand lesson path

What you will learn

  • Assemble each step's context from instructions, tool definitions, history, retrieved data and tool results within a token budget.

Prerequisites: Tokens & Context

01. Beyond Monolithic Transcripts: The Need for Just-in-Time Assembly

In simple chatbot applications, managing conversation history is trivial: you append each user message and assistant reply to an array and send the entire array on each API request. In multi-step autonomous agents, however, this monolithic transcript pattern quickly breaks down.

Autonomous agents interact heavily with external tools: reading file systems, querying vector databases, fetching REST APIs, and inspecting codebases. Tool outputs often contain verbose payloads—thousands of lines of JSON, stack traces, HTML fragments, or database tables. If an agent appends every tool observation to a growing message list, a few large results can fill the context window within a dozen turns. Before that, irrelevant data from early turns clutters the prompt, and the model can lose track of its original objective or invent arguments for later steps.

This lesson calls the fix a per-step context assembler. The name is ours, not an industry term; the wider practice is often called context engineering. Instead of treating the history as an append-only log, the runtime builds a fresh prompt before each model call. It takes pieces from separate stores (the fixed system rules, the progress on the plan, compacted facts from earlier steps and the most recent turns) and puts them together in a fixed order, within a token budget for each part.

Assembling context per step lets you decide what each token is for, which keeps prompts smaller and more relevant and gives you direct control over latency and cost.

02. The Four Stages of Context Assembly

A per-step assembler runs four stages, in this order, on every loop iteration:

  1. Fixed prefix. The persona instructions, safety rules and tool definitions, which do not change between iterations. Because this block is identical every time, providers can cache it. Cached input is billed at a fraction of the normal rate (on current Claude models, cache reads cost between 2.5% and 10% of the base input price depending on the model; OpenAI's discount is also model-dependent) and returns faster. Caching only applies above a minimum prefix length, and some providers charge a premium when the cache is first written.

  2. State summary. A short structured record of progress so far, instead of 30 raw past turns: the milestones completed, the key facts found, and the failed attempts not to repeat.

  3. Step context. Facts fetched from outside storage (a vector index or a key-value store), with the goal of the current step as the query. Only records that the next action needs go in.

  4. Recent turns. The last few turn groups (typically 2 to 4; a group is an assistant message with all of its tool results). They keep the conversation coherent and show the model the exact output of the latest tool call, without carrying the whole older history.

Accurate token budgeting during assembly is essential. Rough character counts (such as dividing string length by four) are fine for fast pre-checks. Within about 10% of the limit, use an exact count: the provider's token-counting endpoint (Anthropic messages.count_tokens, OpenAI responses.input_tokens.count), or the model's own tokenizer for open-weight models (Hugging Face tokenizers). A local tokenizer such as tiktoken counts plain text for OpenAI models only: it misses the tokens added by tool schemas and message formatting, and its counts are wrong for Claude, whose tokenizer is not published.

The Python implementation below builds the prompt in that order and enforces the input budget. Two rules matter. First, it trims history by whole turn groups: an assistant message that requested tools stays together with every tool result that answers it, because a tool result without its matching tool call is rejected by the API with HTTP 400 (the invariant from The Loop in Sixty Lines). Second, it never trims the fixed prefix; if even the newest turn does not fit, it raises CompactionRequired so the caller can summarise (lesson 03) instead of sending an oversized prompt.

Python · memory/context_assembler.py
import json
from typing import Dict, List

Message = Dict[str, object]


class CompactionRequired(Exception):
    """Even the newest turn does not fit: summarise or shrink step_context first."""


def estimate_tokens(message: Message) -> int:
    # Rough pre-check (~4 characters per token) over the whole message, so
    # tool_calls count too; use the provider's token counter near the limit.
    # Tool schemas sent with the request need their own budget line.
    return len(json.dumps(message)) // 4 + 4


def group_turns(turns: List[Message]) -> List[List[Message]]:
    """Units that must stay together: a user message, or an assistant message
    plus every tool result that answers its tool calls."""
    groups: List[List[Message]] = []
    for message in turns:
        if message["role"] == "tool":
            if groups and groups[-1][0]["role"] == "assistant":
                groups[-1].append(message)
            # else: an orphan tool result (its call was cut off) is dropped
        else:
            groups.append([message])
    return groups


class PerStepContextAssembler:
    def __init__(self, context_window: int, max_output_tokens: int, max_groups=4):
        self.max_input_tokens = context_window - max_output_tokens
        self.max_groups = max_groups

    def count(self, messages: List[Message]) -> int:
        return sum(estimate_tokens(m) for m in messages)

    def assemble_prompt(self, system_prompt: str, state_summary: str,
                        step_context: str, recent_turns: List[Message]):
        # Stages 1-3: static prefix first (cacheable), then state and retrieval
        fixed: List[Message] = [{"role": "system", "content": system_prompt}]
        fixed.append({"role": "system", "content": f"Task state:\n{state_summary}"})
        if step_context.strip():
            fixed.append({"role": "system", "content": f"Retrieved:\n{step_context}"})
        # Stage 4: recent turns, trimmed by whole groups from the oldest end
        groups = group_turns(recent_turns)[-self.max_groups:]
        while groups and self.count(fixed + sum(groups, [])) > self.max_input_tokens:
            groups.pop(0)  # never touches the fixed prefix
        messages = fixed + sum(groups, [])
        too_big = self.count(messages) > self.max_input_tokens
        if too_big or (recent_turns and not groups):
            raise CompactionRequired(f"{self.count(messages)} tokens before turns; "
                                     f"budget {self.max_input_tokens}")
        return messages

Check the edge cases before you trust it. Save this next to the assembler and run python3 demo_assembler.py. It covers an empty history, turns too large for the budget, a history slice that starts with an orphan tool result, and a retrieval block so large that nothing fits.

Python · memory/demo_assembler.py
from context_assembler import CompactionRequired, PerStepContextAssembler

asm = PerStepContextAssembler(context_window=8192, max_output_tokens=2000)
SYSTEM = "You are a billing agent. " * 20
call = {"role": "assistant", "content": "", "tool_calls": [{"id": "c1"}]}
result = {"role": "tool", "tool_call_id": "c1", "content": "row " * 1500}
turns = [{"role": "user", "content": "x " * 6000}, call, result,
         {"role": "assistant", "content": "y " * 4000},
         {"role": "user", "content": "Refund order 42?"}]

msgs = asm.assemble_prompt(SYSTEM, "step 3 of 5", "", [])
print("no turns:", [m["role"] for m in msgs])
msgs = asm.assemble_prompt(SYSTEM, "step 3 of 5", "", turns)
print("big turns:", [m["role"] for m in msgs], asm.count(msgs), "tokens")
msgs = asm.assemble_prompt(SYSTEM, "step 3 of 5", "", turns[2:])
print("orphan tool result dropped:", [m["role"] for m in msgs])
try:
    asm.assemble_prompt(SYSTEM, "step 3 of 5", "doc " * 7000, turns)
except CompactionRequired as exc:
    print("CompactionRequired:", exc)
Expected output
no turns: ['system', 'system']
big turns: ['system', 'system', 'assistant', 'tool', 'assistant', 'user'] 3720 tokens
orphan tool result dropped: ['system', 'system', 'assistant', 'user']
CompactionRequired: 7170 tokens before turns; budget 6192

The system prompt survives an empty history. With large turns, the oldest user message is dropped as a whole group, and the assistant tool call is kept together with its tool result. A slice that starts with a tool result loses that result instead of sending an invalid sequence. When the fixed part alone is over budget, the assembler refuses rather than truncating the system prompt.

03. Enforcing Context Hygiene and Cache Maximization

A per-step assembler has to balance two goals that pull against each other: giving each step the context it needs, and keeping the start of the prompt the same on every call so that the provider can cache it.

Providers bill cached input tokens at a discount that differs by provider and model (on current Claude models cache reads cost 2.5% to 10% of the base input price and cache writes 1.25 times it for the default 5-minute lifetime; OpenAI's discount also depends on the model), so check the current pricing pages for the models you use. However, prompt caching algorithms rely on exact prefix matching: every token from the beginning of the prompt up to the cache boundary must match previous calls bit-for-bit. If your assembler injects dynamic content—such as Step 14/50 or Timestamp: 15:32:01—into the system prompt or early in the message list, every single token following that dynamic insertion becomes a cache miss. A stable prefix is also cached only above a minimum length: 512 tokens on current Claude models and 1,024 on OpenAI GPT-5.6 and later, so a short system prompt alone may never show cached tokens.

To keep the cache hits, order the prompt from the parts that never change to the parts that change on every step:

  • Top, never changes: the system prompt, the role of the agent and the tool definitions.

  • Middle, changes now and then: the goal and the checklist, which change only when a milestone is done.

  • Bottom, changes on every step: the snippets retrieved for this step, the current tool arguments and the latest tool result.

Another operational consideration is handling multi-modal or large structured artifacts. If an agent inspects an image or downloads a 200-row CSV file, the assembler should not inject the entire raw artifact directly into recent turns. Instead, store the raw asset in object storage (such as S3 or a local artifacts directory), pass an abbreviated statistical schema or visual description to the model, and let the model query specific segments via targeted tools.

With this ordering the static prefix stays cached across the turns of a run, as long as each call arrives within the cache lifetime (5 minutes by default on Claude, longer on OpenAI). That cuts cost and latency while the dynamic layer still changes freely on every step.

04. Practice

Practice check · 3 questions

Practice Check

Answer the following scenario-based questions to verify your understanding.

Q1. The assembler must drop history to fit its budget. The oldest turn is an assistant message with two tool calls plus their two results. What should it drop?
Q2. The retrieved block alone is larger than the input budget. What should this lesson's assembler do?
Q3. Your static prefix is 400 tokens and identical on every call, yet the bill shows no cached tokens. What is the likely reason?
Practice only: not graded, not saved, not evidence.

05. Apply it

When you build a per-step assembler for your own agent:

  • Keep the top of the prompt identical on every turn, so that it stays cached.
  • Keep a short ledger of finished steps, facts found and failed attempts, and send it instead of replaying every old message.
  • Send only the last 2 to 4 turn groups (an assistant message with all of its tool results) word for word.
  • Give retrieved chunks a token limit, and trim or summarise search results before they go into the prompt.
  • Log the cache-read and cache-write token counts of every step, so that you notice when a change to the prefix stops the cache from working.

With this pipeline, an oversized prompt raises an error before the call instead of failing at the provider, each step sees only what it needs, and the cache metrics show when a prefix change starts costing money.

06. Review prompt

Describe how sending the whole history on every call harms an agent on a long task. Outline the four stages of a per-step context assembler, and explain why ordering the prompt from the parts that never change to the parts that change on every step raises the cache hit rate while each step still gets fresh context.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check