Step 1 of 4
Agent Fundamentals
LLMs vs agents vs agentic AI, the anatomy of an agent, and the five workflow patterns that cover most real systems.
15 min read
"Agent" is the most overloaded word in AI right now. This guide pins it down: what separates an agent from a plain LLM call, what an agent is made of, the patterns that cover most real systems - and the most useful skill of all, knowing when you don't need one. It finishes by building a working agent in about 50 lines of Python.
From single agent to multi-agent#
LLM vs agent vs agentic AI#
LLM call
statelessText in, text out. One pass, no tools, no memory beyond the prompt. Great for summarizing, drafting, classifying, extracting.
Agent
loopAn LLM in a loop that decides what to do next: call a tool, read the result, decide again - until the goal is met or it gives up.
Agentic system
systemSeveral agents and deterministic steps coordinated toward a larger goal, with memory, guardrails, and human checkpoints.
The defining feature of an agent is the model controls the control flow. In a workflow, your code decides the sequence of steps. In an agent, the model decides which step comes next based on what it observes. That flexibility is the whole point - and the whole risk.
Anatomy of an agent#
- Context window
- The finite amount of text (measured in tokens) a model can see at once - conversation, files, and tool results all compete for this space.
- Structured output
- Model responses constrained to a schema (usually JSON), so downstream code can parse them reliably instead of matching free text.
- Tool schema
- A JSON description of a tool's name, purpose, and parameter types that tells the model what the tool does and how to call it.
- Stop reason
- The API's signal for why generation stopped - 'end_turn' means the model chose to finish, 'tool_use' means it wants to call a tool next.
The ReAct loop#
Most agents run some version of ReAct - Reason + Act. The model alternates between thinking about what to do and taking an action, feeding each observation back in:
- 01Thought'I need the current price.'
- 02Actioncall get_price('AAPL')
- 03ObservationTool returns 212.40
- 04DecideDone? Answer. Otherwise think again.
↺ Decide feeds back into Thought
Planning strategies#
| Strategy | How it works | Good for |
|---|---|---|
| ReAct | Think → act → observe, one step at a time | Exploratory tasks where each step depends on the last |
| Plan-and-execute | Write a full plan first, then execute steps (optionally re-planning) | Longer tasks with a predictable structure; cheaper executor models |
| Self-correction | After acting, critique the result and retry (e.g., Reflexion) | Code generation, anything with a checkable outcome |
Going multi-agent#
When one agent's context gets overloaded with too many tools or responsibilities, split the work:
- Research agentWeb + document search
- Coding agentWrites and runs code
- Analyst agentQueries data
- Writer agentDrafts the final answer
Other topologies: hierarchical (supervisors of supervisors for large systems) and network/swarm (agents hand off to each other directly). Start with a supervisor - it's the easiest to debug.
5 agent design patterns#
Most production "agents" are actually workflows - predictable sequences of LLM calls orchestrated by code. These five patterns cover the vast majority of real systems.
1. Prompt chaining with validation gates#
Break a task into fixed steps, each LLM call consuming the previous output. Between steps, run a gate - a programmatic check that stops or retries the chain if something's wrong.
- 01OutlineLLM call 1
- 02GateHas 5 sections? Valid JSON?
- 03DraftLLM call 2
- 04GateUnder 800 words? No banned claims?
- 05PolishLLM call 3
2. Routing#
Classify the input first, then send it to a specialized handler: a different prompt, a cheaper model, a deterministic function, or a human. Routing lets you optimize each path separately. (There's a full guide on this: Routing & Decision Engines.)
3. Parallelization with merge#
Run independent LLM calls at the same time and combine the results. Two flavors:
- Sectioning - split a task into independent parts (review security, performance, and style in parallel).
- Voting - run the same task several times and aggregate (majority vote for classification, or flag disagreement for human review).
4. Orchestrator-workers#
A central LLM breaks down a task dynamically - it decides at runtime how many subtasks exist and what they are - delegates them to worker calls, and synthesizes the results. Unlike parallelization, the subtasks aren't known in advance. Typical example: a coding change that touches an unknown number of files.
5. Evaluator-optimizer#
One LLM generates; another evaluates against clear criteria and returns feedback; loop until the evaluator passes it or you hit an iteration cap. It works when there are clear evaluation criteria and iteration measurably helps - translation, writing to a spec, code that must pass tests.
- 01GenerateProduce a candidate
- 02EvaluateScore against criteria
- 03FeedbackSpecific fixes
↺ Feedback feeds back into Generate
Chain, workflow, or agent?#
| Use... | When... |
|---|---|
| A single LLM call | The task fits in one prompt with good context and examples |
| A workflow (patterns 1-5) | The steps are predictable and you want reliability, cost control, and easy debugging |
| An agent | The number and order of steps genuinely can't be known in advance, and mistakes are recoverable |
Build your first agent#
A complete tool-using agent with the Anthropic Python SDK. It can do arithmetic and look up (fake) weather, and it decides on its own which tools to call and when to stop.
import json
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
TOOLS = [
{
"name": "calculator",
"description": "Evaluate a basic arithmetic expression like '12 * (3 + 4)'.",
"input_schema": {
"type": "object",
"properties": {"expression": {"type": "string"}},
"required": ["expression"],
},
},
{
"name": "get_weather",
"description": "Get the current temperature in Celsius for a city.",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
]
def run_tool(name: str, args: dict) -> str:
if name == "calculator":
allowed = set("0123456789+-*/(). ")
if not set(args["expression"]) <= allowed:
return "error: unsupported characters"
return str(eval(args["expression"], {"__builtins__": {}})) # demo only
if name == "get_weather":
return json.dumps({"city": args["city"], "temp_c": 21}) # stub
return f"error: unknown tool {name}"
def agent(task: str, max_steps: int = 8) -> str:
messages = [{"role": "user", "content": task}]
for _ in range(max_steps): # guardrail: iteration cap
response = client.messages.create(
model="claude-sonnet-5", max_tokens=1024,
tools=TOOLS, messages=messages,
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use": # the model chose to answer
return "".join(b.text for b in response.content if b.type == "text")
results = [
{"type": "tool_result", "tool_use_id": b.id, "content": run_tool(b.name, b.input)}
for b in response.content if b.type == "tool_use"
]
messages.append({"role": "user", "content": results})
return "Stopped: step limit reached."
print(agent("If it's 21°C in Lisbon, what's that in Fahrenheit? Check the weather first."))
Everything from this guide is visible in those lines: the tools with schemas, the loop, observations fed back as tool results, the model deciding when it's done, and a guardrail (the step cap). Production agents add logging, retries, timeouts, permission checks on dangerous tools, and evaluation - covered in the Production AI track.
Papers behind this guide
ReAct: Reasoning + Acting
The foundation of modern AI agents - interleaving reasoning traces with tool use actions.
Google Brain, 2022
Reflexion
Agents that write verbal feedback on their own failures and retry - self-correction without weight updates.
2023
Chain-of-Thought Prompting
The paper that proved step-by-step reasoning dramatically improves LLM performance on complex tasks.
Google Brain, 2022