Lesson 4.3 · 8 min read · about 55 min to master at a very slow pace
Designing the Agent Loop: Stopping, Memory and Errors
What a production agent loop needs beyond "call tools until done": step and cost limits, context management for long runs, memory across sessions, recovering from tool errors, and handing off to a human.
The loop, made safe
def run_agent(task, tools, max_steps=15, budget_eur=0.50):
messages = [system_prompt, user(task)]
for step in range(max_steps):
reply = llm(messages, tools)
if spent() > budget_eur:
return handoff("Budget reached", messages)
if reply.is_final:
return reply.text
for call in reply.tool_calls:
result = run_tool_safely(call) # validate, timeout, catch
messages.append(tool_result(call, result))
messages = compact_if_needed(messages)
return handoff("Step limit reached", messages)
Stopping conditions
Agents can loop: repeat the same search, alternate between two tools, or keep "improving" an answer. Always have:
- A step limit (often 10–30 tool calls).
- A cost or token budget per task.
- A wall-clock timeout.
- A graceful hand-off when any limit is hit: summarise what was found and pass it to a human, rather than failing silently.
Context management
Every tool result is appended to the conversation, so long runs grow the context until they are slow, expensive or overflow. The tactics:
- Keep tool outputs compact at the source (lesson 4.1).
- Summarise or drop old tool results once they have been used.
- Let the agent write notes to a scratchpad or file and re-read them, instead of carrying everything in context.
Memory across sessions
An agent has no memory between runs unless you build it. Common forms: a profile of stable facts (the client's preferences), a store of past outcomes retrieved like RAG, and task state saved so a long job can resume. Decide explicitly what is remembered, for how long, and who can see or delete it (this is personal data under GDPR if it is about people).
Errors are inputs
Tools fail: timeouts, missing records, rate limits. Catch every exception and return a clear error message to the model as the tool result. A good agent reads "Customer not found by email; try searching by phone" and adapts. An uncaught exception just kills the run.
Humans in the loop
For actions with consequences (sending an email, issuing a refund, changing a record), have the agent propose and a human approve. Start with approval for everything; remove it for an action type only when logs show the agent gets it right reliably.
Stuck? Common doubts
Questions real learners asked while studying this lesson. They stay closed so they don't spoil your own thinking: open only the ones you need.
First passHow do I pick the step limit?
Run the agent on your eval tasks and look at how many steps successful runs take. Set the limit comfortably above that (say the 95th percentile plus a margin). Runs that hit the limit are worth reading: they usually reveal a missing tool, a confusing tool description or a loop.
Going deeperShould I use several agents that talk to each other?
Only when one agent's context or tool set becomes too large, or sub-tasks are truly independent and can run in parallel. Multi-agent systems multiply cost and make failures harder to trace. A single agent with good tools is the right first version almost every time.
Cheatsheet
Stopping conditions
Context management
Uncaught tool errors
Check your understanding
Score 75% or more to master this lesson and earn XP. Answer first, then check.