◆ AI All-in-One

Level 2 Agentic Coding · Building with AI

AI Agents

An agent is a language model that uses tools in a loop, deciding its own next step from what it observes until the goal is reached. This chapter builds one from scratch, covers the simpler workflow patterns you should try first, and explains how agents fail.

Level
●●●●● Intermediate
Reading
13 min
To learn it well
1.5 hours to read, a day to build and break your own
↗ Plan a path here

Read first

Tool Use and Function CallingChain-of-Thought and Reasoning Prompts

This leads to

AI Coding Assistants and AgentsMulti-Agent Systems
The full path from zero — 9 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Large Language Models, Explained Simply
  5. Using LLM APIs
  6. Prompt Engineering
  7. Structured Output and JSON
  8. Chain-of-Thought and Reasoning Prompts
  9. Tool Use and Function Calling
  10. AI Agents

Read them roughly in this order. See it on the concept map →

Why it matters

A single model call answers a single question. Plenty of useful work doesn't fit in one question. "Fix the failing test in this repository." "Find the three cheapest flights that fit my calendar." "Research this company and write a two-page brief with sources." Nobody can write down every step of these tasks in advance, because each step depends on what the previous one turned up.

An AI agent handles this kind of task. It is a model that uses tools in a loop: it looks at the situation, picks an action, sees the result, and decides what to do next, until it judges the goal is met. Coding assistants that edit and test whole projects (AI Coding Assistants and Agents), research assistants that search dozens of pages, and "computer use" models that click through websites are all agents.

Agents are also oversold. Many problems that get called "agent problems" are solved more cheaply and reliably by a fixed sequence of model calls, which this chapter calls a workflow. So this chapter does three things. It builds an agent from scratch so you can see there is no magic. It lays out the workflow patterns to reach for first. And it explains the ways agents fail, so you know what to guard against.

The intuition

Compare a recipe with a new kitchen assistant.

A recipe is a workflow. Chop, then fry, then season. The steps are fixed in advance by whoever wrote it. It is predictable and easy to check, but it can't adapt if the shop was out of onions.

A kitchen assistant with the goal "make dinner for four from what's in the fridge" is an agent. They open the fridge (observe), decide on a dish (think), start cooking (act), taste it (observe again) and adjust. They choose their own steps. That flexibility is the point, and it is also the risk: they might wander off, burn something, or decide dinner is "done" when it isn't.

In software terms, the assistant's hands are the tools, the fridge and stove are the environment, and tasting is feedback. An agent needs good feedback at every step, from running the code, reading the search result or checking the file, because the model's own sense of progress isn't reliable on its own.

Goal task, tools, instructions Model: think and choose next tool call, or "I am finished" Final answer verified, then shown Your code acts runs the tool call Environment files, shell, web, APIs, DBs Observation result appended to transcript act read or change result or error observe done Stop when any is true • the model gives a final answer • step limit reached • token or money budget spent • stuck: same call repeated • next action needs a human's OK
Fig. 1 The agent loop. The model chooses an action, your code carries it out in the environment, and the result comes back as an observation. The loop ends when a stop condition fires: the model says it is done, a step or cost budget runs out, it gets stuck, or a human needs to approve.

Key idea An agent is a model using tools in a loop, steering by the feedback from each step. Agents trade predictability for flexibility. Use one only when the steps truly can't be fixed in advance, and give it clear feedback, a budget and a way to stop.

How it works

Workflows versus agents

Anthropic's widely cited essay Building Effective Agents (December 2024) draws a useful line:

  • A workflow is a system in which model calls and tools are wired together by predefined code paths. You decide the steps. The model fills in each one.
  • An agent is a system in which the model dynamically directs its own process and tool usage. The model decides the steps.

Both are built from the same block, which the essay calls the augmented LLM: a model plus retrieval, tools and some form of memory. The question is only who chooses what happens next, your code or the model.

The five workflow patterns

Try these before building an agent. Each one is a few dozen lines of ordinary code around model calls.

1 Prompt chaining fixed steps; a check (gate) between them In LLM 1 gate LLM 2 Out fail: stop or retry 2 Routing classify, then send to a specialist In Router refunds tech general Out 3 Parallelisation sectioning or voting; code combines In LLM LLM LLM combine in code Out 4 Orchestrator-workers the model decides the subtasks In Orchestrator plans worker worker worker merge LLM Out 5 Evaluator-optimizer draft, critique, revise until good In Generator Evaluator draft feedback Out pass Agent the model chooses every next step Goal LLM Environment action observation stop
Fig. 2 The five workflow patterns from Building Effective Agents. In each, your code fixes the shape. Only in the agent at the bottom does the model choose its own path.
  1. Prompt chaining. Split a task into fixed steps, each a model call whose output feeds the next. You can put a programmatic check (a gate) between steps. Example: write an outline, check that it covers the required sections, then write the document from the outline. You trade a little latency for higher accuracy, because each call has an easier job.
  2. Routing. A first call (or a cheap classifier) labels the input, and code sends it to a specialised prompt or model. Example: customer messages go to "refund", "technical" or "general" handlers. Easy questions can go to a small, cheap model and hard ones to a large model.
  3. Parallelisation. Run several calls at once and combine the results in code. There are two flavours. Sectioning splits a task into independent parts, such as checking a contract for five different risks in five separate calls. Voting runs the same task several times and takes a majority or a threshold, such as asking three times whether some code has a security flaw and flagging it if any one says yes.
  4. Orchestrator-workers. A central model looks at the task, decides which subtasks are needed, hands them to worker calls and merges their answers. Unlike sectioning, the subtasks aren't known in advance. Example: a code change that touches an unknown number of files. This is the doorway to Multi-Agent Systems.
  5. Evaluator-optimizer. One call produces an answer, another critiques it against clear criteria, and the first revises. Loop until the critic is satisfied or a round limit is hit. Example: a translation polished over several rounds. It works when you can state what "good" means, a theme that returns in Evaluating LLM Applications.

The agent loop

A true agent has no fixed sequence. Its skeleton is the tool-call loop with more freedom and more rounds:

  1. Give the model a goal, a set of tools and instructions.
  2. Call the model. It either requests one or more tool calls, or says it is finished.
  3. Run the tools and append the results (the observations) to the transcript.
  4. Check the stop conditions. If none has fired, go back to step 2.

The stop conditions are where most of the engineering goes. A robust agent stops when any of these happens:

  • the model returns a final answer instead of a tool call,
  • a step limit is reached (say 30 tool calls),
  • a cost or time budget is spent (tokens, dollars, minutes),
  • it is stuck: the same call with the same arguments repeats, or nothing has changed for several steps,
  • an action needs human approval: deleting data, spending money, sending email.

ReAct: think out loud, then act

Before native tool calling existed, the ReAct paper (Yao et al., 2022) showed that models act better when they alternate between writing a short piece of reasoning and taking an action. A trace looks like this:

Thought: I need to know which config file has debug turned on. List the files first.
Action: list_files()
Observation: ['app.cfg', 'worker.cfg']
Thought: Check each one.
Action: read_file("app.cfg")
Observation: name=shop / debug=false
Action: read_file("worker.cfg")
Observation: threads=4 / debug=true
Thought: worker.cfg is the one. Rewrite it with debug=false.
Action: write_file("worker.cfg", "threads=4\ndebug=false")
Observation: wrote 21 chars
Thought: Done.
Final answer: worker.cfg had debug=true; I set it to false.

Reasoning between actions helps the model keep track of the plan and notice surprises. It is Chain-of-Thought and Reasoning Prompts interleaved with tool use. Modern APIs make the "Action" lines structured tool calls, and reasoning models often do the "Thought" part internally. The pattern remains the mental model for almost every agent.

Why agents fail: compounding errors

Suppose each step of an agent's work is right 95% of the time and the steps are independent. Then the chance that every step of a task is right is pnp^n, where pp is the per-step success rate and nn the number of steps:

P(all n steps right)=p nP(\text{all } n \text{ steps right}) = p^{\,n}
Per-step success pp 5 steps 10 steps 20 steps
0.95 0.77 0.60 0.36
0.99 0.95 0.90 0.82

At 95% per step, a 20-step task succeeds only 36% of the time. This compounding error is why long agent runs go wrong so often. It is also why feedback matters so much: an agent that notices a failed step (a test fails, a file isn't found) and corrects it is no longer a chain of independent coin flips. Good agents are built around checkable feedback, not around hoping each step is right.

The agent-computer interface

People spend a lot of care on user interfaces. The tools an agent uses deserve the same care, and the SWE-agent paper (2024) named this the agent-computer interface. Practical rules:

  • Give tools clear names, descriptions and examples, as you would document a function for a new colleague.
  • Return compact, informative results. "File saved (21 characters). Note: 2 other files also contain debug=true" beats a silent success.
  • Make mistakes hard. Anthropic's essay gives the example of requiring absolute file paths after their agent kept getting relative paths wrong.
  • Prefer a few powerful, well-tested tools to dozens of overlapping ones.

In code

Here is a complete agent loop with tools, an environment and stop conditions. A real model is non-deterministic and costs money, so to test the control flow we plug in a scripted fake model that replays a fixed list of replies. Swapping in a real model later changes one function. Everything else, including the guards, stays the same. This runs as written.

import json

FILES = {"app.cfg": "name=shop\ndebug=false", "worker.cfg": "threads=4\ndebug=true"}
def list_files():            return sorted(FILES)
def read_file(path):         return FILES[path]
def write_file(path, text):  FILES[path] = text; return f"wrote {len(text)} chars"
TOOLS = {"list_files": list_files, "read_file": read_file, "write_file": write_file}

class ScriptedModel:                     # stands in for an LLM so the loop is testable
    def __init__(self, script): self.script = list(script)
    def __call__(self, messages): return self.script.pop(0)

def call(name, **args): return {"stop_reason": "tool_use", "tool": name, "input": args}
def done(text):         return {"stop_reason": "end_turn", "text": text}

def run_agent(task, model, max_steps=8):
    messages, seen = [{"role": "user", "content": task}], set()
    for step in range(1, max_steps + 1):
        reply = model(messages)
        messages.append({"role": "assistant", "content": reply})
        if reply["stop_reason"] == "end_turn":                 # stop: model is finished
            return f"DONE in {step} steps: {reply['text']}"
        key = json.dumps([reply["tool"], reply["input"]], sort_keys=True)
        if key in seen:                                        # stop: stuck in a loop
            return f"STOPPED at step {step}: repeated {reply['tool']}{reply['input']}"
        seen.add(key)
        try:
            result = TOOLS[reply["tool"]](**reply["input"])
        except Exception as e:
            result = f"Error: {e!r}"                           # errors are observations too
        print(f"  step {step}: {reply['tool']}{reply['input']} -> {result!r}")
        messages.append({"role": "user", "content": {"tool_result": result}})
    return f"STOPPED: hit max_steps={max_steps}"               # stop: budget spent

good = ScriptedModel([call("list_files"), call("read_file", path="app.cfg"),
                      call("read_file", path="worker.cfg"),
                      call("write_file", path="worker.cfg", text="threads=4\ndebug=false"),
                      done("worker.cfg had debug=true; I set it to false.")])
print(run_agent("Turn off debug mode wherever it is on.", good))
assert FILES["worker.cfg"].endswith("debug=false")

stuck = ScriptedModel([call("read_file", path="secrets.cfg")] * 2)
print(run_agent("Read the secrets file.", stuck))
#   step 1: list_files{} -> ['app.cfg', 'worker.cfg']
#   step 2: read_file{'path': 'app.cfg'} -> 'name=shop\ndebug=false'
#   step 3: read_file{'path': 'worker.cfg'} -> 'threads=4\ndebug=true'
#   step 4: write_file{'path': 'worker.cfg', 'text': 'threads=4\ndebug=false'} -> 'wrote 21 chars'
# DONE in 5 steps: worker.cfg had debug=true; I set it to false.
#   step 1: read_file{'path': 'secrets.cfg'} -> "Error: KeyError('secrets.cfg')"
# STOPPED at step 2: repeated read_file{'path': 'secrets.cfg'}

To make it real, replace ScriptedModel with a function that sends messages and the tool schemas to a model API and converts its reply into the same {"stop_reason", "tool", "input"} shape, exactly as in the Tool Use and Function Calling chapter. Keep the scripted model too. Scripted runs make good unit tests for your guards: does the loop stop on a repeat, survive a tool error, respect max_steps? Testing the model's judgment is a different job, covered in Evaluating LLM Applications.

SDKs and frameworks can run this loop for you: Anthropic's tool runner and Agent SDK, the OpenAI Agents SDK, Hugging Face's smolagents, LangGraph and others. They save boilerplate. Build the loop yourself once anyway, so you can read their traces when something goes wrong.

Common pitfalls

  • Building an agent when a workflow would do. If you can write the steps down, write them as code. You get lower cost, lower latency, and behaviour you can test.
  • Loops and thrashing. The agent repeats the same search, or flips a file back and forth between two versions. Detect repeats, cap steps, and show the model what it already tried.
  • Declaring victory early. Models often say "Done!" when the task is half-finished. Verify completion with code (run the tests, check the file exists) instead of trusting the claim.
  • Claimed but unperformed actions. A model may say it saved the file without calling the tool. Trust the tool log, not the prose.
  • Context overflow. Every observation stays in the transcript. After 50 steps of long tool outputs the context is huge, slow and expensive, and the model starts losing track of the goal. Truncate outputs and summarise old steps. See Context Engineering and Memory.
  • Gaming the check. Told to "make the tests pass", an agent may delete or weaken the tests. Protect your success criteria from the agent, and review diffs.
  • Runaway cost. A stuck agent burns tokens fast, because each step re-sends the growing transcript. Set hard budgets and alerts.

Watch out An agent with tools can take real actions on the basis of text it read moments ago. A web page or email in its context can carry prompt injection that redirects it. Run agents with the least privilege possible, in a sandbox when they execute code, and put a human approval step in front of anything irreversible.

Where it leads

A bit of history

The word "agent" is old in AI. Classic textbooks define an agent as anything that perceives its environment and acts on it, and reinforcement learning has always been about agents. The language-model version took shape in 2022 and 2023. ReAct (Yao et al., Princeton and Google, October 2022) interleaved reasoning with actions. In spring 2023 open-source projects such as AutoGPT and BabyAGI wired GPT-4 into open-ended loops. They caught the public imagination but mostly showed how quickly unguided agents drift and loop. Reflexion (Shinn et al., 2023) had agents write lessons from failures into memory and retry. SWE-agent (Yang et al., 2024) showed that a carefully designed tool interface lifted an agent's success at fixing real GitHub issues. Through 2024 and 2025, models trained specifically for long tool-using tasks, together with practical guides like Building Effective Agents, turned agents from demos into products: coding agents, deep-research tools and browser-using assistants.

Try it

  1. Add a max_cost guard to run_agent: give each tool a cost (say read_file = 1, write_file = 5) and stop when the total passes a limit. Write a scripted model that trips it.
  2. Add an approval gate: before any write_file, call input("Approve? [y/n]"), and on "n" send back the observation "User declined" instead of running the tool.
  3. Using the table above, how high must per-step accuracy be for a 30-step task to succeed 90% of the time with no error correction?

Hint for 3: solve p30=0.9p^{30} = 0.9, so p=0.91/30p = 0.9^{1/30}. You should get about 0.9965.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You need to turn each support email into a summary, then translate it, then file it. The steps never change. What should you build?

  2. Each step of an agent is right 95% of the time and errors are not corrected. Roughly how often does a 20-step task succeed completely?

  3. Your agent keeps calling the same search with the same arguments. Which guard in the agent loop addresses this most directly?

  4. Told to "make the tests pass", an agent reports "Done!". What is the safest way to confirm the task is really complete?

  5. In the evaluator-optimizer pattern, what is required for it to work well?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Building Effective Agents

Anthropic · 2024 · Intermediate · Free

A clear, practical essay on agent patterns (workflows vs agents) and when to use each.

Course

Hugging Face Agents Course

Hugging Face · Beginner · Free

A free course on how agents work (thought, action, observation), with hands-on units building agents in smolagents, LlamaIndex and LangGraph.

Article

LLM Powered Autonomous Agents

Lilian Weng · 2023 · Intermediate · Free

A widely read survey of agent components (planning, memory, tool use) with the key papers behind each.

Article

Writing effective tools for agents

Anthropic · 2025 · Intermediate · Free

Practical advice on designing tools a model can use well: choosing the right tools, naming, returning meaningful context, token-efficient outputs and evaluating tools.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/ai-agents.md