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.
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
- What state belongs in a model call?
- Budget first, assemble second
- Updates and deletion are memory operations
- Preserve invariants when rebuilding a summary
- Experiment: complete tool turns and the latest preference
- Use replay to separate retrieval and merge errors
- Summary and exercises
- Quick self-check
- Design a cross-session regression test
- Further reading
- 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.
| Layer | Contents | Use |
|---|---|---|
| Instructions | System rules, tool contracts, and output constraints | Define tasks and responses the model can handle |
| Current task | Explicit request and confirmed constraints | Select the next action within its authorization |
| Working history | Calls, replies, and pending actions in this session | Preserve causal order across turns |
| Cross-session memory | Confirmed preferences with provenance, versions, and expiry | Supply defaults when the request leaves a field open |
| Business state | Live availability, attendees, and confirmed bookings | Validate before committing and verify after execution |
Budget first, assemble second
Let the context limit be . Fixed instructions, tool schemas, the current request, and template overhead consume . Reserve for the output. History, summaries, and retrieval can share the remainder:
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 case | Expected behavior | Signal |
|---|---|---|
| Explicit override for this request | Use it once, without a persistent write | Selected value and source |
| Out-of-order replicas | Read the latest confirmed version | Version read and last committed version |
| Deleted preference | Use an application default or ask | Stale retrievals after deletion |
| Tool group barely exceeds budget | Include all of it or remove all of it | Orphaned calls or results |
| Two accounts share a key name | Retrieve within the current account | Out-of-scope hits |
| Live state changes after planning | Query again before committing | Final-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
- Berkeley Scalable AI Fall 2026 lectures on context engineering and harness design.
- Yu Su’s memory and planning slides.
- Agent tool calling, RAG, and Agent evaluation.
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.