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.
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.
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
You can create an AI agent without writing code, but the options change quickly. The table below reflects what each vendor's own pages say as of October 2026.
| Route | Best for | Trade-offs |
|---|---|---|
| n8n AI Agent node | Automating internal workflows across many apps, visually | You still design the trigger, tools and approval steps yourself |
| ChatGPT workspace agents | Teams on ChatGPT Business, Enterprise, Edu or Teachers plans | Lives inside ChatGPT; launched as a preview with credit-based pricing |
| OpenAI Agent Builder | Not recommended for new projects | OpenAI is winding it down; unavailable from November 30, 2026 |
| 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 |
How to create an AI agent with no code
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:
- 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 (opens in a new tab), launched in April 2026, take a conversational approach: 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 build an AI agent in Python, step by step
Building your own AI agent in code 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):
answer = input(f"Approve refund for {order_id} ({reason})? [y/N] ")
if answer.strip().lower() != "y":
raise PermissionError("A human declined this refund. Tell the customer it needs review.")
return {"order_id": order_id, "refunded": ORDERS[order_id]["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."""
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 != "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, it returns the 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. 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` asks a person to type
ybefore it runs. In a real system that becomes an approval button in Slack or your admin panel.
4. How we tested it
We ran this exact file with version 1.17.0 of the anthropic SDK, pointed at a local stand-in for the API that returned scripted model replies. That let us check the loop itself, not the model's judgment, under three cases. When the model asked for two orders at once, one of them invalid, the agent returned both results in one message and flagged the bad ID with is_error. Approving the refund returned a refund result; declining it sent the model an error it could explain to the customer. A model that kept calling tools was stopped after ten steps with a hand-off message. 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. As of October 2026, 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.