Lesson 5 of 6 in Foundations
Agents 101 — LLMs in a loop
The definition again, now with context
An agent is an LLM in a loop that decides its own next action until it judges the task done. Three properties: autonomy (the model picks steps), tool use (it acts on the world via tools), action loop (it iterates on tool results). Take away any one and you have something simpler — a workflow, a one-shot call, a chatbot.
Why loops matter
Real tasks rarely fit in one round-trip. 'Book a flight' needs to check dates, compare options, confirm preferences, then book. Each step's result changes what the model should do next. A loop lets the model plan, act, observe, plan again. Without the loop, you'd have to write out every possible branch — which defeats the purpose of using an LLM.
The simplest agent, in pseudocode
This is the entire idea, boiled down. Every production agent is a more elaborate version of this loop.
messages = [{"role":"user","content":user_task}]
for iteration in range(MAX_ITERATIONS):
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=4096,
tools=all_tools,
messages=messages
)
messages.append({"role":"assistant","content":response.content})
if response.stop_reason == "end_turn":
break # Claude thinks it's done
if response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = execute_tool(block.name, block.input)
tool_results.append({
"type":"tool_result",
"tool_use_id":block.id,
"content":str(result)
})
messages.append({"role":"user","content":tool_results})
continue
break # any other stop_reason: bail outThe stop_reason contract
The loop's termination is driven by stop_reason. end_turn = Claude is done. tool_use = Claude wants to call tools; execute them and continue. Other values (max_tokens, stop_sequence) usually mean 'something unexpected happened, bail.' Do NOT parse Claude's text for termination — this is the single most important rule for reliable agents (see D1L2).
When you DON'T need an agent
If the steps of the task are known in advance, don't build an agent. Write a workflow: extract → validate → transform → save. Agents cost more, run longer, and fail in less predictable ways than fixed workflows. Use them when the model's decisions at runtime are what determines the path.
This is the foundation of everything
Every pattern in D1 (subagents, orchestrator-workers, parallelization) is a variation on this loop. Every scenario on the exam assumes you can reason about how the loop should terminate, delegate, or escalate. Get comfortable with the basic loop, and the rest is engineering choices around it.
Takeaways
- Agent = LLM in a loop that picks its own next step
- The loop drives on stop_reason (end_turn / tool_use)
- Tool_use? Execute, append result, loop. end_turn? Done.
- Workflows beat agents when steps are knowable in advance
- Everything advanced is a variation on this basic loop