Module 3 · Communication & protocols

Managing and compressing inter-agent context

5 min read

Context is the most precious — and most wasted — resource in a multi-agent system. Every useless token costs money, adds latency and, above all, dilutes the model's attention. An agent drowning in irrelevant information reasons worse. This lesson covers what each agent should see, and the tools to keep context under control.

The minimal sufficient context principle

For each agent, ask: what does it need to do its job well — and nothing else?

Atlas agentSeesDoesn't see
PlannerThe questionThe documents
ResearcherIts sub-question, its documentsThe global question, other researchers
WriterThe question, the researchers' summariesThe raw documents
CriticThe question, the noteThe raw documents, the version history

The writer never reads raw documents: it works from compact, sourced summaries. Here is how it builds its context:

notes = "\n\n".join(
    f"### {f['subquestion']}\n{f['summary']}\n(sources: {', '.join(f['source_ids']) or 'none'})"
    for f in state["findings"]
)
prompt = f"Question: {state['question']}\n\nResearch notes:\n{notes}"

Three researchers may have read nine documents; the writer receives three structured paragraphs. That's context isolation: the main reason sub-agents exist (lesson 1.3).

Pass summaries, not transcripts

The naive reflex is to pass the next agent the whole conversation of the previous one. That's rarely a good idea:

  • the transcript contains fumbling, corrected mistakes, bulky tool results;
  • the next agent may adopt hypotheses that were abandoned;
  • cost grows with each step.

Instead, require each agent to produce a structured deliverable (lesson 3.1) containing only what the next one needs to know. If a detail is missing, the contract is incomplete: enrich the schema rather than opening the floodgates.

Measure before optimizing

The SDK lets you count a request's tokens before sending it:

count = client().messages.count_tokens(
    model=MODEL,
    system=SYSTEM_WRITER,
    messages=[{"role": "user", "content": prompt}],
)
print(count.input_tokens)

Instrument this count for each type of agent during development: you'll often find that a single agent accounts for most of the volume.

Long-running agents: three mechanisms

Summaries handle context passing between agents. But an agent working for a long time (dozens of tool calls) sees its own history grow. Three complementary mechanisms:

1. Context editing: removing what's no longer needed

Old tool results often become useless (a search whose essentials have already been extracted). The API can clear them automatically from the history before the model reads it:

response = client().beta.messages.create(
    model=MODEL,
    max_tokens=16000,
    betas=["context-management-2025-06-27"],
    context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
    tools=TOOLS,
    messages=messages,
)

2. Compaction: summarizing when approaching the limit

When a conversation approaches the context limit, server-side compaction automatically summarizes older exchanges:

response = client().beta.messages.create(
    model=MODEL,
    max_tokens=16000,
    betas=["compact-2026-01-12"],
    context_management={"edits": [{"type": "compact_20260112"}]},
    messages=messages,
)
messages.append({"role": "assistant", "content": response.content})  # FULL content

Critical point: always append response.content in full to the history. The response may contain a compaction block that the API reuses on the next turn; keeping only the text would silently lose the compacted state.

3. External memory: what must survive the session

Whatever must persist beyond the conversation (decisions, established facts, preferences) goes into external memory: the LangGraph store (lesson 2.3) or the API's memory tool. The agent deliberately writes what it considers important, and reads it back on demand.

MechanismScopeEffect
Context editingOne conversationRemoves stale tool results
CompactionOne conversationSummarizes older history
External memoryAcross sessionsDeliberately keeps the essentials

Prompt caching: paying once for stable context

In a multi-agent system, the same system instructions are sent hundreds of times. Prompt caching means you only pay full price once for an identical prefix — subsequent reads cost a fraction of the price.

Caching works by prefix match: any changed byte invalidates everything after it. Design rules:

  1. Stable first: tools, then frozen system instructions, then variable content.
  2. Nothing volatile in the prefix: no timestamps, request IDs, or tool lists that change from call to call.
  3. One model per agent: the cache is per model; switching models mid-conversation starts from scratch.

The simplest form enables automatic caching on the request:

response = client().messages.create(
    model=MODEL,
    max_tokens=16000,
    cache_control={"type": "ephemeral"},
    system=SYSTEM_WRITER,           # stable prefix, identical on every call
    messages=[{"role": "user", "content": prompt}],
)
print(response.usage.cache_read_input_tokens)  # > 0 from the second call if the cache works

Always check cache_read_input_tokens: if it stays at zero across repeated calls, something variable has slipped into the prefix. Also note that a prefix that is too short won't be cached: the gains show up on substantial instructions and contexts.

Key takeaways

  • Each agent gets the minimal sufficient context; sub-agents exist first and foremost to isolate context.
  • Pass structured summaries, not transcripts.
  • For long-running agents: context editing (remove), compaction (summarize), external memory (persist).
  • Prompt caching rewards stable prefixes: stable first, nothing volatile, one model per agent.

Hands-on

  1. Add a token count (count_tokens) before each writer and critic call; which one consumes the most?
  2. Change the researcher to pass raw documents instead of a summary. Compare the size of the writer's context.
  3. Enable caching on the critic and check cache_read_input_tokens on two successive calls.

Resources