Memory and Context Engineering

Decide what goes into the context window at each step: short-term history, long-term memory stores, retrieval and summarization.

Intermediate · about 5 hours · difficulty 3/5

Learn first: The Agent Loop, RAG Fundamentals

Models are stateless. Every call sees only what you put in the request. Context engineering is the discipline of choosing that content well: enough to do the job, little enough to stay fast, cheap and focused.

Kinds of memory

  • Short-term (working) memory: the current conversation and tool results. Trim or summarize old turns, and drop bulky tool outputs once they have been used.
  • Long-term memory: facts that persist across sessions, such as user preferences, past decisions or project notes. Store them in a database or files and load only what is relevant.
  • Semantic memory via retrieval: embed past notes or documents and pull back the top matches, exactly like RAG.
  • Procedural memory: instructions and skills the agent should always follow, kept in the system prompt or loaded on demand.

Design questions

  • Who writes memory: the agent via a "save memory" tool, or your code after each session?
  • How do you prevent stale or wrong memories from compounding? Add timestamps, sources and a way for users to view and delete them.
  • What is private? Memory is user data; apply the same privacy rules as any other personal data.

Context rot

Performance often drops as context grows, even within the window limit, because relevant details get buried. Keep the most important instructions near the start and end, prefer fresh sub-agents for isolated sub-tasks, and measure quality at long context rather than assuming it holds.

Good enough to move on

You can build a chat assistant that remembers user preferences across sessions through an explicit memory store, summarizes old turns, and lets the user inspect and delete what it remembers.

Key concepts

  • Short-term conversation memory
  • Summarization and trimming
  • Long-term memory stores
  • Retrieval-based memory
  • Memory tools the agent controls
  • Context rot and ordering
  • Memory privacy and deletion

Mini project

Add persistent memory to a chat assistant: a save_memory tool, a Postgres table of memories with timestamps, retrieval of the top 5 relevant memories per turn, and a page where users can delete them.

Check yourself

What goes wrong if your agent saves every conversation turn as a long-term memory and retrieves the top 20 each time?

Free resources