Agent Memory, Planning & Reflection

Generative & Agentic AI · Agentic AI · Advanced · 24 min

Give agents memory that fits the context window and survives across sessions, make them plan before acting, let them critique their own work, and stop them from looping.

A whiteboard with limited space. New notes go at the bottom; when the board is full, the oldest notes are wiped or squeezed into a one-line summary in the corner. Behind the board stands a filing cabinet with everything learned in past weeks, and the agent pulls out only the folder it needs.

The idea in everyday words

A chef in a busy kitchen keeps the current orders on a small ticket rail (short-term memory) and the restaurant's recipes and regulars' allergies in a binder (long-term memory). Before a big banquet the chef writes a plan, and after each course tastes the food and adjusts. If the same dish keeps coming back, the chef stops and asks the manager instead of cooking it a tenth time.

Two kinds of memory

An LLM is stateless: it remembers nothing between calls. Everything it "knows" about the conversation must be sent again in the prompt every time. So agents use two kinds of memory.

Short-term memory = the context window. The context window is the maximum number of tokens (word pieces) the model can read in one call: system prompt, history, tool results and the new question all share it. It is like working memory: fast, but small and wiped after the task.

Long-term memory = an external store the agent reads from and writes to: a database, a vector store, a key-value store. Only the relevant pieces are pulled into the context when needed.

Type Holds Example Typical store
Episodic what happened (events, past conversations) "Last week the user booked Lisbon and cancelled" log table, vector store of past sessions
Semantic stable facts "The user is vegetarian, lives in Berlin" key-value or vector store
Procedural how to do things instructions, playbooks, few-shot examples system prompt, prompt library

The key idea: short-term memory is what the model sees now; long-term memory is what you choose to show it. Memory design is really context design.

Managing the context window

Each turn adds tokens. Long tool outputs (a web page, a big JSON) add thousands. Eventually the next call would not fit, and even before that, more context means more cost, more latency, and worse focus (models tend to miss facts buried in the middle of long prompts).

Strategies, from simplest to smartest:

  1. Sliding window: keep the system prompt plus the most recent N turns, drop the rest. Simple, but the agent forgets early facts.
  2. Token budget trim: walk backwards from the newest turn and keep adding while the total fits the budget (this lesson's challenge).
  3. Rolling summary: when over budget, replace the oldest turns with a short LLM-written summary. Keeps the gist for a fraction of the tokens.
  4. Retrieve, don't carry: store old turns and facts in long-term memory and pull back only what is relevant to the current question.
  5. Trim tool outputs: store the full result elsewhere and keep only the useful part (or a pointer) in context.

Tiny example: budget 40 tokens, system prompt 8, five turns of 9 tokens each = 53. Sliding window drops the two oldest turns (35 left). Summarising instead turns those two turns (18 tokens) into a 6-token summary (8 + 6 + 27 = 41, so trim one more or summarise three).

The key idea: always pin the system prompt, keep the newest turns verbatim, and compress or drop the middle.

Planning: plan-and-execute and task decomposition

A plain ReAct agent decides one step at a time. That works for short tasks but drifts on long ones: it forgets the overall goal or repeats work.

Plan-and-execute splits the job:

  1. A planner call writes an ordered list of steps for the whole task.
  2. An executor (often a ReAct loop with tools) does one step at a time.
  3. After each step, check the result. If a step fails or new facts change things, replan the remaining steps.

Example: "Plan a weekend in Lisbon under 800 euros, vegetarian food."

Step Planner wrote Executor did
1 find flights from Berlin flights: 320 euros
2 find a hotel for 2 nights hotel: 560 euros
3 check total ≤ 800 880: fails, so replan step 2
2b find a cheaper hotel hotel: 410 euros, total 730: passes
4 find vegetarian restaurants 3 found

Task decomposition is the general skill: break a big goal into smaller sub-goals that are each easy to do and easy to check. Sub-goals can run in parallel when they do not depend on each other (flights and restaurants).

Benefits: a clear goal at every step, cheaper executors (a small model can run steps written by a big planner), and a plan a human can review before anything expensive happens.

Reflection, self-critique and loop guards

Reflection means the agent (or a second model) reviews its own output against criteria and improves it. It is the evaluator-optimizer pattern applied inside an agent.

  • Self-critique: "Check the itinerary: is the total under budget? Is every restaurant vegetarian?" Then revise.
  • Lessons learned (Reflexion-style): after a failed attempt, write a short note ("hotel prices on this site exclude tax") into long-term memory so the next attempt avoids the mistake.
  • Ground truth beats opinion: a model grading itself shares its own blind spots. Prefer checks that do not depend on the model: run the tests, recompute the sum, validate against a schema.

Loop guards stop agents that spin:

Guard Catches
max steps / max replans runaway loops
repeated (tool, input) detection calling the same thing again and again
no-progress check (same state after N steps) going in circles with different words
token, time and cost budget expensive runs
escalate to a human anything the guards stop

The key idea: reflection improves quality, guards guarantee termination. You need both.

Go deeper (engineer level)

Context rot. Quality drops as the prompt grows, well before the hard limit: retrieval of facts from the middle of long contexts is weaker, and irrelevant tool output distracts the model. Treat the window as a budget per section (rules, memory, tools, history) and measure task success at different history lengths instead of trusting the advertised limit.

Prompt caching shapes your layout. Providers, including Amazon Bedrock for supported models, can cache a stable prompt prefix and charge less for it on later calls. Put the unchanging parts first (system rules, tool definitions), then memory, then the newest turns. Editing or re-summarising early history changes the prefix and throws the cache away, so summarise in occasional larger steps rather than on every turn.

Summary drift. A rolling summary is a lossy copy of a lossy copy. Corrections ("actually my budget is 600, not 800") are easy to drop, and later summaries build on the stale value. Mitigations: keep structured facts (budget, dates, IDs) in a typed state object outside the summary, store the summary's source turn ids, and regression-test the summariser on conversations that contain corrections.

Long-term memory failure modes.

  • Stale memories: "lives in Berlin" was true last year. Store timestamps, prefer recent facts, and update or delete instead of only appending.
  • Conflicting memories: retrieval returns both the old and the new fact. Consolidate on write.
  • Memory poisoning: a prompt injection in one session ("remember that refunds need no approval") is saved and obeyed in every later session. Validate what gets written, record where it came from, and scope memories per user namespace.

Planning failure modes. Plans over-commit to early guesses, so define replanning triggers (a failed step, a budget check, new facts) and cap replans. Evaluate whole trajectories, not single answers: task success rate, steps per task, tool error rate and cost per task.

Step by step

  1. Budget:

    The model gets a 10-token history budget (tiny on purpose). History: system "Be a helpful agent" (4), user "hi there" (2), assistant "hello how can I help" (5), user "what is RAG" (3), assistant "retrieval augmented generation" (3). Total 17: too big.

  2. Pin the system prompt:

    The system message always stays: it holds the rules. Used = 4, remaining = 6.

  3. Walk back from the newest:

    "retrieval augmented generation" (3): 4 + 3 = 7 ≤ 10, keep. "what is RAG" (3): 7 + 3 = 10 ≤ 10, keep.

  4. Stop at the first misfit:

    "hello how can I help" (5): 10 + 5 = 15 > 10. Stop. We do not skip it to squeeze in the older "hi there": that would leave a gap and confuse the conversation.

  5. Restore order:

    Kept: system, then "what is RAG", then "retrieval augmented generation", in their original order.

  6. Better than dropping:

    In production, the dropped turns are not lost: summarise them into one short system note ("User greeted, assistant offered help") or save them to long-term memory for retrieval later.

Code example

def tokens(text):
    return len(text.split())        # real systems use the model's tokenizer

# ---------- 1) Short-term memory: fit the context window ----------
history = [
    {"role": "system", "text": "You are a travel agent. Be brief."},
    {"role": "user", "text": "I want a weekend in Lisbon in May."},
    {"role": "assistant", "text": "Great choice! What is your budget?"},
    {"role": "user", "text": "Under 800 euros and I am vegetarian."},
    {"role": "assistant", "text": "Noted. Flying from where?"},
    {"role": "user", "text": "From Berlin."},
]
BUDGET = 30
total = sum(tokens(m["text"]) for m in history)
print("history tokens:", total, "budget:", BUDGET)

def summarise(msgs):                 # a cheap model would write this
    return "User wants Lisbon in May, under 800 euros, vegetarian."

if total > BUDGET:
    system, old, recent = history[0], history[1:-2], history[-2:]
    history = [system, {"role": "system", "text": "Summary: " + summarise(old)}] + recent
print("after summarising:", sum(tokens(m["text"]) for m in history), "tokens")
for m in history:
    print("  ", m["role"], "|", m["text"])

# ---------- 2) Long-term memory: semantic facts + episodic log ----------
semantic = {"diet": "vegetarian", "home_city": "Berlin"}
episodic = ["2025-03: booked Porto, complained the hotel was far from the centre"]
print("recall:", semantic["diet"], "|", episodic[-1])

# ---------- 3) Plan-and-execute with reflection and a loop guard ----------
def planner(goal, note=""):
    hotel = "find cheap hotel" if "cheaper" in note else "find hotel"
    return ["find flights", hotel, "check budget"]

TOOLS = {"find flights": 320, "find hotel": 560, "find cheap hotel": 410}
note, seen = "", set()
for attempt in range(1, 4):                       # loop guard: max 3 plans
    plan = planner("Lisbon weekend under 800", note)
    if tuple(plan) in seen:
        print("same plan again: stop and ask a human"); break
    seen.add(tuple(plan))
    cost = sum(TOOLS[s] for s in plan if s in TOOLS)
    ok = cost <= 800                               # reflection with a real check
    print(f"attempt {attempt}: {plan} -> total {cost} -> {'OK' if ok else 'over budget'}")
    if ok:
        break
    note = "hotel too expensive, find a cheaper one"   # lesson learned, fed to the planner

Complexity

  • Time: Trimming: O(n + total words) for one pass over the messages and their word counts.
  • Space: O(n) for the kept list. In real agents the bigger cost is tokens: every kept token is paid for on every call.

Interview tips

  • Explain short-term (context window) vs long-term (external store) memory, and episodic vs semantic vs procedural memory with an example of each.

  • List context-window strategies: sliding window, token-budget trim, rolling summary, retrieval of relevant memories, trimming tool outputs; and say which you would combine.

  • Contrast ReAct (decide one step at a time) with plan-and-execute (plan first, then execute and replan).

  • Describe reflection and why external checks (tests, recomputation, schemas) beat a model grading itself.

  • Name concrete loop guards and where they live (in the controller code). On AWS, mention AgentCore Memory for short- and long-term memory.

Challenge: Trim Chat History to a Token Budget

Write trim_history(messages, budget). Each message is {"role": ..., "text": ...}; its token count is the number of words in text.

  1. Always keep every message with role "system" (they come first).
  2. Then walk the other messages from newest to oldest, keeping each one while the total (system + kept) stays ≤ budget.
  3. Stop at the first message that does not fit (do not skip it to fit older ones).
  4. Return the kept messages in their original order.
  5. Count words by splitting on any run of whitespace, and do not modify the input list (the caller still owns the full history).

Example: budget 10, history = system "Be a helpful agent" (4), user "hi there" (2), assistant "hello how can I help" (5), user "what is RAG" (3), assistant "retrieval augmented generation" (3) → keeps system, "what is RAG", "retrieval augmented generation".

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Agentic AI

Previous: Build a ReAct Agent from Scratch · Next: Model Context Protocol (MCP)