Library

Volume 2 · Agentic AI Systems

Notebook
Sign in

Section 33

Context Management & Window Management

748 words · about 3 min

33.1 The Core Problem

A complex agent task can generate 50K+ tokens of reasoning trace, far exceeding a manageable context window (even against large context-window models, unbounded growth degrades latency, cost, and — often — reasoning quality, since models attend less reliably to information buried deep in a very long context).

33.2 Strategy 1 — Structured State Object

Maintain a compact, typed JSON state object and pass that to each agent invocation instead of the full transcript:

{
  "incident_id": "INC-2024-1234",
  "summary": "Payment processing failures affecting checkout",
  "severity": "P1",
  "timeline": [
    {"time": "14:00", "event": "First alert received"},
    {"time": "14:05", "event": "Blast radius: 3 services affected"}
  ],
  "hypotheses": [
    {"id": 1, "description": "Database connection pool exhaustion",
     "status": "confirmed", "evidence": ["Logs show connection timeout errors"]}
  ],
  "actions_taken": [
    {"action": "Scaled DB connection pool", "result": "No improvement"}
  ],
  "current_focus": "Investigating upstream service causing connection spike",
  "pending_approvals": []
}

33.3 Strategy 2 — Hierarchical Summarization

Every N reasoning steps, condense the recent trace into a paragraph; after several such summaries accumulate, summarize the summaries. Always preserve current hypothesis, key findings, and attempted actions verbatim rather than summarizing them away.

33.4 Strategy 3 — Retrieval-Augmented Memory

Store all actions and observations in a searchable (typically vector) index; when the agent needs context on a specific aspect, retrieve only the relevant entries rather than replaying everything. Scales far better than transcript replay for long-running tasks.

33.5 Strategy 4 — Checkpoint and Resume

Periodically persist full agent state to durable storage. On failure, timeout, or process restart, resume from the last checkpoint rather than starting over — this also enables clean hand-off between operators/shifts, since the incoming operator gets the complete structured state rather than having to reconstruct context from a chat log.

33.6 Putting It Together

class ClaimProcessingContext:
    def __init__(self, llm, checkpoint_store, max_tokens: int = 8000):
        self.llm = llm
        self.checkpoint_store = checkpoint_store
        self.messages: list[dict] = []
        self.summary = ""
        self.max_tokens = max_tokens

    def add_step(self, step_result: dict):
        self.messages.append(step_result)
        if self._count_tokens() > self.max_tokens:
            self._compress()

    def _compress(self):
        old = self.messages[: len(self.messages) // 2]
        summary = self.llm.summarize(old)
        self.summary += f"\n{summary}"
        self.messages = self.messages[len(self.messages) // 2 :]

    def checkpoint(self, task_id: str):
        self.checkpoint_store.save(task_id, {
            "summary": self.summary, "messages": self.messages,
        })

    def resume(self, task_id: str):
        state = self.checkpoint_store.load(task_id)
        if state:
            self.summary = state["summary"]
            self.messages = state["messages"]

    def _count_tokens(self) -> int:
        return sum(len(m["content"]) // 4 for m in self.messages)

    def get_context(self) -> list[dict]:
        return [{"role": "system", "content": f"Context so far:\n{self.summary}"},
                *self.messages]

Section 33 — Interview Q&A

Q1: Structured state vs. full conversation replay — how do you decide which to use where? Full conversation replay is simplest and preserves the most fidelity, but scales poorly past a modest number of turns and increases both cost and (often) reasoning-quality degradation on long contexts. Structured state is more engineering effort up front (you must define the schema for what’s worth keeping) but scales indefinitely, is cheaper per call, and doubles as a natural audit artifact. In production, default to structured state for anything expected to run more than ~10-15 steps; conversation replay is fine for short, bounded interactions.

Q2: How do you avoid losing critical information during hierarchical summarization? Never summarize the “always preserve” set — current hypothesis, key findings, actions taken and their results, pending approvals. Only summarize the exploratory reasoning trace around those. Test summarization quality explicitly: periodically diff the summarized state against the raw trace on a sample of tasks to confirm no load-bearing fact silently disappeared.

Q3: What’s your checkpoint frequency strategy for a long-running agent, and what triggers a checkpoint beyond a fixed interval? Checkpoint on a fixed cadence (e.g., every 5-10 steps) as a baseline, but also checkpoint immediately after any state-mutating action (so a crash never loses record of an action that was actually taken — critical for avoiding duplicate execution on resume), after any human approval decision, and before any step estimated to be expensive or risky.