What Are AI Agents?
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
"Agent" is one of the most overused words in AI right now. Some people mean a chatbot with a button, some mean a script that calls a model three times, and some mean software that runs for hours on its own. This lesson pins the word down using the definition Anthropic gives in its engineering guidance, then shows the smallest version you can actually run. After that, the rest of the module is about building one properly.
What you'll learn
- What makes something an agent, and how that differs from a workflow.
- The three parts every agent has: a model, tools and a loop.
- What an agent can and can't be trusted with.
- When you shouldn't build one at all.
Before you start
The definition that's worth using
Anthropic's "Building effective agents" article draws one line and it's a useful one. Both of these are called "agentic systems", but they're built differently:
- A workflow is a system where the model and tools are orchestrated through predefined code paths. You wrote the steps. The model fills in each step, but your code decides what happens next.
- An agent is a system where the model dynamically directs its own process and tool use, staying in control of how it gets the task done.
So the test is simple: who decides the next step? If your code does, it's a workflow. If the model does, it's an agent. Neither is better in general. Workflows are more predictable. Agents are more flexible. Most of the useful things people ship are somewhere in between, which is why lesson 6.3 spends time on workflows before we get to loops.
The three parts
Strip away the marketing and an agent is three things:
- A model that reads the situation and decides what to do.
- Tools that let it look things up or change things. Without tools it can only talk.
- A loop that keeps going: the model asks for a tool, your code runs it, the result goes back, and the model decides again. It stops when the model says it's finished or when a limit is hit.
You already built the second and third parts in Module 4. An agent is mostly that loop plus the discipline around it: limits, safety and a way to see what happened.
task ──► MODEL decides ──► tool call? ──yes──► YOUR CODE runs the tool
▲ │ │
│ no │
└──── result ──────┼───────────────────────┘
▼
final answer
(and a budget that can stop the loop at any point)
The smallest runnable agent
Here is a complete, small agent. It has a budget, it turns tool failures into information, and it can be paused. We'll use this same class through the whole module, so it's worth reading once now. Don't worry about the pause feature yet; lesson 6.9 covers it.
import json
import time
import uuid
from dataclasses import dataclass, field
from typing import Any, Callable
@dataclass
class Budget:
max_iterations: int = 10
max_total_tokens: int = 60_000
max_seconds: float = 90.0
max_tool_calls: int = 20
@dataclass
class Tool:
definition: dict
func: Callable[..., str]
risk: str = "read" # read | write. A "write" tool waits for a person before it runs.
@dataclass
class Run:
status: str # done | paused | stopped
reason: str = "" # why it stopped: end_turn, max_iterations, token_budget, time_budget, tool_budget, ...
text: str = ""
state: dict = field(default_factory=dict) # plain JSON; save it, and resume later
pending: list = field(default_factory=list) # [{"id","tool","input"}] waiting for a person
trace: list = field(default_factory=list)
def block_to_dict(block) -> dict:
"""Turn an SDK content block (or a dict, in tests) into plain JSON we can store and send back."""
if isinstance(block, dict):
return block
if block.type == "text":
return {"type": "text", "text": block.text}
if block.type == "tool_use":
return {"type": "tool_use", "id": block.id, "name": block.name, "input": dict(block.input)}
return block.model_dump(exclude_none=True)
class Agent:
def __init__(self, client, model: str, tools: dict[str, Tool], system: str, budget: Budget | None = None, max_tokens: int = 1024):
self.client, self.model, self.tools, self.system = client, model, tools, system
self.budget, self.max_tokens = budget or Budget(), max_tokens
# ---- public API -------------------------------------------------------------------------------------------
def run(self, user_text: str) -> Run:
state = {"messages": [{"role": "user", "content": user_text}], "iterations": 0, "tokens": 0, "tool_calls": 0, "elapsed": 0.0}
return self._loop(state, [])
def resume(self, state: dict, decisions: dict[str, bool]) -> Run:
"""Continue a paused run. decisions maps each pending tool_use id to approve (True) or reject (False)."""
state = json.loads(json.dumps(state)) # never mutate the caller's copy
waiting = state.pop("waiting")
trace: list = []
results = list(waiting["done"])
for item in waiting["pending"]:
if item["id"] not in decisions:
raise ValueError(f"No decision for {item['id']}")
if decisions[item["id"]]:
results.append(self._call(item["id"], item["tool"], item["input"], state, trace, approved=True))
else:
trace.append({"event": "rejected", "tool": item["tool"]})
results.append({"type": "tool_result", "tool_use_id": item["id"], "is_error": True,
"content": "A person declined this action. Do not try it again; tell the user it was not done."})
state["messages"].append({"role": "user", "content": self._ordered(waiting["order"], results)})
return self._loop(state, trace)
# ---- internals --------------------------------------------------------------------------------------------
@staticmethod
def _ordered(order: list[str], results: list[dict]) -> list[dict]:
by_id = {r["tool_use_id"]: r for r in results}
return [by_id[i] for i in order] # one result per tool_use, in the model's order
def _over_budget(self, state: dict) -> str | None:
b = self.budget
if state["iterations"] >= b.max_iterations: return "max_iterations"
if state["tokens"] >= b.max_total_tokens: return "token_budget"
if state["elapsed"] >= b.max_seconds: return "time_budget"
if state["tool_calls"] >= b.max_tool_calls: return "tool_budget"
return None
def _call(self, tool_use_id: str, name: str, tool_input: dict, state: dict, trace: list, approved: bool = False) -> dict:
state["tool_calls"] += 1
tool = self.tools.get(name)
if tool is None:
content, error = f"Unknown tool '{name}'. Available: {', '.join(sorted(self.tools))}.", True
else:
try:
content, error = str(tool.func(**tool_input)), False
except Exception as e: # noqa: BLE001 - a failed tool is information for the model
content, error = f"{type(e).__name__}: {e}", True
trace.append({"event": "tool", "tool": name, "input": tool_input, "error": error, "approved": approved})
return {"type": "tool_result", "tool_use_id": tool_use_id, "content": content, **({"is_error": True} if error else {})}
def _loop(self, state: dict, trace: list) -> Run:
defs = [t.definition for t in self.tools.values()]
while True:
if reason := self._over_budget(state):
trace.append({"event": "stopped", "reason": reason})
return Run("stopped", reason, state=state, trace=trace)
started = time.monotonic()
kwargs = {"model": self.model, "max_tokens": self.max_tokens, "system": self.system, "messages": state["messages"]}
if defs:
kwargs["tools"] = defs
response = self.client.messages.create(**kwargs)
state["elapsed"] += time.monotonic() - started
state["iterations"] += 1
state["tokens"] += response.usage.input_tokens + response.usage.output_tokens
content = [block_to_dict(b) for b in response.content]
state["messages"].append({"role": "assistant", "content": content})
if response.stop_reason == "pause_turn":
continue
if response.stop_reason != "tool_use":
text = "".join(b["text"] for b in content if b["type"] == "text")
trace.append({"event": "finished", "stop_reason": response.stop_reason})
return Run("done", response.stop_reason or "end_turn", text, state, trace=trace)
uses = [b for b in content if b["type"] == "tool_use"]
done, pending = [], []
for use in uses:
tool = self.tools.get(use["name"])
if tool and tool.risk == "write":
pending.append({"id": use["id"], "tool": use["name"], "input": use["input"]})
else:
done.append(self._call(use["id"], use["name"], use["input"], state, trace))
if pending:
state["waiting"] = {"order": [u["id"] for u in uses], "done": done, "pending": pending}
trace.append({"event": "paused", "pending": [p["tool"] for p in pending]})
return Run("paused", "approval_needed", state=state, pending=pending, trace=trace)
state["messages"].append({"role": "user", "content": self._ordered([u["id"] for u in uses], done)})
The tests for this file cover the normal loop, an unknown tool, a crashing tool, all four budget limits, a model that gets cut off at max_tokens and a paused run that is saved as JSON and resumed. We also ran it through the real Python SDK against a local mock of the Messages API to make sure the saved message format is accepted. We did not run it against the live API in these lessons, so test with your own key before you rely on it.
Using it
import anthropic
from agent import Agent, Tool
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
ORDERS = {"A100": "shipped, arriving Thursday"}
lookup = Tool(
definition={
"name": "lookup_order",
"description": "Look up one order by its id, for example A100. Returns its status. Does not return payment details.",
"input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]},
},
func=lambda order_id: ORDERS.get(order_id, "No such order"),
)
agent = Agent(client, "claude-sonnet-5-5", {"lookup_order": lookup}, system="You answer questions about orders. Use the tool; never guess.")
run = agent.run("Where is order A100?")
print(run.status, "-", run.text)
print(run.state["iterations"], "model calls,", run.state["tokens"], "tokens")
Notice what you didn't write: any code that says "first look up the order, then write the reply". The model chose to call the tool. That's the difference from a workflow.
What an agent is good at, and not
Anthropic's guidance is blunt about the trade: agents can handle open-ended problems where you can't predict the steps in advance, but they cost more and can compound errors. Their advice is to find the simplest solution first and only add complexity when it clearly helps. In practice that often means a single model call with good prompts, or a fixed workflow, is the right answer. An agent earns its place when the number of steps really can't be known ahead of time.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
Suppose a small shop gets emails like "my parcel hasn't come, and the box was damaged last time too". A fixed workflow struggles because one customer needs an order lookup, another needs a lookup and a refund proposal, and a third needs neither. A model with two tools and a loop can pick the right path per email. That flexibility is the reason to use an agent. If every email were an order-status question, a single tool call in a workflow would be simpler and cheaper, and that's what you should build.
Mistakes to avoid
- Calling anything with a model "an agent". If your code fixes the steps, it's a workflow, and that's fine.
- Building an agent for a task with a known, fixed sequence.
- No limits on the loop. A confused model can keep calling tools until your budget is gone.
- Judging an agent by one successful demo. Test it on the strange inputs too.
Security notes
An agent acts on text it reads, and some of that text comes from outside: emails, web pages, files. Anyone who can put text in front of the model can try to steer it. So give an agent the fewest tools it needs, keep anything that changes money or data behind a human decision (lesson 6.9), and treat every tool result as untrusted data, not instructions.
Cost and speed
Every loop iteration is another model request that re-reads the whole conversation so far. More steps means more tokens and more waiting. Anthropic's write-up on their own multi-agent research system reports that agents use roughly four times the tokens of a plain chat and multi-agent systems roughly fifteen times, for their research workload. Treat those as a warning about the direction of the cost rather than a forecast for your task, and measure your own.
Key takeaways
- Workflow: your code decides the steps. Agent: the model decides. Pick the simplest one that works.
- An agent is a model, tools and a loop, plus limits and safety.
- Agents suit open-ended tasks where the steps can't be known in advance.
- Always bound the loop, and keep risky actions behind a person.
Lesson recap: your code decides in a workflow, the model decides in an agent, and an agent is a model, tools and a loop.
Quick quiz
- What decides the next step in a workflow, and what decides it in an agent?
- Name the three parts of an agent.
- Why should an agent's loop have limits?
- Give one task that suits an agent and one that doesn't.
- Why treat tool results as untrusted?
Answers and explanations
- In a workflow, your code does, along predefined paths. In an agent, the model does, dynamically.
- A model, tools, and a loop that feeds tool results back until the model finishes.
- Because a confused or manipulated model could otherwise keep calling tools, spending tokens and taking actions without end. Limits on iterations, tokens, time and tool calls bound the damage.
- Suits: open-ended support triage where each email needs different tools. Doesn't: always looking up one order status, which a single fixed call handles cheaper and more predictably.
- Results can contain text written by someone else, such as a customer email or a web page, and that text may contain instructions aimed at the model.
Official references and further reading
Related tutorials