8 Applications 6 / 8
  1. In this chapter
  2. Your first agent
  3. Prompt Engineering
  4. Structured Outputs and Function Calling
  5. RAG in Practice
  6. Agents and Tool Calling in Practice
  7. Agent context and memory
  8. Agent Evaluation
  9. MCP and the Tool Ecosystem
All chapters →

Chapter 8 · Applications 8.6

Agent context and memory: budgets, versions, and state

Context engineering fits instructions, tool history, and retrieved evidence into a model call. Long-term memory keeps confirmed preferences across sessions. Test whole tool turns, version precedence, deletion, and replay.

Intermediate 9 min read Updated Companion code ↓

After this page you will be able to

  • Account for inputs, output reserve, and serialization overhead of a model call.
  • Trim history as whole tool groups and preserve causal and pending state.
  • Use provenance, access, and versions to handle writes, replica order, and deletion.
  • Design regressions that distinguish assembly bugs from final-state failures.
On this page
  1. What state belongs in a model call?
  2. Budget first, assemble second
  3. Updates and deletion are memory operations
  4. Preserve invariants when rebuilding a summary
  5. Experiment: complete tool turns and the latest preference
  6. Use replay to separate retrieval and merge errors
  7. Summary and exercises
  8. Quick self-check
  9. Design a cross-session regression test
  10. Further reading
  11. FAQ

Context engineering determines what the model sees on each call. Long-term memory determines which authorized details persist across sessions and when to retrieve them. A reliable agent records the origins of instructions, current requests, tool results, and past preferences, assembles them under a budget, and checks changing business state before acting.

What state belongs in a model call?

The context engineering and harness lectures in Berkeley Scalable AI treat context as input assembled by the system. Consider a room reservation assistant. The current request, a retrieved preference, and the booking service’s record have different roles.

LayerContentsUse
InstructionsSystem rules, tool contracts, and output constraintsDefine tasks and responses the model can handle
Current taskExplicit request and confirmed constraintsSelect the next action within its authorization
Working historyCalls, replies, and pending actions in this sessionPreserve causal order across turns
Cross-session memoryConfirmed preferences with provenance, versions, and expirySupply defaults when the request leaves a field open
Business stateLive availability, attendees, and confirmed bookingsValidate before committing and verify after execution
The layers of one call: F + history + R, business state outside the window Structure diagram: the window W first holds the fixed block F (instructions, tool descriptions, templates and this turn's request), then the full tool groups and retrieved cross-session memory inside the history budget B = W-F-R, with the output reserve R at the bottom; business state is not in the window — read it live right before executing. Counts use the actual tokenizer and templates; tool calls and results are kept in pairs. The layers of one call: F + history + R, business state outside the window Context window W Instructions + tool descriptions + templates (counts toward fixed F) This turn's request (also in F) History budget B = W-F-R Working history: whole tool groups (call + result) Cross-session memory: retrieved preferences + source + version Reserved output R Business state (not in the window) room availability, participants, booking results — re-read live before executing read live Count with the actual tokenizer and chat template; keep tool calls and results in pairs; re-read out-of-window business state before executing
The window W first holds the fixed block F (instructions, tool descriptions, templates and this turn's request), then the full tool groups and retrieved cross-session memory inside the history budget B = W-F-R, with the output reserve R at the bottom. Business state lives outside the window: before submitting, the booking service's latest result is the truth.
If the user preferred morning last time and explicitly asks for the afternoon now, choose the afternoon. Even when a cache lists an available room, check the booking service before committing. Newly seen evidence can inform a decision. Persistence should follow an explicit policy and any necessary confirmation.

Budget first, assemble second

Let the context limit be WW. Fixed instructions, tool schemas, the current request, and template overhead consume FF. Reserve RR for the output. History, summaries, and retrieval can share the remainder:

B=W−F−RB = W-F-R

Count with the actual tokenizer, chat template, and serialized tool definitions. If the fixed blocks already exceed budget, reduce the definitions, output reserve, or current input as appropriate. Dropping additional history cannot solve fixed overhead. Log cost by source along with the tokenizer and template version so replay reconstructs the same budget.

Keep pending task anchors and recent complete turns first. Treat a tool call and its result as one logical group. A result without its parameters is hard to interpret. A surviving call without its result may look unexecuted. With parallel calls, use IDs to pair each result to the right call. Summarize old turns with references to the originals and retrieve relevant evidence by keywords or embeddings. Check freshness, duplication, roles, and access. Two near-identical passages can consume budget needed for the working history.

Updates and deletion are memory operations

The Berkeley Advanced LLM Agents lecture on memory and planning discusses how external memory supports reasoning. In an application, give cross-session preferences a key, scope, provenance, and version. For a preference within one account, filter for confirmed accessible records before comparing versions. Retrieval rank helps locate records. The application decides which sources carry authority.

A write path extracts a candidate fact and checks whether it is a durable preference or a temporary choice. Use stable keys and versions for persistence, with an operation ID to handle retries. Deleting a preference should invalidate old copies. In an incremental log, a higher-version deletion marker can prevent old values from resurfacing while the retention process removes stored values and derived entries. Query the authoritative business service for live state.

On reads, check scope before selecting the latest confirmed version. Include provenance and expiry when the value enters context. A deleted or expired preference leaves the current request and application defaults available, or the assistant can ask. A separately validated write path prevents one-off choices from becoming durable preferences.

Preserve invariants when rebuilding a summary

Treat summaries as derived data and tag their source message ranges and versions. When a preference is deleted, invalidate old summaries and semantic-index entries too. Otherwise the main store may return no value while derived text still exposes the older one. To resume a durable session, restore a consistent snapshot before appending new events. If two writes are based on the same old revision, detect the conflict in storage so a late write cannot silently overwrite a newer confirmed value.

Keep fields needed to finish the task, including pending call IDs, commitments, and explicit user constraints. A completed read can be summarized as a conclusion with provenance. A pending write needs a traceable state. Include template changes, tool schema changes, and tokenizer updates in budget regression checks.

Experiment: complete tool turns and the latest preference

Three groups use synthetic token costs. A contiguous suffix represents a simple history window. Out-of-order confirmed records test version precedence. The example uses the standard library and ran on an Apple M2 Max with Python 3.12.14. A real context assembler can budget separately for summaries and retrieval.

from __future__ import annotations

from collections.abc import Iterable
from dataclasses import dataclass


@dataclass(frozen=True)
class Record:
    version: int
    value: str | None


def resolve(current: str | None, confirmed: Iterable[Record]) -> str | None:
    """Prefer the current value or the latest trusted record."""
    if current is not None:
        return current
    latest = max(confirmed, key=lambda record: record.version, default=None)
    return latest.value if latest is not None else None


def recent_groups(costs: list[int], budget: int) -> list[int]:
    """Take the latest contiguous whole groups within the available budget."""
    if budget < 0 or any(cost <= 0 for cost in costs):
        raise ValueError("budget must be nonnegative and costs positive")
    start = len(costs)
    while start and costs[start - 1] <= budget:
        start -= 1
        budget -= costs[start]
    return list(range(start, len(costs)))

costs = [18, 22, 8]
for budget, expected in [(25, [2]), (30, [1, 2])]:
    kept = recent_groups(costs, budget)
    assert kept == expected
    print("kept groups:", budget, kept)

records = [Record(3, None), Record(1, "morning"), Record(2, "evening")]
current = resolve("afternoon", records)
deleted = resolve(None, records)
assert current == "afternoon" and deleted is None
assert resolve(None, records[1:]) == "evening"
print("override:", current)
print("after deletion:", deleted or "absent")
kept groups: 25 [2]
kept groups: 30 [1, 2]
override: afternoon
after deletion: absent

The widget below makes the window budget and whole-group trimming draggable: tune W, F and R to see the history budget and which tool groups survive, then try the memory read rule (this turn wins; deletion markers don’t come back).

After keeping the latest short turn, the smaller budget cannot fit the previous tool group, so the script leaves that group out. The larger budget fits both. Memory records arrive out of order, yet the highest version wins. When that record is a deletion, older values stay inactive. A deployment should separately protect in-progress operations from eviction.

Use replay to separate retrieval and merge errors

Run the old and new assemblers on the same initial database snapshots and tasks. Check the context before running the full task. Log included and omitted IDs, the selected preference and provenance, the budget, and model decisions so failures can be replayed in isolation.

Test caseExpected behaviorSignal
Explicit override for this requestUse it once, without a persistent writeSelected value and source
Out-of-order replicasRead the latest confirmed versionVersion read and last committed version
Deleted preferenceUse an application default or askStale retrievals after deletion
Tool group barely exceeds budgetInclude all of it or remove all of itOrphaned calls or results
Two accounts share a key nameRetrieve within the current accountOut-of-scope hits
Live state changes after planningQuery again before committingFinal-state success and duplicate writes

Retrieval recall asks whether the right evidence entered context. Final-state success asks whether the system used it correctly and completed the task. For an ablation, keep the budget fixed and replace one selector rather than changing model and memory at once. If several stages may be responsible, replay with known-correct evidence first and see what still fails.

Summary and exercises

  • Budget against rendered tokens and trim only whole tool groups.
  • Store confirmed preferences with scope and version and invalidate stale copies on deletion.
  • Measure context assembly before checking end-to-end outcomes.

Quick self-check

1. What should a context budget count?

  • Rendered model input and reserved output tokens.
  • Characters in the raw string.

Templates, serialization, and tokenization change the cost.

2. How should an executed tool group be trimmed?

  • Keep the call and omit its result.
  • Pair items by call ID and keep or remove the whole group.

Whole groups preserve what was executed and what happened.

3. What if the highest memory version is a deletion marker?

  • Treat the preference as absent and use the request or an application default.
  • Fall back to the next older record.

Falling back would resurrect a deleted preference.

4. How do you test an afternoon request with a stored morning preference?

  • Expect afternoon to become the default on the next request.
  • Check that afternoon applies to this task without a persistent write.

An override can be temporary.

Design a cross-session regression test

The assistant booked a morning room on the last session. The user asks for the afternoon this time, but the room becomes unavailable just before execution. Define the starting state, whether memory needs an update, and two final-state assertions.

Worked answer

Keep the prior morning preference, the current afternoon request, and two snapshots of room availability. The current request overrides the old default for this task and creates no persistent preference. Query again before committing. On seeing the conflict, ask for alternatives or stop according to the task contract. Verify that no overlapping booking exists and that no morning slot was booked without authorization.

Further reading

FAQ

Is the context window the same as long-term memory?
The context window covers one model call. The application stores long-term memory and retrieves it into the window when relevant.
What happens when an old preference conflicts with the current request?
An explicit current request takes precedence. Persistence of a temporary choice needs application validation and confirmation when appropriate.
Why trim tool calls and results together?
A whole group preserves the causal link between parameters and results. A partial group can hide what executed or make a completed operation look pending.