Handbooks / RAG & AI Agents / Chapter 4
Agent Loops and Memory
7 pages · ~5 min✓ Reviewed
Builds on Tool Calling. Next up: Guardrails and Evaluation.
The ReAct Loop Mental Model
1. Agent = LLM + Tools + Loop
- Agent = LLM + tools + loop
- The model picks the next action
- Code executes it; the result goes back into the context
- Repeat until a final answer
2. The ReAct Cycle
- Thoughtreason about next step
- Actiontool call + arguments
- Observationtool result
- Final answerloop ends
| Plain CoT | ReAct | |
|---|---|---|
| Facts from | prompt only | real tool observations |
| Fetch data? | no | yes |
| Hallucination | higher | lower |
3. Example: Weather in the capital of France?
- 1Thoughtneed the capital
- 2Actionsearch('capital of France')
- 3ObservationParis
- 4Actionget_weather('Paris')
- 5Final answerweather in Paris
One iteration
Thought → Action → Observation. The loop ends only on a final answer
4. Interview Point
- Workflow vs agent? Workflow: code fixes the steps. Agent: the model picks them.
- Why less hallucination than CoT? Each step is grounded in real tool observations.
- One loop iteration? Thought, Action, Observation.
Planning Patterns
1. Plan-and-Execute and Re-planning
- Planner LLM writes the full step list up front
- Executor runs each step in order
- Fits long, predictable tasks
- Re-plan after each step or failure: check plan against observations, then revise
- A static plan breaks when a tool result surprises you
- Planall steps
- Executeone step
- Checkvs observation
- Reviseon surprise
2. ReAct vs Plan-and-Execute
| ReAct | Plan-and-execute | |
|---|---|---|
| Decides | one step at a time | all steps up front |
| Strength | flexible | coherent |
| Weakness | myopic | rigid |
| Cost | more LLM calls | cheaper |
| Use for | adaptive tasks | long, predictable tasks |
3. Reflection Loop
- 1Draftfirst output
- 2Critiquemodel judges itself
- 3Reviseretry, then repeat
Cap the rounds
Limit reflection to 1-3 rounds. Every round adds LLM calls and latency.
Short-term vs Long-term Memory
1. Two Memories
| Short-term | Long-term | |
|---|---|---|
| Is | Context window | External store: vector DB, KV, files |
| Holds | Messages, tool calls, results | Facts, preferences, outcomes |
| Lifetime | Lost at session end | Persists across sessions |
| Access | Size-limited | Similarity or key lookup |
2. Stay Within Budget
Sliding window
Keep recent turns
Summarize
Compress old turns
Trim
Cut bulky tool outputs
3. Long-term Write Policy
- Write distilled facts: preferences, decisions, outcomes
- Never raw transcripts
- Read: retrieve top-k relevant items, inject into the prompt
- 1Query
- 2Search storesimilarity or key
- 3Top-k
- 4Prompt
Mistake
Storing raw transcripts bloats the store and buries useful facts.
4. Interview Point
- Storage and lifetime? Context window, gone at session end, vs an external store that persists.
- Window full? Slide the window, summarize old turns, trim tool outputs.
- What to write, how to read? Distilled facts; retrieve top-k by similarity or key.
Multi-Agent Patterns
1. Three Patterns
| Pattern | Shape | Use for |
|---|---|---|
| Orchestrator-worker | Lead splits, delegates, merges | Most common |
| Pipeline / handoff | researcher → writer → reviewer | Sequential stages |
| Debate / critic | Propose, critique or vote | Hard, high-stakes answers |
- Leadsplits task
- Workersspecialists
- Leadmerges results
2. Single vs Multi
- Use multi-agent only if subtasks are parallel
- Or they need separate contexts
- Or they need different tools or prompts
- Otherwise start with a single agent
Cost
Multi-agent multiplies token cost and adds coordination failures.
3. Interview Point
- Single enough? Yes, unless subtasks are parallel or need separate contexts, tools or prompts
- Sharing context? Lead sends each worker a task brief; workers return results the lead merges
- Specific failures? Lost context at handoffs, conflicting outputs, runaway cost, error cascades
Stopping Conditions, Cost and Latency
1. Stop Signals and Loop Failure
- Final answerno tool call
- Step capmax iterations
- Budgettokens or time
- Interrupthuman or guardrail
- Same tool + same args repeated = never converges
- Detect the repeat, then break out or force a different strategy
python
key = (call.name, json.dumps(call.args, sort_keys=True)) if key in seen: raise LoopDetected(key) # or re-plan seen.add(key)
key = tool name + sorted args
2. Cost
| Mitigation | Effect |
|---|---|
| Prompt caching | re-sent prefix costs less |
| Smaller model | handles easy steps |
| Trimmed tool outputs | fewer tokens per step |
| Hard step cap | bounds total spend |
Why cost snowballs
Every step re-sends the whole context, so step n pays for all earlier steps. Total cost grows faster than linearly.
3. Latency
| Lever | How |
|---|---|
| Parallel calls | run independent tools together |
| Streaming | show tokens as they arrive |
| Fewer steps | cut needless loop iterations |
| Fast model | route simple requests to it |
Agents Cheat Sheet
1. The Loop
- Thoughtnext step
- Actiontool call
- Observationtool result
- Repeat
- Stop on a final answer
- Step cap reached
- Budget (token or time) spent
- Guardrail interrupts
2. Planning and Memory
| Topic | Rule |
|---|---|
| ReAct | adaptive tasks |
| Plan-and-execute | long, predictable tasks |
| Re-plan | on surprises |
| Reflect | 1-3 rounds at most |
| Short-term | context window: window, summarize, trim |
| Long-term | external store, distilled facts, top-k |
3. Multi-Agent and Cost
- Orchestrator-worker by default
- Start with a single agent
- Cost: step cap, prompt caching, small model for easy steps
- Parallel tool calls cut latency
Stuck loop
Same tool call with same arguments never converges. Detect repeats, then break out.
Check yourself
An agent calls search('Paris weather') with the same arguments five times in a row. What is wrong, and what do you do?
- It is stuck: the same call and arguments give the same observation, so it never converges.
- Detect repeats, then break out or force a different strategy. A step cap guarantees it stops.
Each step of a 10-step loop adds 1k tokens to the context. Is the total input about 10k tokens?
- No. Every step re-sends the whole context: 1k + 2k + ... + 10k = 55k.
- Cost grows faster than linearly. Prompt caching and trimmed tool outputs reduce it.
A plan-and-execute agent finds no flights in step 2, yet runs step 3, "book a hotel for those flights". What is the bug?
- The plan is static and never checked against the observation.
- Re-plan after a surprise or failure: revise the remaining steps.