Early-bird price on the GenAI & Agentic AI Engineer Bootcamp batch. Grab a seat →

An AI agent is a language model that calls tools in a loop until a task is done. The model chooses the next step, your code runs the tool, and the result goes back to the model so it can choose again. Use an agent when you cannot predict the steps in advance. When you can, a fixed workflow is cheaper, faster and easier to test.

Key takeaways

  • An agent is three things: a model, a set of tools, and a loop that continues until the model stops asking for tools.
  • Most of the engineering sits outside the model: tool design, stop conditions, permissions and evaluation.
  • Start with one model call, then a fixed workflow. Move to an agent only when the path through the task really varies.
  • The Model Context Protocol (MCP) is a standard way to plug tools into an agent. Multi-agent designs split work across separate contexts, at a high token cost.
  • Treat everything an agent reads as untrusted input, and limit what its tools are able to do.

What is an AI agent?

A large language model (LLM) on its own only produces text. It cannot look up an order, run a test or send an email. A tool is a function you describe to the model: a name, a description and a schema for its inputs. When the model decides a tool would help, it replies with a structured request to call it. Your code runs the function and sends the result back.

An agent is what you get when you put that exchange in a loop and let the model decide when it is finished.

Anthropic's engineering guide "Building effective agents" (December 2024) draws a line that is worth adopting. It calls any system built this way an agentic system, and then separates two kinds:

  • Workflows: systems where LLMs and tools are orchestrated through predefined code paths. You wrote the steps.
  • Agents: systems where the LLM dynamically directs its own process and tool usage. The model chooses the steps.

The difference is who holds control flow. That one fact drives cost, testability and risk, which is why it comes up in every section below.

A few things an agent is not. It is not a chatbot with a long system prompt, because a chatbot does not act. It is not retrieval-augmented generation (RAG), although an agent may use a search tool; see the guide to retrieval-augmented generation for that pattern. And it is not autonomous in any deep sense. It is a loop with a model inside, and it does exactly what its tools allow.

A cycle showing the agent loop: the model reads the conversation, requests a tool, your code runs it, and the result returns to the model until it answers.

How does the agent loop work?

The loop has four steps:

  1. Send the model the conversation so far and the list of tools.
  2. If the model answers in plain text, you are done.
  3. If it asks for one or more tools, run them.
  4. Append the model's request and your results to the conversation, then go back to step 1.

Here is a complete loop using the Anthropic Python SDK's Messages API. It follows the steps in Anthropic's tool-use documentation: a response with stop_reason equal to tool_use contains tool_use blocks, and you answer each one with a tool_result block in a user message.

import json

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
MODEL = "claude-opus-5-5"       # use any current model ID from the models page
MAX_STEPS = 10                  # stop condition: never loop forever

TOOLS = [
    {
        "name": "get_order_status",
        "description": (
            "Look up the current status of a customer order by its order ID. "
            "Use this when the user asks where an order is. "
            "Returns the status and the expected delivery date. "
            "It does not return payment details."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "order_id": {
                    "type": "string",
                    "description": "The order ID, for example A-1042",
                }
            },
            "required": ["order_id"],
        },
    }
]


def run_tool(name, tool_input):
    if name == "get_order_status":
        # Replace with a real lookup.
        return {"order_id": tool_input["order_id"], "status": "shipped",
                "expected_delivery": "2026-12-02"}
    raise ValueError(f"Unknown tool: {name}")


messages = [{"role": "user", "content": "Where is my order A-1042?"}]

for step in range(MAX_STEPS):
    response = client.messages.create(
        model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages
    )
    if response.stop_reason != "tool_use":
        break  # the model answered, or stopped for another reason

    results = []
    for block in response.content:
        if block.type == "tool_use":
            try:
                output = run_tool(block.name, block.input)
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": json.dumps(output)})
            except Exception as exc:
                # Tell the model what failed so it can recover.
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": str(exc), "is_error": True})

    messages.append({"role": "assistant", "content": response.content})
    messages.append({"role": "user", "content": results})
else:
    raise RuntimeError("Step limit reached without a final answer")

print("".join(b.text for b in response.content if b.type == "text"))

Four details in this code matter in every agent, whatever SDK you use:

  • The model never runs anything. It only asks. Your run_tool function is the single place where actions happen, which makes it the place to enforce permissions.
  • Every tool request gets a result, even on failure. The Anthropic docs require one tool_result per tool_use block, and recommend setting is_error with a message that says what went wrong and what to try next.
  • The whole conversation is sent on each turn. The message list grows with every step, so later steps cost more than earlier ones.
  • There is a hard step limit. The for ... else raises if the model has not finished after ten turns.

Anthropic's SDK also ships a tool runner that manages this loop for you. Writing it by hand once is still the fastest way to understand what a framework is doing on your behalf.

What is an agent made of?

Strip away the vocabulary and an agent has five parts.

A stack of the five parts of an agent, from instructions at the top through the model, tools and loop, down to guardrails.

PartWhat it isWhat goes wrong when it is weak
InstructionsThe system prompt: goal, constraints, when to stopThe agent wanders or stops early
ModelThe LLM that reads context and picks the next actionWrong tool, wrong arguments
ToolsFunctions with names, descriptions and input schemasThe agent cannot act, or acts too broadly
LoopYour code: runs tools, manages context, enforces limitsRunaway cost, lost state
GuardrailsPermissions, approvals, budgets, loggingDamage when the model is wrong or manipulated

Notice that only one of the five is the model. Teams that struggle with agents usually have a tools or loop problem and try to solve it by changing the prompt.

How do you design tools an agent can use well?

Anthropic's guide makes the point that tool definitions deserve as much attention as the prompt, and calls this the agent-computer interface. Its tool-use documentation gives concrete rules:

  • Write long, specific descriptions. Say what the tool does, when to use it and when not to, what each parameter means, and what it does not return. The docs suggest at least three or four sentences per tool.
  • Prefer fewer, more capable tools. One tool with an action parameter is easier for a model to choose than three near-identical ones.
  • Namespace tool names when they span services, for example github_list_prs and slack_send_message.
  • Return only what the model needs next. Large, noisy results fill the context and hide the useful part.
  • Make mistakes hard to make. Anthropic gives the example of requiring absolute file paths after a model kept getting relative paths wrong.

A useful test: hand the tool description to a colleague with no other context. If they could not call it correctly, the model will not either.

When should you use an agent, and when a workflow?

Anthropic's advice is to find the simplest solution possible and add complexity only when it is needed. It also notes that for many applications, a single well-prepared LLM call with retrieval and examples is enough.

SituationReasonable choice
One question, one answer, context known up frontSingle model call
Steps are known and always the sameWorkflow (a chain of calls in code)
Inputs fall into a few known typesWorkflow with a routing step
Number and order of steps depends on what is found along the wayAgent
Mistakes are costly and cannot be undoneWorkflow, or an agent with human approval

The price of an agent is stated plainly in the same guide: higher cost, and the potential for compounding errors, because each step builds on the one before. The full decision rule, with code for a workflow, is in agent or workflow: how to choose the simplest design that works.

How do agents connect to tools and data?

In the loop above, tools are Python functions in the same file. That stops scaling when several applications need the same tools, or when another team owns them.

The Model Context Protocol (MCP) is an open protocol for this. A server exposes tools, resources (data to read) and prompts (reusable templates). A host application, such as a desktop assistant or an IDE, connects to servers through a client and offers their tools to the model. Messages use JSON-RPC 2.0, and the two standard transports are stdio for local servers and Streamable HTTP for remote ones.

The current specification is version 2026-07-28. It made the protocol stateless and removed the connection handshake used by earlier versions, so older tutorials may not match what current SDKs do. The details, a minimal server in Python and the authorisation model are in Model Context Protocol explained: servers, tools and transports.

MCP is plumbing. It standardises how a tool is described and called. It does not make a badly designed tool good, and it does not decide whether a tool call is safe.

Do you need more than one agent?

Usually not at first. A multi-agent system gives separate agents their own instructions, tools and context. The common shape is an orchestrator (or lead agent) that splits a task and hands pieces to subagents, each of which works in a fresh context and reports back a summary. A second shape is the handoff, where one agent passes the whole conversation to a specialist.

The benefit is real for broad, parallel work such as research across many sources. So is the bill. Anthropic reported in 2025 that in its own data, agents typically used about 4 times the tokens of a chat interaction, and multi-agent systems about 15 times. The same write-up says tasks where agents must share context or depend heavily on each other, including most coding tasks, were not a good fit at the time.

A single agent with good tools is easier to debug, cheaper to run and has no coordination problems. The patterns, the costs and a test for when to split are in multi-agent systems: when more agents help and when they hurt.

What can go wrong, and what guardrails help?

An agent fails in ways a chat application cannot, because it acts. Three failure types cover most incidents:

  • It does the wrong thing confidently. The model misreads a result, and every later step builds on the error.
  • It is told to do the wrong thing. Text inside a web page, email or document can contain instructions aimed at the model. This is indirect prompt injection. The OWASP Top 10 for LLM Applications lists prompt injection first (LLM01:2025) and says it is unclear whether any fool-proof prevention exists.
  • It does too much. OWASP calls this Excessive Agency (LLM06:2025) and names three causes: excessive functionality, excessive permissions and excessive autonomy.

Since you cannot guarantee the model's judgement, you limit the damage a wrong decision is able to cause:

  • Give each tool the narrowest permission that still does the job.
  • Require a human to approve actions that cannot be undone or that spend money.
  • Set hard limits on steps, time and spend.
  • Log every tool call with its inputs.

Each of these, with code for an approval gate and a budget, is covered in guardrails for AI agents: permissions, approvals and stop conditions.

How do you know an agent works?

A demo that works once proves little, because the same agent can take a different path on the next run. Evaluation for agents has three layers:

  1. Outcome. Did the task end in the right state? Build a set of realistic tasks with a checkable result, such as "the ticket is tagged billing and a draft reply exists".
  2. Path. How many steps, which tools, how many errors and retries? A correct answer reached in forty steps is a problem waiting to show up on the invoice.
  3. Safety. Include tasks where the right behaviour is to refuse, to ask, or to ignore an instruction planted in a document.

Run the set on every change to a prompt, tool description or model version. Anthropic's guide recommends testing extensively in sandboxed environments before giving an agent access to anything real. For the mechanics, see LLM evaluation in CI and LLM observability: what to trace, log and alert on.

What does an agent cost to run?

More than the per-token price suggests, for a structural reason. Each turn of the loop sends the entire conversation again, including every earlier tool result. A task that takes ten turns does not cost ten times one call. It costs the sum of ten steadily growing calls.

Three habits keep this under control:

  • Keep tool results small. Return the five fields the model needs, not the whole API response.
  • Cap the loop. A step limit turns a runaway bill into a visible error.
  • Measure per task, not per call. Record total tokens and steps for each completed task so you can see the distribution, not only the average.

Pricing differs by provider and model and changes often, so check the provider's pricing page before estimating. The article on how to reduce LLM costs covers caching, batching and routing.

What is a sensible order of work for a first agent?

  1. Write down the task and how you will check that it was done correctly.
  2. Try it with a single model call and good context. If that works, stop.
  3. If the steps are fixed, build a workflow.
  4. If they are not, write the loop by hand with one or two tools.
  5. Add a step limit and logging before adding more tools.
  6. Build a test set of at least a few dozen realistic tasks, including ones that should be refused.
  7. Classify every tool as read-only, reversible or irreversible, and put approval on the last group.
  8. Only then consider a framework, MCP servers or more agents, and only for a problem you have actually observed.

Common questions

Is an AI agent the same as a chatbot?

No. A chatbot returns text. An agent can call tools that read or change other systems, and it decides for itself how many steps to take. A chatbot becomes an agent the moment you give it tools and a loop.

Do I need a framework to build an agent?

No. The loop above is about forty lines. Anthropic's guide suggests starting with the LLM API directly, and warns that frameworks can add layers of abstraction that hide the underlying prompts and responses. If you do adopt one, make sure you understand the code underneath.

Can an agent run with no human involved?

It can, for tasks that are low-risk and reversible, with hard limits in place. The MCP specification itself says there should always be a human in the loop with the ability to deny tool invocations. For anything irreversible, keep an approval step.

How is an agent different from RAG?

RAG fetches relevant passages and puts them in the prompt, usually in one fixed step. An agent decides whether and when to search, and can search again based on what it found. Many agents use retrieval as one of their tools.

Free download: The AI agents field guide

What an agent is, when a simple workflow is the better choice, how MCP connects tools, when several agents help, and the guardrails every agent needs, with working Python. See what’s inside.