AI agents › Agent basics
What is an AI agent? The loop behind AI that takes action
What an AI agent is, how it loops through thinking, calling tools, and checking results, how it differs from a chatbot or a workflow, and when to use one.
If you’ve been following AI news at all, you’ve probably run into the word agent almost every day. That’s because coding tools and new products alike keep presenting themselves as agents. Yet the word is used in so many ways that it can be hard to pin down what it actually means.
Put simply, an AI agent is an AI system that, once you give it a goal, decides for itself what to do next and works through several steps using tools. It’s usually built from a large language model (LLM), the tools that model can use, and a loop that repeats until the work is done. An LLM is a model trained on a vast amount of text to read and write language, and it’s the kind of model ChatGPT and Claude run on. As for why the word comes up so often now, Anthropic explained it this way in its December 2024 post Building effective agents. Agents are emerging in production as LLMs mature in key capabilities such as understanding complex inputs, reasoning and planning, using tools reliably, and recovering from errors. Then in February 2025, Anthropic released Claude Code, a tool for agentic coding, as a research preview.
How an agent differs from a chatbot
A chatbot answers your question once, in text, and its turn is over. That’s why, even if the answer tells you to fix a file, you’re still the one who fixes it. An agent, on the other hand, goes all the way. It reads the file, makes the change, runs the tests, and if they fail, goes back and fixes it again. It’s a bit like the difference between asking a friend for directions and sending a friend on an errand. A friend on an errand decides on their own whether to try the shop next door when the shelf is empty.
OpenAI’s practical guide to building agents also describes agents as systems that independently accomplish tasks on your behalf, and it doesn’t count simple chatbots, which don’t let the LLM control how the work proceeds, as agents. So if you want to know whether something is an agent, it helps to ask who decides the next step.
Think, act, look at the result, repeat
The basic shape of how an agent works was laid out clearly in the ReAct paper by Shunyu Yao and colleagues, posted to arXiv in October 2022 and published at ICLR 2023. As its name, a blend of reasoning and acting, suggests, ReAct has the model alternate between thoughts, actions, and observations. A thought is the model reasoning in words about what to do next, so it doesn’t change anything outside. An action is a call to a tool, such as a Wikipedia search, and an observation is what that tool sends back.
The model doesn’t run the tool itself, though. According to the Claude tool use docs, the model only decides which tool to call and returns a structured call, and it’s the application that runs the call and sends back the result. In How Claude Code works, the layer around the model that provides the tools and manages the context is called the harness, and the loop is described as gathering context, taking action, and verifying results. The loop ends when the model decides the task is done, and a stopping condition such as a maximum number of rounds is often added as well.
Watching an agent add up a CSV file
To see this loop for myself, I gave Claude Code a small job. In a folder that held only orders.csv, I asked it to find the total of the amount column and write it to total.txt. The file holds 24 orders, including one refund of -18.40, and here’s the command I ran.
claude -p "There is a CSV file of orders in this folder. Find the total of the amount column and write it to total.txt." \
--model haiku --allowedTools "Read,Write,Bash(awk *)" \
--output-format stream-json --verbose < /dev/null > run.jsonl
claude -p is a headless run that does the job once without opening a chat and then exits. With --allowedTools, I let it read and write files and use awk, a tool for working with text column by column, without asking me. Calls that need approval but aren’t on that list get refused. --output-format stream-json --verbose records every step of the run in run.jsonl. As you can see, the prompt says nothing about how to do the job.
The log is long, so I wrote a short script that pulls out the model’s thoughts, its tool calls, and the first line of each result, cut at 60 characters. It shows the folder path as a dot.
import json
import sys
# Replay a stream-json log: what the agent thought, called, and got back.
cwd = ""
def short(text):
lines = str(text).replace(cwd, ".").splitlines() or [""]
return lines[0][:60]
for line in open(sys.argv[1]):
event = json.loads(line)
if event["type"] == "system" and event.get("subtype") == "init":
cwd = event["cwd"]
print("model:", event["model"])
elif event["type"] in ("assistant", "user"):
content = event["message"]["content"]
for block in content if isinstance(content, list) else []:
if block["type"] == "thinking":
print("think:", short(block["thinking"]) or "(not shown)")
elif block["type"] == "text":
print("say: ", short(block["text"]))
elif block["type"] == "tool_use":
args = block["input"].get("command") or json.dumps(block["input"])
print("call:", block["name"], short(args))
elif block["type"] == "tool_result":
print("got: ", short(block["content"]))
elif event["type"] == "result":
print(f"turns: {event['num_turns']}, cost: ${event['total_cost_usd']:.4f}")
Here’s what python3 steps.py run.jsonl printed.
model: claude-haiku-5-5
call: Bash cd . 2>/dev/null; pwd; ls -la; for f in *.csv; do echo "== $
got: A variable in this command can't be checked before it runs
call: Bash ls -la .
got: total 32
call: Read {"file_path": "./orders.csv"}
got: 1 order_id,date,item,amount
think: (not shown)
say: The file has 24 data rows, including one negative refund row
call: Bash awk -F, 'NR>1{s+=$4; n++} END{printf "%.2f\n", s; print n >
got: Output redirection to './total.txt' needs approval. The path
think: (not shown)
say: The shell redirect needs approval, so I'll compute the sum f
call: Bash awk -F, 'NR>1{s+=$4; n++} END{printf "%.2f (rows: %d)\n", s,
got: 692.66 (rows: 24)
call: Write {"file_path": "./total.txt", "content": "692.66\n"}
got: File created successfully at: ./total.txt (file state is cur
say: The total of the `amount` column is **692.66**, and I wrote
turns: 7, cost: $0.0045
Read it from the top and you can see the loop. The first command was refused by Claude Code’s permission check because it contained a variable that couldn’t be checked before it ran, so the agent used a simpler ls to find the file and then read it. Next it tried to have the shell write the awk result straight into total.txt, and when that was refused too, it said so, ran awk without the redirect to get 692.66, and wrote the file with the Write tool. None of these steps were in my prompt, and each one was chosen after looking at what the previous step returned. The think: (not shown) lines mark where the model reasoned but the log didn’t include the text.
When I ran the exact same command again, nothing was refused, and it finished in 5 turns instead of the first run’s 7. Before both of these, I had tried allowing only Read and Write. With awk blocked, the agent added up the 24 numbers on its own, and while the total was right, its closing message described 24 rows as 23. In all three runs, total.txt held 692.66, the same total I got separately in Python.
The four parts of an agent
OpenAI’s guide names the model, tools, and instructions as an agent’s components, and Anthropic’s post treats an LLM augmented with retrieval, tools, and memory as the basic building block. Putting the two together and mapping them onto the run above gives this.
| Part | What it does | In the run above |
|---|---|---|
| Model | Reads the situation and picks the next step | claude-haiku-5-5 |
| Tools | Act on the world and report back | Bash, Read, Write |
| Memory | Keeps what has happened so far | Every call and result in the conversation |
| Instructions | Set the goal and the rules | My prompt and Claude Code’s system prompt |
Short-term memory is the conversation so far, tool results included, and it has to fit in the context window, the amount of text a model can take in at once. A new session starts with an empty context, so in Claude Code, anything meant to last goes into files such as CLAUDE.md. Tools can also come from outside. MCP (Model Context Protocol) is an open-source standard for connecting AI applications to external systems, and it lets a tool built once be used by many different agents.
Workflows and agents
In Anthropic’s post, a workflow is a system in which LLMs and tools are orchestrated through predefined code paths, and an agent is a system in which the LLM directs its own process and tool use. Take customer emails as an example. If your code has the model classify each email and then picks a reply template based on the label, that’s a workflow. But if you hand over the email, simply ask the model to resolve it, and let it decide whether to look up the order, check the refund policy, or ask the customer a question, that’s an agent. According to Anthropic, workflows offer predictability and consistency for well-defined tasks, while agents are the better option when flexibility and model-driven decisions are needed at scale. My two runs, which took different paths with the same command, show that difference too.
Where you’ll meet agents
Coding agents are perhaps the best-known example. Anthropic said Claude Code could read and edit code, run tests, and commit and push to GitHub. There are also agents that use a computer directly. With the computer use tool, Claude takes screenshots and controls the mouse and keyboard, and there’s a separate browser use tool for working with webpages. Research agents find, read, and summarize sources, and in June 2025, Anthropic’s post on its multi-agent research system described a Research feature in which several agents split up the searching.
What can go wrong
Cost comes first. At every step, an agent sends the ever-growing conversation to the model again, so it uses a lot of tokens. According to that research post, agents typically use about four times more tokens than chat interactions, and multi-agent systems about fifteen times more. Errors also pile up, because a small mistake in an early step becomes the starting point for every later one. Anthropic, too, names higher costs and compounding errors as the price of autonomy, and recommends extensive testing in sandboxed environments, walled off from anything that matters, along with appropriate guardrails. The wrong row count in my earlier run shows why it’s worth checking what an agent says against what it actually did.
Permissions matter too. An agent can do whatever its tools allow, so it’s safest to grant only what the job needs, as with --allowedTools. And the broader those permissions, the more dangerous prompt injection becomes. This is an attack that hides instructions in content the agent reads, such as a webpage or an email, so that the model follows them as if they came from you. The computer use docs warn that Claude sometimes follows commands found in content even when they conflict with your instructions. Simon Willison calls the combination of access to private data, exposure to untrusted content, and the ability to communicate externally in one agent the lethal trifecta. With all three together, an attacker can trick the agent into handing over your private data, and as the post puts it, we still don’t know how to prevent this with complete reliability.
When an agent fits and when a fixed flow is better
Anthropic advises finding the simplest solution first and adding complexity only when it’s needed, which might mean not building an agentic system at all. Agents fit open-ended problems where it’s hard to predict how many steps the work will take, so you can’t hardcode a fixed path. OpenAI’s guide likewise points to work that involves nuanced judgment, rules that have grown hard to maintain, or heavy reliance on unstructured data, and says that otherwise a deterministic solution may suffice.
By that standard, my own example didn’t really need an agent, since a one-line script adds up a column the same way every time, faster and more cheaply. If you know the order of the steps and the same input should always give the same output, a fixed flow is usually the better choice. On the other hand, when you can’t know in advance what you’ll run into, as when you’re tracking down a bug, an agent starts to earn its cost. That’s even more true when you can check the result automatically, for example with tests.
If you’re trying it for the first time
If you have Claude Code, I’d suggest putting a small CSV file in an empty folder and running the command above. Then take one tool out of --allowedTools and run it again, and you’ll see for yourself how an agent changes course when a step is blocked. I ran these examples on October 27, 2026, on macOS with Claude Code 2.1.304, and --model haiku resolved to claude-haiku-5-5.
AI tools helped with the research for this post.