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

stateless

Text in, text out. One pass, no tools, no memory beyond the prompt. Great for summarizing, drafting, classifying, extracting.

Agent

loop

An 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

system

Several 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#

ModelThe reasoning engine that reads context and chooses the next action
InstructionsSystem prompt: role, goal, constraints, when to stop, when to ask a human
ToolsFunctions it can call - search, code execution, APIs, databases - each with a clear schema
Perception / contextWhat it can see: the conversation, tool results, retrieved documents
MemoryShort-term (the context window) and long-term (stored facts, past episodes)
PlanningBreaking a goal into steps, explicitly or implicitly
GuardrailsLimits on actions, iteration caps, approval gates, output checks
The components every agent has in some form.
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:

  1. 01Thought'I need the current price.'
  2. 02Actioncall get_price('AAPL')
  3. 03ObservationTool returns 212.40
  4. 04DecideDone? Answer. Otherwise think again.

↺ Decide feeds back into Thought

Reasoning traces make actions more deliberate; observations ground the reasoning in real data instead of guesses.

Planning strategies#

StrategyHow it worksGood for
ReActThink → act → observe, one step at a timeExploratory tasks where each step depends on the last
Plan-and-executeWrite a full plan first, then execute steps (optionally re-planning)Longer tasks with a predictable structure; cheaper executor models
Self-correctionAfter 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:

Supervisor agentPlans, delegates, merges results
  • Research agentWeb + document search
  • Coding agentWrites and runs code
  • Analyst agentQueries data
  • Writer agentDrafts the final answer
The supervisor pattern. Each specialist has a narrow prompt and a small tool set, which makes each one more reliable.

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.

  1. 01OutlineLLM call 1
  2. 02GateHas 5 sections? Valid JSON?
  3. 03DraftLLM call 2
  4. 04GateUnder 800 words? No banned claims?
  5. 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.

  1. 01GenerateProduce a candidate
  2. 02EvaluateScore against criteria
  3. 03FeedbackSpecific fixes

↺ Feedback feeds back into Generate

Always cap iterations - an evaluator that never passes will loop forever.

Chain, workflow, or agent?#

Use...When...
A single LLM callThe 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 agentThe 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

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.