skip to content

learn.smmeyer.devllm-engineering10

llm-engineering/10

knowledge systems · core · ~3h practice

Context & memory

outcome

Allocate context and design safe memory that remains relevant, fresh, and user-controlled.

Plan a practice session · ~3h including exercises
Read + trace the worked example
25 min
Assignment + constraint variations
100 min
Timed drill + repeated explanations
35 min
Closed-book recall + self-review
20 min

This is a suggested practice budget, including drawing, variations, and repeated drills. Reading is the first block. Split the work across sessions and use the rubric to judge when to move on.

why this matters

Context is scarce working space; memory is a product subsystem that selects what to put there. More history can increase cost and distract the model while making stale assumptions feel authoritative.

coverage

  • Working context: window limits, instruction/history/tool budgets.
  • Compression: summaries, compaction, lossy state.
  • Retrieval memory: store, embed, rank, inject.
  • State: session state vs durable preferences/facts.
  • Quality: relevance, freshness, contradiction, context rot.
  • Privacy: consent, visibility, deletion, sensitive inference.

mental model

Memory is a write policy plus a retrieval policy, both under user control.

  1. 1 →Observe

    Candidate fact

  2. 2 →Decide

    Worth storing?

  3. 3 →Retrieve

    Relevant now?

  4. 4 →Reconcile

    Fresh + permitted?

Read in numbered order: observe → decide → retrieve → reconcile.

lessons

01Budget the window

Allocate space among policy, task instructions, current user input, recent turns, retrieved knowledge, tool results, and output headroom. Truncate by semantics, not raw oldest-first token count.

Assemble context as a budgeted input: trusted instructions, user request, selected history, evidence, tool observations, and output headroom. If the maximum window is 16k tokens and output needs 2k, the input cannot consume all 16k. Token counts vary by tokenizer, so measure with the intended setup rather than assuming characters map uniformly to tokens.

More context is not automatically more useful. Duplicate passages, old tool results, and conflicting instructions can distract from decisive evidence while increasing prefill work. Rank context by task relevance and authority, keep source labels, and preserve the details needed to justify the next action. Test a shorter evidence-focused version against a longer one instead of treating window size as a quality strategy.

  • Keep critical instructions stable and visible
  • Summaries lose detail and can encode mistakes
  • Large tool results should be compacted or referenced

02Memory is selective persistence

Separate ephemeral task state, conversation summaries, explicit preferences, and inferred facts. Store provenance, timestamp, confidence, sensitivity, and scope. Retrieve by relevance plus recency and policy.

Application memory needs a write policy as well as retrieval. Distinguish a user preference, an event record, a derived summary, and an attempted instruction in an untrusted document. Store provenance, subject, tenant, creation time, expiry, and consent or policy basis where relevant. A statement should not become a durable instruction just because it appeared in a conversation.

A memory read is also an authorization decision. Retrieve only the current user's permitted scope, apply freshness and sensitivity rules, and retain enough provenance to explain or delete the item. The model only sees the retrieved subset; the database remains authoritative. Support correction and retraction, including invalidating derived summaries that would otherwise reintroduce a deleted preference.

  • Do not store everything said
  • Let users inspect/correct/delete durable memory
  • Avoid carrying preferences across incompatible contexts

03Reconcile contradictions

New information can supersede old, sources can disagree, and summaries can drift. Use versions and provenance, prefer explicit recent user statements, and ask when conflicts materially affect action.

Compaction is lossy. “Use vendor A” may preserve a decision while losing the condition “only if data remains in the EU.” Keep constraints, rejected alternatives, evidence versions, unresolved questions, and effect identities alongside summaries. Evaluate compaction by asking whether the next correct decision is still possible, not whether the shorter text sounds coherent.

When memory conflicts with current evidence, do not silently merge it into a confident answer. Compare authority, scope, and time; ask the user when the conflict cannot be resolved safely. A current explicit preference may replace an older one, while a user preference cannot override organizational access policy. Design invalidation and contradiction handling as application rules that can be tested.

  • Context rot is quality degradation, not only overflow
  • Compression checkpoints need validation
  • Sensitive memory deserves stricter defaults

worked example

A summary preserves a decision but loses its reason

An assistant compacts ‘Use region A only until EU residency is required’ into ‘Use region A.’ Later an EU customer arrives.

  1. Classify context as current task, durable decisions, source evidence, temporary observations, and sensitive user data.
  2. Preserve the decision's condition, date, and source when summarizing. A shorter statement that drops the reversal trigger changes meaning.
  3. Retrieve relevant durable records for the current task instead of replaying every old tool result.
  4. Give persisted user memory explicit write, correction, deletion, and retention rules; do not silently turn every conversation into a permanent preference.

Design decision: Store compact, attributable facts and decision conditions, then retrieve them under a bounded context policy.

Limit: Summaries are lossy and generated memory can be wrong. Keep source links and allow correction rather than treating a summary as authoritative.

Teaching scenario · traffic, prices, and capacity values are illustrative.

assignment

Produce: A memory schema, context assembly policy, and before/after compaction test.

Paper, a text editor, or a spreadsheet is enough. Model access and paid services are optional.

  1. Create a fictional conversation with two decisions, a contradiction, a temporary detail, and a sensitive field.
  2. Write a compact summary and test whether it answers the later questions without changing conditions or permissions.
  3. Specify consent, update, retrieval, expiry, and deletion; compare a no-memory baseline with the proposed design.

Change a constraint

  • The user retracts a remembered preference.
  • An untrusted document attempts to write a durable instruction into memory.

Self-review rubric

  • Decisions retain conditions and provenance.
  • Context and durable memory are distinguished.
  • The user can inspect, correct, and delete retained information.

If a criterion is missing, revise that part of the artifact before rating your practice below.

Compare a sample artifact after your attempt

One defensible answer under these assumptions. Compare the reasoning and checks with your work; other designs can satisfy the same contract.

A 16k-token exercise window reserves 2k output tokens. Organizational placement rules outrank remembered preferences.

Input allocation: policy 1k + request 1k + history 2k + evidence 8k
                  + tool state 2k = 14k; output reserve = 2k
Memory: {subject, tenant, kind, value, source, createdAt, expiresAt,
         authority, sensitivity, consentBasis, supersedes}
Bad summary: “Use region A.”
Retained decision: “Use A only until EU residency is required;
                  then reevaluate under the placement policy.”
Compaction test: EU customer arrives → must recover conditional decision
Retraction: remove preference + invalidate summaries/retrieval references

The allocation is a proposed budget to test with the real tokenizer and task. Context order, relevance, and authority matter as much as length. A retrieved instruction cannot write durable memory without an allowed write policy. Rebuild or invalidate derived summaries when an underlying preference is corrected.

Check your artifact

  • Input plus reserved output fits the stated window.
  • The compaction test preserves the condition and its reason, not only a conclusion.
  • Memory retrieval is permission-scoped and supports correction, expiry, and deletion.

A tempting mistake: A coherent summary can still lose the constraint that makes the next decision correct.

cumulative practice

Harbor · build and evaluate a support assistant

Project brief

Keep one project document and a folder of fictional input/output fixtures for Harbor, a workspace-scoped support assistant. Start with ticket triage and policy-backed drafts at 20 requests/minute, 1,500 input and 200 output tokens/request. Human users remain responsible for consequential actions until you design explicit permissions and approval. Later chapters add retrieval, controlled tools, durable runs, evaluation, security, and scale. Use paper, a text editor, and mocked results; paid APIs are optional. Preserve first attempts, evidence, and revisions within the existing practice budget.

Keep one project document across this track. Reconstruct earlier reasoning before opening notes, then revise the same artifact. Use part of the assignment and review budget for this work. If you enter mid-course, sketch the earlier decisions first using the linked chapters.

Add to your project: Harbor's context assembler and safe preference memory.

Recall how input length affects serving and how retrieved evidence is authorized. Add a user response-style preference, a current policy, and an old contradictory memory. Compact the run while preserving operation identity and policy provenance; then retract the preference.

Compare cumulative reasoning after your attempt

Budget evidence and history with output headroom; current organizational policy outranks a style preference. Keep source versions, unresolved facts, and effect IDs outside lossy summaries where needed. Memory records carry subject, scope, provenance, and deletion rules. Retraction invalidates derived summaries so a later retrieval cannot silently reintroduce the preference. Recheck the old long-ticket fixtures after compaction changes.

Keep your first attempt and revision together. If your answer differs, identify the assumption or mechanism that explains the difference before rating your recall.

senior signal

Treat memory as data product with consent, provenance, and evaluation—not a bigger prompt buffer.

failure patterns

  • Persisting every utterance
  • Injecting all memories into every turn
  • No user correction/deletion mechanism
  • Summarizing away permissions or unresolved decisions

knowledge checks

Start with these quick checks, then explain the closed-book questions in your own words.

  1. 01What makes a memory safe to inject?

    select an option to check your answer

  2. 02Why can more context hurt?

    select an option to check your answer

closed-book recall

Close the worked example and explain these from memory. Answers are self-reviewed. Drafts stay on this page; save anything you want to keep in chapter notes.

Rate the assignment and recall together

Use the assignment rubric as evidence. Completion is your own judgment; this score schedules practice.

interview drill

Design persistent user memory for a general assistant that works across health, travel, and work contexts.

  • cross-domain
  • sensitive facts
  • user control
  • context budget
compare a strong approach after your attempt

Create scoped memory types with explicit/implicit provenance, sensitivity labels, TTL/review policy, and user controls. Gate cross-domain retrieval, rank by relevance and recency, surface material assumptions, and evaluate false recall, missed recall, contradiction handling, and deletion completeness.

Compare decisions and failure behavior, then repeat with a changed constraint. Keep your own wording.

Use the timed mock workspace →

references

Sources offer deeper context. Provider capabilities and API contracts can change; check current official docs before implementing.

notes

saved locally