Handbooks / RAG & AI Agents / Chapter 6
Agent Loops and Memory
7 pages · ~5 min✓ Reviewed
Builds on Tool Calling. Next up: Agentic RAG.
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 |
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
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
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
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
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.