Skip to content

Lesson 13 of 40Agents

What Is an Agent?

Explain what makes an AI agent (a model, tools, a loop and an environment), how tool use works, and when an agent is the wrong choice.

15 min read0/5 questions

You have been using agents for a whole unit: Claude Code and Copilot's agent mode both read, act and check in a loop. Now you will look inside one. "Agent" is the most stretched word in AI right now. It gets stuck on chatbots, on scripts with one model call, and on products that run for an hour on their own. This lesson gives you a precise definition you can use: what parts an agent has, how a model "uses" a tool when all it can do is write text, what makes the loop stop, and how to tell when you should build something simpler. Everything in the rest of this unit builds on these ideas.

Four parts

An agent is a language model that works toward a goal by repeatedly choosing actions, seeing what happened, and choosing again. It has four parts:

  1. The model (an LLM). It reads everything in its context and decides the next step. It is the only part that "thinks".
  2. Tools. Functions the model is allowed to ask for: read a file, run a command, search the web, query a database. Each tool has a name, a description, and a list of inputs.
  3. The loop. Plain code that sends the conversation to the model, runs whatever tool it asked for, adds the result to the conversation, and sends it back. Again and again.
  4. The environment. The world the tools touch: your repo, a terminal, a browser, an API. The environment is where the real effects happen, and where the model gets feedback (a test failed, the file does not exist).

Take away any one and you no longer have an agent. A model with no tools can only talk. Tools with no loop give you one action and then stop. A loop with no environment has nothing to learn from.

The agent loop
You: the goalYouthe goalLoop: your codeLoopyour codeModel: picks next stepModelpicks next stepTools: read, edit, runToolsread, edit, runEnvironment: repo, shell, webEnvironmentrepo, shell, webtaskcontexttool callrun itactresult

You hand the loop a goal, not a list of steps.

1/5

How tool use actually works

A model only produces text. It cannot open a file or press Enter. So how does it "use a tool"?

You describe each tool to the model in the request: its name, what it does, and what inputs it takes (as a small JSON schema). When the model decides it needs a tool, it does not write a normal answer. It writes a structured tool call instead: the tool name plus the inputs, as JSON. The API marks the response so your code knows a tool is wanted.

Then the work passes to you:

  • The model asks. "Call read_file with {"path": "orders.csv"}."
  • Your code runs it. Your program reads the file, with whatever checks and permissions you choose.
  • The result goes back. You add the output to the conversation as a tool result and call the model again.

That division of labour matters. The model never touches your machine directly. Every action passes through code you wrote, which is where you add limits, approvals and logging. Claude Code is exactly this pattern: the model asks for Bash or Edit, and the harness (the program around the model) decides whether to run it or ask you first.

One tool call, end to end
YouLoopModelTooltotal of all orders?goal + tool listcall read_file(orders.csv)read_file(orders.csv)id,amount ...history + tool resultThe total is 100.

The goal arrives.

1/7
Quick check
An agent 'deletes a file'. Which part actually deleted it?
Need a nudge? A hint rules out a wrong answer.

Watch a loop run

Here is a complete agent loop in plain Python. The model is fake: a function with hard-coded rules, so it runs without an API key. Everything else is real. The tools are real functions, and the loop really runs them and feeds results back. Run it, then read the run_agent function: that loop is the heart of every agent you will use.

Python
# A tiny "filesystem" the tools can seeFILES = { "orders.csv": "id,amount\n1,40\n2,25\n3,35", "notes.txt": "Remember to check orders.csv",} # Tools: plain Python functionsdef list_files(): return ", ".join(FILES) def read_file(path): return FILES.get(path, f"error: no file called {path}") def add(numbers): return str(sum(numbers)) TOOLS = {"list_files": list_files, "read_file": read_file, "add": add} # A fake model: looks at the history and decides the next step.# A real LLM makes this decision itself; here it is hard-coded.def fake_model(history): last = history[-1] if last["role"] == "user": return {"tool": "list_files", "args": {}} if last["tool"] == "list_files": return {"tool": "read_file", "args": {"path": "orders.csv"}} if last["tool"] == "read_file": rows = last["result"].splitlines()[1:] amounts = [int(r.split(",")[1]) for r in rows] return {"tool": "add", "args": {"numbers": amounts}} return {"answer": f"The orders total {last['result']}."} # The agent loop: real code, the same shape as a real agentdef run_agent(goal, max_turns=5): history = [{"role": "user", "content": goal}] for turn in range(1, max_turns + 1): step = fake_model(history) if "answer" in step: print(f"turn {turn}: done -> {step['answer']}") return step["answer"] result = TOOLS[step["tool"]](**step["args"]) print(f"turn {turn}: {step['tool']}({step['args']}) -> {result!r}") history.append({"role": "tool", "tool": step["tool"], "result": result}) print("stopped: hit max_turns") run_agent("What is the total of all orders?")
Output
Press Run (⌘ Enter) to see what happens.

Notice that nobody told the loop "first list files, then read, then add". The fake model chose each step by looking at the latest result. With a real LLM, those choices come from the model reading the history, which is why the same loop can handle tasks you never planned for.

The history only ever grows. Each turn adds one more result, and the model is sent the whole thing every time. That is why long agent runs get expensive and why the context fills up.

Predict the outputPython

What does this print?

history = ["goal"]
for tool in ["list_files", "read_file", "add"]:
  history.append(tool + " result")
print(len(history))
Need a nudge? Hints walk you through it.

Stop conditions

A loop that never ends is a bug that costs money. Every agent needs clear ways to stop:

  • The model says it is done. It replies with a plain answer and no tool call. This is the normal exit.
  • A turn or step limit. A hard cap, like max_turns above. Claude Code subagents have a maxTurns setting for the same reason.
  • A budget. Stop after a number of tokens, dollars or minutes.
  • A check passes or fails for good. For coding agents: the tests pass, or the same error has repeated three times.
  • A human says stop. In Claude Code, Esc interrupts at any moment.

Models get stuck in ways that look busy. This one asks for the same missing file forever:

Python
def stuck_model(history): # A confused model that keeps asking for the same file forever return {"tool": "read_file", "args": {"path": "missing.txt"}} def run_agent(goal, model, max_turns=4): history = [{"role": "user", "content": goal}] for turn in range(1, max_turns + 1): step = model(history) if "answer" in step: return step["answer"] result = "error: no file called " + step["args"]["path"] print(f"turn {turn}: {step['tool']} -> {result}") history.append({"role": "tool", "result": result}) print(f"stopped after {max_turns} turns without an answer") run_agent("Summarise missing.txt", stuck_model)
Output
Press Run (⌘ Enter) to see what happens.

Without max_turns, that runs until something external kills it. Always decide the limit before you start the loop, not after the bill arrives.

Workflow or agent?

Not every system with an LLM and some code is an agent. There is a useful line between two designs:

  • A workflow is code-driven. Your program decides the steps in a fixed order and calls the model inside some of them. "Summarise the ticket, then classify it, then draft a reply." The model fills in each step but never chooses what comes next.
  • An agent is model-driven. You give a goal and tools, and the model decides which step to take, how many, and when to stop.
Single callWorkflowAgent
Who picks the stepsNobody, one stepYour codeThe model
PredictableVeryMostlyLess
Cost and latencyLowestMediumHighest, varies
Good forClassify, extract, summariseKnown multi-step processesOpen-ended tasks with feedback

The official advice is to start at the simplest tier that works: a single call, then a workflow, and only then an agent. Most features in real products are single calls or workflows. The lesson on shipping AI features goes deeper on this choice.

Match the pairs0/4 matched

Match each task to the simplest design that fits.

Choose an item, then its match on the other side.

When not to use an agent

Agents are slower, cost more, and are harder to predict than a single call. Before you build one, ask four questions:

  1. Complexity. Is the task genuinely open-ended, with steps you cannot list in advance? If you can write the steps down, write a workflow.
  2. Value. Is the result worth the extra tokens and time? Running an agent to rename one variable is waste.
  3. Viability. Can a model actually do it well today? Try it by hand in a chat first. If the model fails with a human guiding it, a loop will not save it.
  4. Cost of error. Can mistakes be caught and undone? Code has tests, review and git. Sending emails to customers or moving money does not roll back easily, so those need a human approval step or no agent at all.

A coding agent passes all four well: code tasks are open-ended, valuable, within current models' ability, and errors are caught by tests and undone with version control. That is why coding was one of the first places agents worked.

Quick checkPick all that apply
Which of these are good reasons NOT to use an agent? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Put one turn of an agent loop in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
agent
A model that works toward a goal by choosing tool calls in a loop, using feedback from its environment.
tool
A function described to the model by name, description and input schema, which your code runs on request.
tool call
A structured request from the model to run a named tool with specific inputs.
harness
The program around the model that runs the loop, executes tools and enforces permissions, like Claude Code.
workflow
A system where code decides the order of steps and calls the model inside them.
stop condition
A rule that ends the loop: a final answer, a turn limit, a budget, a passing check, or a human.