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
- Builds on
- 9 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 9 concepts before this one
- What Is AI?
- Python for AI
- How Machines Learn
- Large Language Models, Explained Simply
- Using LLM APIs
- Prompt Engineering
- Structured Output and JSON
- Chain-of-Thought and Reasoning Prompts
- Tool Use and Function Calling
- 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.
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.
- 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.
- 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.
- 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.
- 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.
- 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:
- Give the model a goal, a set of tools and instructions.
- Call the model. It either requests one or more tool calls, or says it is finished.
- Run the tools and append the results (the observations) to the transcript.
- 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 , where is the per-step success rate and the number of steps:
| Per-step success | 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
- Multi-Agent Systems: an orchestrator agent delegating to sub-agents, and when that is worth the cost.
- AI Coding Assistants and Agents: the most mature agents today, and what they show about feedback (tests) and tools (shell, editor).
- Model Context Protocol: a standard way to give any agent new tools.
- Context Engineering and Memory: managing memory and the transcript in long agent runs.
- Evaluating LLM Applications: measuring whether an agent actually completes tasks, step by step.
- Building AI Products: putting agents in front of users with guardrails and human oversight.
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
- Add a
max_costguard torun_agent: give each tool a cost (sayread_file= 1,write_file= 5) and stop when the total passes a limit. Write a scripted model that trips it.- Add an approval gate: before any
write_file, callinput("Approve? [y/n]"), and on "n" send back the observation"User declined"instead of running the tool.- 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 , so . You should get about 0.9965.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Building Effective Agents
A clear, practical essay on agent patterns (workflows vs agents) and when to use each.
Hugging Face Agents Course
A free course on how agents work (thought, action, observation), with hands-on units building agents in smolagents, LlamaIndex and LangGraph.
LLM Powered Autonomous Agents
A widely read survey of agent components (planning, memory, tool use) with the key papers behind each.
ReAct: Synergizing Reasoning and Acting in Language Models
Interleaving reasoning and tool actions. It is the template for most LLM agents.
Reflexion: Language Agents with Verbal Reinforcement Learning
Agents write short reflections on why an attempt failed, keep them in memory, and use them on the next try.
SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering
Shows that designing the agent's tools (file viewer, search, editor with linting) carefully, the agent-computer interface, greatly improves success at fixing real GitHub issues.
Writing effective tools for agents
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