Most guides on how to build an AI agent stop at a diagram of boxes and arrows. You finish reading and still don't know what the code looks like, which parts are hard, or whether you needed an agent in the first place.
This guide is hands-on. You will learn what an agent actually is, how to tell whether your task needs one, how to build one with a no-code tool, and how to build one in Python with a short agent loop we ran and tested. It ends with the guardrails and tests that separate a demo from something you can trust.
How to build an AI agent in 5 steps
- Check that you need an agent. If the task follows the same fixed steps every time, a script or workflow is cheaper and more predictable.
- Define one narrow job. Write down the goal, the tools it may use, its hard limits, when to stop, and ten real cases to test it on.
- Choose a route and build it. Use a no-code builder such as n8n or Zapier Agents, or create your own agent from scratch with a short Python loop that gives a model tools and feeds the results back.
- Add guardrails. Grant the fewest permissions possible, require human approval for risky actions, and cap steps and spending.
- Test, measure and improve. Run your real cases, check the outcome, the tools used and when it stopped, and add a new test every time it slips.
The rest of this guide walks through each step, with a working Python agent you can copy.
What you need to build an AI agent
Agents are systems that independently accomplish tasks on your behalf.
OpenAI's practical guide (opens in a new tab) breaks every agent into three parts: a model that reasons and decides, tools that fetch data or take actions, and instructions that define the job and its rules. Anthropic's engineering team (opens in a new tab) describes agents more bluntly: they are typically just LLMs using tools based on environmental feedback in a loop.
That loop is the fourth ingredient, and the one most explanations skip. The model looks at the task and asks for a tool. Your code runs the tool and hands back the result. The model reads it and either asks for another tool or gives a final answer. Everything else, including memory, multiple agents and fancy frameworks, is built on that cycle.
| Part | What it does | Example |
|---|---|---|
| Model | Reads the task and decides the next step | Claude Opus 5.5, GPT models, an open-weight model |
| Tools | Functions the model can ask your code to run | Look up an order, search docs, create a ticket |
| Instructions | The job description, rules and when to stop | Refund only delivered orders; escalate anything over $100 |
| Loop | Runs requested tools and feeds results back | Repeat until the model answers or a step limit is hit |
If agents are new to you, our explainer on agentic AI vs generative AI covers the difference between a model that writes and a system that acts.
Step 1: Check that you need an agent at all
Agents are slower and more expensive than a single model call, because they make several calls per task. Anthropic advises finding the simplest solution possible and adding complexity only when it is needed, which can mean not building an agent at all.
OpenAI's guide says agents earn their place in workflows that have resisted traditional automation, especially ones that involve:
- Complex judgment, such as deciding whether a refund request is reasonable.
- Rules that are hard to maintain, where a decision tree has grown into hundreds of brittle branches.
- Heavy unstructured data, such as reading emails, PDFs or support conversations.
If your task follows the same fixed steps every time, a script or a fixed chain of model calls is cheaper and more predictable. Anthropic calls these predefined paths workflows, and contrasts them with agents, which direct their own process and tool use. Our guide to AI agentic workflows covers the common patterns and when each one fits.
Step 2: Define one narrow job
The most common reason a custom AI agent fails is a vague brief. "Handle customer support" is not a job an agent can do well. "Answer order-status questions and process refunds under $100 for delivered orders" is. Before you touch a tool, write a one-page job card:
- The goal. One sentence on what done looks like.
- Inputs. What the agent receives: a chat message, an email, a form, a ticket.
- Allowed actions. Every tool it may use, split into read-only and write actions.
- Hard limits. What it must never do, and the dollar or risk thresholds that need a human.
- Stop conditions. When it should finish, and when it should give up and hand off.
- Ten real examples. Past cases with the correct outcome. These become your first tests.
OpenAI recommends writing instructions from documents you already have, such as support scripts or policy pages, and breaking them into explicit steps with defined actions and edge cases. Our guide to Claude prompt engineering covers how to write those instructions so a model follows them.
Step 3: Choose your route, no-code or code
There are three ways to build an AI agent. Most people should pick the first route that can do the job, because each step down the table adds control and adds work.
| Route | Best for | Trade-offs |
|---|---|---|
| No-code builder | Automating internal workflows across many apps, visually | Less control and portability; you still design the trigger, tools and approval steps |
| Model API plus your own loop | Products, custom logic and full control | You write and maintain the code, the guardrails and the tests |
| Agent framework | Multi-agent systems or durable, long-running state | Extra abstraction; harder to debug if you don't know what it does underneath |
Build AI agents without coding
You can build AI agents without coding, but names, plans and free allowances in this category change often. As of November 2026, these are the main no-code builders, with each free option and entry price read from the vendor's own page. For general assistants and developer frameworks as well, see our roundup of the best AI agents.
| Builder | Free option | Entry paid plan | Best for |
|---|---|---|---|
| n8n (opens in a new tab) (AI Agent node) | Self-hosted Community edition (opens in a new tab), free indefinitely; cloud trial with no credit card | Cloud Starter: 20 euros/month billed annually, 2,500 executions | Technical teams that want to self-host |
| Zapier Agents (opens in a new tab) | Agents Free: 400 activities a month | Agents Pro: $400/year ($33.33/month), 1,500 activities | Teams already automating with Zapier |
| Make AI Agents (opens in a new tab) | Free plan: 1,000 credits a month | Core: from $9/month for 10,000 credits | Visual workflows with agents on the same canvas |
| Lindy (opens in a new tab) | $50 of credits that last 7 days | Team: $49.99/month per active user, 5,000 credits | Email, meeting and admin assistants |
| Microsoft Copilot Studio (opens in a new tab) | Internal agents included with a Microsoft 365 Copilot license; free trial | $200/month per 25,000-credit pack, or pay as you go | Companies on Microsoft 365 |
| ChatGPT workspace agents (opens in a new tab) | None; free only during the preview, until May 6, 2026 | Credit-based, on ChatGPT Business, Enterprise, Edu or Teachers | Teams that already work in ChatGPT |
Make says its agents are available on all plans, and its own comparison page (opens in a new tab) lists the Core price. The build itself looks similar in every tool. In n8n, the agent is a single node. Its documentation (opens in a new tab) describes it simply: connect a chat model and one or more tools, and the agent decides which tools to call to complete a task. You must connect at least one tool for the node to work. A typical build looks like this: Our n8n explainer covers the platform itself, including its pricing and the free self-hosted edition.
- Add a trigger: a chat message, a new email, a form submission or a schedule.
- Add the AI Agent node and connect a chat model sub-node with your provider's API key.
- Connect tool sub-nodes for the apps the agent needs, such as a spreadsheet lookup or a ticketing system.
- Paste your job card into the agent's system message, including the hard limits and when to stop.
- Route anything risky, such as refunds or outgoing emails, through an approval step before it runs.
- Run your ten real examples through it and fix the instructions or tools wherever it gets one wrong.
ChatGPT workspace agents, launched in April 2026, take a conversational approach instead: you describe a recurring workflow or upload a file, and ChatGPT guides you through defining the steps, connecting tools and testing. OpenAI says they can run on a schedule, work in Slack and require approval before sensitive actions.
How to create an AI agent from scratch
Creating your own AI agent from scratch in Python gives you full control and teaches you how every other tool works under the hood. The example below is a small support agent for a hypothetical online store. It can look up orders and issue refunds, and every refund needs a human's approval. It uses the official Anthropic Python SDK and follows the loop in Anthropic's tool-using agent tutorial (opens in a new tab), with three additions the tutorial leaves out: a step limit, error handling and an approval gate.
1. Install the SDK and set your key
pip install anthropic
export ANTHROPIC_API_KEY="your-key-here"2. Write the agent
import json
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
MODEL = "claude-opus-5-5"
MAX_STEPS = 10 # hard stop so a confused agent cannot loop forever
# Stand-in data. Replace with calls to your real systems.
ORDERS = {
"A1001": {"status": "delivered", "total": 42.50, "item": "USB-C hub"},
"A1002": {"status": "in transit", "total": 19.99, "item": "Phone case"},
}
TOOLS = [
{
"name": "get_order",
"description": (
"Look up one order by its ID and return its status, item and total. "
"Use this whenever the customer mentions an order. "
"Order IDs look like A1001. Read-only: it never changes anything."
),
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string", "description": "Order ID, e.g. A1001"}},
"required": ["order_id"],
},
},
{
"name": "issue_refund",
"description": (
"Refund an order in full. Only use this after get_order shows the order "
"was delivered and the customer has asked for a refund. "
"A human must approve every refund before it runs."
),
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string"},
"reason": {"type": "string", "description": "One-sentence reason"},
},
"required": ["order_id", "reason"],
},
},
]
def get_order(order_id):
order = ORDERS.get(order_id)
if order is None:
raise ValueError(f"No order {order_id}. Ask the customer to check the ID.")
return order
def issue_refund(order_id, reason):
order = get_order(order_id) # check the order exists before bothering a human
if order["status"] != "delivered": # enforce the rule in code, not just in the prompt
raise ValueError(f"Order {order_id} is {order['status']}, not delivered. It cannot be refunded yet.")
try:
answer = input(f"Approve refund for {order_id} ({reason})? [y/N] ")
except EOFError: # no one at the keyboard, e.g. running on a server
answer = ""
if answer.strip().lower() != "y":
raise PermissionError("No human approved this refund. Tell the customer it needs review.")
return {"order_id": order_id, "refunded": order["total"]}
HANDLERS = {"get_order": get_order, "issue_refund": issue_refund}
def run_tool(block):
"""Run one tool call and package the result, or the error, for the model."""
if block.name not in HANDLERS:
return {"type": "tool_result", "tool_use_id": block.id, "is_error": True,
"content": f"Unknown tool {block.name}. Available tools: {', '.join(HANDLERS)}."}
try:
output = HANDLERS[block.name](**block.input)
return {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(output)}
except Exception as err: # the model sees the error and can recover
return {"type": "tool_result", "tool_use_id": block.id, "content": str(err), "is_error": True}
def run_agent(task):
messages = [{"role": "user", "content": task}]
for step in range(MAX_STEPS):
response = client.messages.create(
model=MODEL,
max_tokens=1024,
system="You are a support agent for a small online store. Be brief and accurate.",
tools=TOOLS,
messages=messages,
)
if response.stop_reason == "max_tokens":
return "Stopped: the reply was cut off. Raise max_tokens or hand this to a human."
if response.stop_reason != "tool_use":
return "".join(b.text for b in response.content if b.type == "text")
messages.append({"role": "assistant", "content": response.content})
results = [run_tool(b) for b in response.content if b.type == "tool_use"]
messages.append({"role": "user", "content": results})
return "Stopped: step limit reached. Hand this one to a human."
if __name__ == "__main__":
print(run_agent("Order A1001 arrived broken. Can I get my money back?"))3. What each part does
- `TOOLS` describes each tool to the model: a name, a description and a JSON Schema for its inputs. The descriptions say when to use each tool and when not to, because that is how the model chooses.
- `run_tool` runs whatever the model asked for and wraps the output in a
tool_resultblock with the matchingtool_use_id. If the tool raises an error, or the model names a tool that does not exist, it returns a clear message withis_errorset, so the model can recover instead of your program crashing. - `run_agent` is the loop. While the model's
stop_reasonistool_use, it runs every requested tool, appends the results to the conversation and calls the model again. If the reply was cut off bymax_tokens, it stops and says so rather than returning an empty answer. Any other stop reason means the model has its answer. - `MAX_STEPS` caps the loop at ten model calls. Without it, a confused agent can call tools forever and run up your bill.
- `issue_refund` checks in code that the order exists and was delivered, then asks a person to type
ybefore it runs. If nobody is there to answer, it treats that as a no. In a real system the prompt becomes an approval button in Slack or your admin panel.
4. How we tested it
We ran this file with version 2.14.0 of the anthropic SDK, pointed at a local stand-in for the API that returned scripted model replies. That checks the loop and the guardrails, not the model's judgment. We first tested the three happy cases: two orders requested at once with one bad ID (both results came back, the bad one flagged with is_error), a refund approved, and a refund declined. A model that kept calling tools was stopped after ten calls with a hand-off message.
Then we threw awkward cases at it, and the first version of this code failed five of them. Each fix is now in the file above:
- The model asked for a tool that does not exist. The error it got back was just
'cancel_order', which gives it nothing to work with. Fix: a clear message that lists the available tools. - A refund for an order that does not exist. The person was asked to approve it before the code noticed the order was missing. Fix: look the order up first, so nobody approves something invalid.
- A refund for an order still in transit. It went through. The "only after delivery" rule lived only in the tool description, which the model can ignore. Fix: check the status in code. Rules that protect money belong in code, not in the prompt.
- Nobody at the keyboard. Run without a terminal, as it would be on a server, the approval prompt failed with "EOF when reading a line", a message the model could not explain to a customer. Fix: treat no answer as a no.
- A reply cut off by the token limit. The agent returned an empty string with no warning. Fix: check for
max_tokensand hand off instead.
One version note: the 2.x SDK switched its HTTP library to httpx2. Normal use is unchanged, but if you pass your own http_client or mock requests in tests, update those imports. With a real API key, the model's wording and choices will vary from run to run, which is why Step 5 matters.
To connect this agent to real systems, replace ORDERS with calls to your database or APIs. If a system already has an MCP server, your agent can use its tools without you writing the integration; our guide to the Model Context Protocol explains how.
Step 4: Add guardrails before anyone else uses it
OpenAI's guide treats guardrails as layers of defense, not a single filter. For a first agent, these five cover most of the risk:
- Least privilege. Give the agent only the tools the job card lists, and make as many of them read-only as you can.
- Human approval for high-risk actions. OpenAI recommends escalating to a person for irreversible changes, large refunds and payments, especially early in a deployment.
- Step and spending limits. Cap the number of loop iterations, and alert yourself when a single task uses far more tokens than usual.
- Treat tool output as untrusted. An email or web page the agent reads can contain instructions aimed at the model, a technique called prompt injection. Never let content from a tool expand what the agent is allowed to do.
- A way out. When the agent fails repeatedly or hits a limit, it should hand off to a human with a summary, not guess.
Step 5: Test, measure and improve
An agent that works on the example you built it for has not been tested. Turn the ten real cases from your job card into a test set, then grow it every time the agent gets something wrong. For each case, check three things: did it reach the right outcome, did it use the right tools, and did it stop when it should have?
OpenAI suggests prototyping with the most capable model to set a performance baseline, then trying smaller models to see whether they still pass your tests at lower cost and latency. The gap can be large. At the time of writing, Anthropic's models overview (opens in a new tab) lists Claude Opus 5.5 at $4 per million input tokens and $20 per million output tokens, and Claude Haiku 5.5 starting at $0.10 and $0.50. Our guide to small language models covers when a smaller model is good enough.
When to use an AI agent framework
Anthropic's advice is to start with the model API directly, because most agent patterns take only a few lines of code, and to make sure you understand the underlying code if you adopt a framework. The roughly 90-line example above is the whole agent; there is nothing hidden.
Frameworks start to pay off when you need features you would otherwise build yourself, such as handing a conversation between specialized agents, saving state across long-running tasks, or tracing every step. OpenAI's guide recommends getting the most out of a single agent before splitting work across several, and suggests multiple agents only when the logic becomes highly conditional or tools start to overlap. The Anthropic SDK also includes a tool runner that manages the loop for you once you are comfortable with how it works.
Common mistakes when building AI agents
- Starting with a big job. Agents that do one thing well beat agents that do ten things badly. Add scope only after the first job passes its tests.
- Vague tool descriptions. A tool called
searchwith a one-line description will be misused. Name tools specifically and describe when not to use them. - No step limit. A loop without a cap is a bill without a cap.
- Write access on day one. Ship read-only first, then add write tools behind approval.
- Crashing on tool errors. Return the error to the model with a clear message about what to try next, so it can recover or explain.
- Testing only the happy path. Include invalid inputs, missing data and requests the agent should refuse.
The bottom line
Building an AI agent is less about clever code and more about a narrow job, well-described tools and firm limits. Pick one task that needs judgment, write its job card, and choose the route that fits: a no-code builder for internal workflows, or a short loop like the one above when you need control. Add approvals and a step limit before anyone relies on it, and grow your test set every time it slips. For more on models, tools and agents, browse our AI guides.



