#What an agent is
AddedStrip away the marketing and an agent is a short program: a model, a set of tools, and a loop. The model reads the goal and what has happened so far, picks a tool, your code runs it, the result goes back into the conversation, and the model picks again, until it decides the goal is met or a limit stops it. Anthropic's definition, from "Building effective agents" (December 2024), is the one most interviewers have read: an agent is a system where the model "dynamically direct[s] its own processes and tool usage", and in implementation agents are typically "just LLMs using tools based on environmental feedback in a loop".
What makes that a different kind of software is who decides the control flow. In everything else you've written, the ifs and the fors are yours. In an agent, the model chooses the next step at run time, from what it just observed. That one change is the source of both the power (it can handle tasks you couldn't write the steps for in advance) and every problem in this chapter (it can also choose badly, forever, at your expense).
Anthropic's article draws the line that organises this whole chapter:
- A workflow is a system where "LLMs and tools are orchestrated through predefined code paths". Your code decides the steps; the model fills each one in.
- An agent is a system where the model decides the steps.
The mental model: a workflow is a recipe and an agent is a cook. A recipe gives the same sequence every time; it's predictable, testable and cheap, and it can't cope with a missing ingredient. A cook looks in the fridge and adapts; you get flexibility and you give up predictability. A restaurant runs on recipes wherever it can and saves the cook's judgement for where it's needed. So should your product.
The example runs the same support task both ways, on two inputs. The workflow always does the same two steps. The agent, given the same tools, takes one path for the simple request and a different, longer path for the unusual one.
import Anthropic from "@anthropic-ai/sdk";
// Scripted replies (see "How these examples run")
const reply = (content, stop_reason = "end_turn") => ({ id: "msg_01Aa1bCc2dDe3fFg4hHj5kKm6n", type: "message", role: "assistant", model: "claude-opus-5-5", content, stop_reason, stop_sequence: null, usage: { input_tokens: 400, output_tokens: 40 } });
const text = (t) => reply([{ type: "text", text: t }]);
const use = (name, input) => reply([{ type: "tool_use", id: `toolu_01${name}`, name, input, caller: { type: "direct" } }], "tool_use");
const lastResults = (body) => { const c = body.messages.at(-1).content; return Array.isArray(c) ? c.filter((b) => b.type === "tool_result").map((b) => b.content).join() : ""; };
const fetch = async (url, init) => {
const body = JSON.parse(init.body);
const all = JSON.stringify(body.messages);
if (!body.tools) return Response.json(text(body.system.includes("Classify") ? (all.includes("twice") ? "billing" : "shipping") : "Thanks for getting in touch. We've looked into it and will follow up shortly."));
const done = (body.messages.length - 1) / 2; // tool rounds so far
if (!all.includes("twice")) return Response.json(done === 0 ? use("get_order", { order_id: "A-10422" }) : text("Your order A-10422 shipped on 1 December and should arrive on 8 December."));
const steps = [use("get_order", { order_id: "A-10422" }), use("list_payments", { order_id: "A-10422" }), use("refund_payment", { payment_id: "pay_2" })];
return Response.json(steps[done] ?? text("You were charged twice for A-10422. I've refunded the duplicate payment (pay_2, €490)."));
};
// End of scripted replies
const client = new Anthropic({ apiKey: "sk-ant-test", fetch });
const ask = async (system, user) => (await client.messages.create({ model: "claude-opus-5-5", max_tokens: 16000, system, messages: [{ role: "user", content: user }] })).content.find((b) => b.type === "text").text;
// A WORKFLOW: the code decides the steps. Always classify, then draft.
async function workflow(ticket) {
const path = ["classify"];
const category = await ask("Classify the ticket as billing, shipping or other. Reply with one word.", ticket);
path.push(`draft(${category})`);
const answer = await ask(`You answer ${category} tickets for an online shop.`, ticket);
return { path, answer };
}
// AN AGENT: the model decides the steps. The code only runs what it asks for, in a loop.
const tool = (name, description) => ({ name, description, input_schema: { type: "object", properties: {}, additionalProperties: true } });
const tools = [tool("get_order", "Look up an order"), tool("list_payments", "List the payments made for an order"), tool("refund_payment", "Refund one payment")];
const handlers = {
get_order: () => ({ status: "shipped", shipped: "2026-12-01", expected: "2026-12-08" }),
list_payments: () => [{ id: "pay_1", amount: 490 }, { id: "pay_2", amount: 490 }],
refund_payment: ({ payment_id }) => ({ refunded: payment_id }),
};
async function agent(ticket, maxSteps = 8) {
const path = [];
const messages = [{ role: "user", content: ticket }];
for (let step = 0; step < maxSteps; step++) {
const response = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 16000, tools, messages });
if (response.stop_reason !== "tool_use") return { path, answer: response.content.find((b) => b.type === "text").text };
messages.push({ role: "assistant", content: response.content });
const calls = response.content.filter((b) => b.type === "tool_use");
path.push(...calls.map((c) => c.name));
messages.push({ role: "user", content: calls.map((c) => ({ type: "tool_result", tool_use_id: c.id, content: JSON.stringify(handlers[c.name](c.input)) })) });
}
return { path, answer: "(step limit reached)" };
}
for (const ticket of ["Where is my order A-10422?", "I was charged twice for order A-10422!"]) {
console.log(`ticket: ${ticket}`);
const w = await workflow(ticket);
console.log(` workflow path: ${w.path.join(" -> ")}\n workflow says: ${w.answer}`);
const a = await agent(ticket);
console.log(` agent path: ${a.path.join(" -> ")}\n agent says: ${a.answer}`);
}ticket: Where is my order A-10422?
workflow path: classify -> draft(shipping)
workflow says: Thanks for getting in touch. We've looked into it and will follow up shortly.
agent path: get_order
agent says: Your order A-10422 shipped on 1 December and should arrive on 8 December.
ticket: I was charged twice for order A-10422!
workflow path: classify -> draft(billing)
workflow says: Thanks for getting in touch. We've looked into it and will follow up shortly.
agent path: get_order -> list_payments -> refund_payment
agent says: You were charged twice for A-10422. I've refunded the duplicate payment (pay_2, €490).workflowis ordinary code with two model calls in a fixed order. Whatever the ticket says, it classifies and then drafts. Thepatharray records what ran:classify -> draft(shipping)for the first ticket andclassify -> draft(billing)for the second. Same shape both times; only the category differs.agentis the tool loop: call the model, and while the reply'sstop_reasonistool_use, run the requested tools and go round again. Nothing in this function says which tool comes first, or how many there will be. Itspathrecords the tools the model asked for.- For "Where is my order?", the (scripted) model asks for
get_order, reads the result and answers with the dates. One tool, two model calls. - For "I was charged twice", the same loop with the same tools takes a different route:
get_order -> list_payments -> refund_payment. It looked at the order, then decided it needed the payments, saw two of €490, and refunded the duplicate. No line of code anticipated "double charge"; the path came from the model reading each result. - The workflow's answer to the double charge is the generic acknowledgement, because the code path has no lookup and no refund step in it. To handle this case, a developer would have to add a branch. That's the trade in one run: the workflow does exactly what was written, every time; the agent can handle a case nobody wrote down.
- Now look at what the agent did unsupervised: it issued a refund. The same freedom that found the right path could have refunded the wrong payment.
maxStepsis the only limit in this toy loop. The rest of the chapter is about the controls a real one needs.
The most useful sentence in Anthropic's article is about restraint: find "the simplest solution possible", and only increase complexity when needed, because agentic systems "trade latency and cost for better task performance". For many applications, the article says, optimising a single model call with retrieval and good examples is enough. Before building an agent, check four things:
| Question | If the answer is no |
|---|---|
| Is the task hard to specify step by step? Could you write the steps as a flowchart? | If you can draw the flowchart, build the workflow. It's cheaper, faster and testable |
| Is the outcome worth the cost? An agent run can be dozens of model calls | A task worth a fraction of a cent can't pay for an agent |
| Can the model actually do the steps? Have you seen it succeed at each kind of step? | An agent built on a step the model does poorly fails in a loop |
| Can mistakes be caught and undone? Tests, review, a confirmation, a rollback | Without a safety net, restrict the agent to reading, or keep a person in the loop |
The spectrum between "one call" and "full agent" is where most production systems live:
| Level | Who decides the steps | Example |
|---|---|---|
| One model call | Nobody: there's one step | Classify this ticket |
| Call with retrieval or tools you invoke | Your code | Fetch the order, then ask the model to answer |
| Workflow | Your code, with the model filling in each step | Classify, route, draft, check |
| Agent | The model, inside limits your code enforces | "Resolve this ticket" with ten tools |
| Multi-agent | Models directing other models | A lead agent delegating research to subagents |
Each row down costs more tokens, more latency and more ways to fail. The engineering skill is to pick the highest row that solves the problem.
Classify each: (a) every incoming invoice is extracted to JSON, validated, and posted to the ledger; (b) "find out why last night's deploy doubled checkout latency", with access to logs, metrics and the repository; (c) a button that rewrites the selected paragraph in a friendlier tone; (d) a nightly job that summarises each of 5,000 support tickets.
Show answer
(a) workflow, (b) agent, (c) a single model call, (d) a single call per ticket, run as a batch.
- Invoices: the steps are known in advance and never change: extract, validate, post. You can draw the flowchart, so it's a workflow, with a validation gate in code between the steps.
- The latency investigation: nobody can list the steps beforehand. What to look at next depends on what the last query showed. The model has to direct its own path through the tools, which is the definition of an agent. It also meets the other tests: the outcome is valuable, and its actions are read-only.
- The rewrite button: one input, one output, no tools, no decisions about what to do next. It's one call. Calling it an "agent" adds nothing but latency.
- Ticket summaries: 5,000 independent single calls. There's no control flow to hand over. The interesting engineering is cost: nobody is waiting, so the Batch API does it at half price.
- The test in every case: who decides the next step? If the answer is "my code" or "there is no next step", it isn't an agent.