Context Engineering for AI Agents: Treating “Context” as a Production Line
If tools give an agent its “hands” to actually do things in the world, Context Engineering is the methodology that keeps those hands from grabbing blindly — it determines what the model sees, ignores, remembers, and forgets on every turn. Models are naturally stateless: once a call ends, they wake up with no memory of what just happened. To give agents persistent conversation, long-term personalization, and cross-session experience accumulation, you must externalize state into two systems: Sessions (the conversation workbench) and Memory (the long-term filing cabinet), dynamically assembling them into the context window each turn.
This article focuses on engineering practice: designing sessions, compressing long conversations, how memory is generated/consolidated/retrieved, why memory becomes the “common layer” for multi-agent and cross-framework collaboration, and finally privacy/security and evaluation metrics — because “remembering” isn't the goal. Remembering correctly, finding reliably, using stably, and not leaking is.
---
Chapter 1: What Is Context Engineering?
Traditional prompt engineering writes a fixed system instruction; Context Engineering concerns the complete payload of every call: dynamically constructing a “stateful” request from user identity, session history, tool results, external knowledge, and long-term memory.
Think of it as *mise en place* before cooking: prepare the fresh ingredients, knives, seasonings, and plating requirements in advance — the model doesn't need to “guess”; it reasons and acts with maximum certainty in minimal noise.
Context typically consists of three categories:
A. Reasoning-guiding context (behavioral constitution)
- System instructions: persona, capability boundaries, rules
- Tool definitions: schemas and descriptions
- Few-shot examples: guiding reasoning paths
- Long-term memory: user info/experience accumulated across sessions
- External knowledge: RAG-retrieved documents/database info
- Tool outputs, sub-agent outputs, artifacts (files, images, etc.)
- Conversation history, state/scratchpad (temporary variables, cart contents, draft calculations), user prompt
- Events: time-ordered conversation events: user input, agent replies, tool calls, tool outputs
- State: structured working memory (scratchpad), e.g., cart contents, task progress, confirmed parameters
- Sessions belong to one user: strict ACL isolation to prevent cross-user access
- Best practice: redact/remove PII before writing to storage — reduces breach blast radius, aids GDPR/CCPA compliance
- Event append order must be deterministic (out-of-order logs break reasoning)
- Sessions shouldn't live forever: use TTL or archival policies to control cost and compliance risk
- Generate summaries asynchronously in the background and persist them; avoid re-summarizing every turn
- Track which events are already summarized so raw text isn't re-injected 4. Trigger mechanisms:
- Count-based: compress when turn/token thresholds are exceeded (most common, “good enough”)
- Time-based: compress in background when the user is idle
- Event-based: compress when a subtask/topic ends
- Personalization (preferences, facts, history)
- Replacing long histories (summaries/key facts reduce tokens)
- Insights at scale (aggregate trend mining, with privacy protection)
- Self-improvement (recording successful strategies/tool paths into playbooks)
- RAG: injects external, static, authoritative facts; typically shared, read-only
- Memory: accumulates user-relevant, dynamic, isolated context; needs writes and evolution
- content: fact snippets (text or structured JSON/dict)
- metadata: id, owner, tags, source, etc.
- Declarative (knowing what): facts, preferences, events
- Procedural (knowing how): skills, processes, workflow “playbooks”
- Collections: atomic memories; good for search and multi-topic
- Structured user profile: stable fields (name, preferences); fast reads
- Rolling summary: one continuously updated overview; often used to compress long sessions
- Vector databases: semantic similarity retrieval; good for unstructured memory
- Knowledge graphs: entity-relation reasoning; good for structured associations
- Hybrid: graph nodes with embeddings, supporting both semantic and relational retrieval
- Source type (preloaded system data / user input / tool output)
- Freshness (timestamps)
- Possible confidence dynamics (rising with multi-source corroboration, decaying over time)
- Trust tiers during consolidation (trusted sources first, recent first, multi-source corroboration first)
- When a data source is deleted, regenerate precisely along the lineage instead of wiping everything
- Session end: cheap, possibly low-fidelity
- Every N turns: common compromise
- Every turn, real-time: freshest, most expensive
- Explicit user instruction: controllable but incomplete coverage
- Memory-as-a-Tool: the agent decides when to call
create_memory— smarter, but needs strict tool definitions and policy controls to avoid “over-memory-ing” - Relevance (semantic)
- Recency (temporal freshness)
- Importance (annotated at generation time)
- Proactive prefetch: fetch at turn start; simple but adds latency; cacheable
- Reactive (Memory-as-a-Tool): query only when needed; cheaper but may add an LLM call; the agent must “know what memory types exist” or it won't know when to query
- Precision: how many memories are correct and relevant (guards against “over-memory-ing” pollution)
- Recall: are must-remember facts missing (guards against losing key facts)
- F1: combined metric
- Recall@K: does the needed memory appear in top-K
- Latency: within strict budget (e.g., <200ms) (Complex rewrite/rerank flows generally don't fit real-time hot paths unless cached and resistant to staleness.)
- Strict isolation (user/tenant scope): cross-user leakage is a fatal incident
- User control: opt-out and deletion supported
- PII redacted before persistence
- Defend against memory poisoning: validate and sanitize injected/fabricated information
- Cross-user shared procedural memory must be strongly anonymized, or “experience reuse” becomes “information leakage”
B. Evidence and factual data (reasoning evidence chain)
C. Current interaction info (the task at hand)
> Tip: more context is not better. Long contexts bring cost, latency, and “context rot” — the more information, the harder it is for the model to grasp key points, and reasoning quality drops. The goal is “just enough, not more.”
---
Chapter 2: The Per-Turn Context Pipeline
A production agent typically runs a four-step loop each turn:
1. Fetch Context: retrieve memory, RAG results, recent events 2. Prepare Context: build the final prompt (blocking hot path) 3. Invoke LLM and Tools: outputs appended into context 4. Upload Context: persist new information (mostly async in background)
The most overlooked but critical point: Prepare is a blocking hot path; Upload should be backgrounded. Putting expensive distillation/integration work into the hot path makes every reply feel laggy.
---
Chapter 3: Sessions — The Conversation Workbench
3.1 A session = Events + State
A session is a single-user, single-conversation container. A user can have multiple sessions, but they are disconnected “project workbenches” that don't naturally share memory (sharing requires Memory).
3.2 Production session storage
Most agent runtimes are stateless: memory is cleared when a request ends. So session history must be persisted (database or managed session service) and reloaded at each turn.---
Chapter 4: Framework Differences and Multi-Agent Session Patterns
4.1 Frameworks are translators
Frameworks map internal event structures into model-API-specific formats. This decouples model vendors but introduces cross-framework “semantic isolation.”4.2 Two multi-agent history patterns
A. Shared Unified History — all agents write messages, tool calls, and observations into one chronological log. Fits tightly coupled, pipeline-style tasks that depend on a single source of truth. Pros: globally traceable, natural handoffs. Cons: history bloat, noise, harder permission isolation.
B. Separate Individual Histories — each agent keeps a private history and exposes only final results (black-box tools), often via “Agent-as-a-Tool” or A2A messages exchanging results, not processes. Pros: clear boundaries, less leakage. Cons: impoverished shared context; collaboration needs extra design.
---
Chapter 5: Cross-Framework Interoperability — Memory as the Universal Layer
Different frameworks' session/event storage models are strongly bound to internal object structures, so one framework's session is hard for another to read. You can pass A2A messages, but “rich state” still needs a translation layer.
The more robust pattern: abstract shared knowledge into a framework-agnostic Memory layer. Memory stores distilled facts/entities/summaries (strings or dicts), not framework event objects — making it a shared cognitive resource across frameworks and agents.
---
Chapter 6: Session Production Considerations
6.1 Security & privacy
6.2 Data integrity
6.3 Performance
Every turn pulls session history and builds a prompt — bigger history means slower and costlier. Key optimization: filter/compress history before sending to the model (e.g., drop stale tool outputs).---
Chapter 7: Long-Conversation Management — Packing History Like Luggage
Four hard constraints: context window limits, token cost, latency, and quality (noise + autoregressive drift).
Compression strategies (simple → complex):
1. Sliding window: keep the last N turns. Simple, but may lose early key constraints. 2. Token-based truncation: truncate by token budget. Better cost control, same “may cut key facts” risk. 3. Recursive summarization: replace older segments with summaries alongside recent raw turns. Engineering points:
---
Chapter 8: Memory — The Long-Term Filing Cabinet
Memory isn't “storing conversations”; it's extracting and solidifying valuable information from them, persisting across sessions for personalization, context management, data insight, and self-improvement.
Four capabilities memory provides:
---
Chapter 9: Memory vs. RAG
One sentence: RAG makes the system a “facts expert”; Memory makes it a “user expert.”
---
Chapter 10: Memory Structure and Types
10.1 Basic structure
10.2 Declarative vs. Procedural
Key distinction: procedural memory isn't “retrieving data” but “retrieving an executable plan” — more like a reasoning-augmentation layer. Compared with fine-tuning (offline, weight changes), procedural memory injects playbooks online via in-context learning for rapid correction.
---
Chapter 11: Memory Organization and Storage
11.1 Organization patterns
11.2 Storage architectures
---
Chapter 12: Memory Generation — LLM-Driven ETL
Memory generation is an LLM-driven ETL, not simple summarization:
1. Ingestion: input source data (usually session history) 2. Extraction & filtering: extract meaningful info per “topic definitions” (if no match, don't record) 3. Consolidation: dedup, conflict resolution, update/create/delete, and forgetting (TTL / low confidence) 4. Storage: write to vector DB / graph, etc.
12.1 Extraction: deciding what's worth remembering
“What's meaningful” depends entirely on business goals. Common implementations: schema/template-based extraction (structured output), natural-language topic definitions, few-shot examples (especially effective for subtle domains). Many systems use rolling summaries as auxiliary extraction input to avoid rescanning full history each turn.12.2 Consolidation: without it, memory becomes a contradictory garbage heap
Consolidation must handle: duplication (same fact, many phrasings), conflicts (changing user preferences), evolution (facts become more specific), and decay/forgetting (delete/downweight old, low-confidence entries).Common operations: UPDATE / CREATE / DELETE (or INVALIDATE).
---
Chapter 13: Memory Provenance — Why Believe It?
Long-term memory without source tracking drifts into “confident nonsense.” Track at minimum:
Important recommendation: generating long-term memory from tool outputs is generally not advised — tool data suits short-term caching and is easily stale and brittle.
Engineering value of provenance:
---
Chapter 14: When to Generate Memory? Memory-as-a-Tool
Trigger strategies trade cost vs. fidelity:
Background vs. blocking: memory generation should almost always be async
Memory generation requires LLM calls and DB writes — strip it from the hot path: the user gets the reply first; extraction/consolidation happens in the background. Otherwise the experience becomes unusably slow.---
Chapter 15: Memory Retrieval — Relevance Isn't Enough
Goal: find the most useful memories within a strict latency budget.
Common scoring dimensions:
Relying only on vector similarity is a common trap: it surfaces “similar but stale/trivial” memories. Multi-dimensional hybrid scoring is more robust.
Advanced (but slower) enhancements: query rewriting (one extra LLM call), reranking (fetch top-50, rerank with an LLM), training a dedicated retriever (needs labeled data, expensive). Combine with caching to avoid repeating expensive flows.
Retrieval timing: proactive prefetch vs. reactive query
---
Chapter 16: Injecting Memory into Context — Where You Put It Is How Much It Weighs
16.1 In system instructions
Pros: high authority, clean conversation history; good for stable info (user profiles). Risks: over-influence — the model may force every topic toward the memory; system instructions are usually text-only (bad for multimodal memory); incompatible with “let the model decide whether to call memory tools.”16.2 Injected into conversation history
Pros: flexible; good for situational memories. Risks: noisy, high token cost, possible “conversational injection” illusion (model treats memory as something the user just said). If injecting user-level memory via the user role, maintain first-person perspective consistency.16.3 As tool output
With reactive querying, memory enters context as a tool output, naturally placed in the conversation sequence. Pros: clear provenance chain. Cons: poor retrieval quality directly pollutes reasoning.---
Chapter 17: Evaluating Whether Memory Actually Helps
Evaluate at three levels:
17.1 Generation quality: is it remembered correctly?
Compare against a human golden set:17.2 Retrieval performance: can it find things, fast?
17.3 End-to-end task success
Use an LLM judge to compare final answers against golden answers — does memory actually improve goal outcomes?---
Chapter 18: Privacy & Security — Memory Is a Corporate Archive, Not a Scratchpad
The bottom lines for long-term memory:
References
1. Retrieval-Augmented Generation overview: https://cloud.google.com/use-cases/retrieval-augmented-generation?hl=en 2. Agent Engine Sessions overview: https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/sessions/overview 3. Agent Engine Memory Bank – generate memories: https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/memory-bank/generate-memories 4. Model Armor overview: https://cloud.google.com/security-command-center/docs/model-armor-overview 5. Gemini long context limitations: https://ai.google.dev/gemini-api/docs/long-context#long-context-limitations