Skip to content
AI12 min read

How to build an AI agent: a no-code route and a tested Python agent loop

An AI agent is a model, a few tools, clear instructions and a loop. This guide shows you how to decide whether you need one, build it with or without code, and add the guardrails that keep it safe.

ME

By

Founder and Editor

Fact-checked by

Claire Whitfield

Published

The short answer

To build an AI agent, give a language model three things: tools it can call (functions or APIs), instructions that define its job and limits, and a loop that runs each tool the model requests and feeds the result back until the task is done. Start with one narrow job, add a step limit and human approval for risky actions, then test it on real cases.

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, A practical guide to building agents

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.

The four parts of every AI agent
PartWhat it doesExample
ModelReads the task and decides the next stepClaude Opus 5.5, GPT models, an open-weight model
ToolsFunctions the model can ask your code to runLook up an order, search docs, create a ticket
InstructionsThe job description, rules and when to stopRefund only delivered orders; escalate anything over $100
LoopRuns requested tools and feeds results backRepeat 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:

  1. The goal. One sentence on what done looks like.
  2. Inputs. What the agent receives: a chat message, an email, a form, a ticket.
  3. Allowed actions. Every tool it may use, split into read-only and write actions.
  4. Hard limits. What it must never do, and the dollar or risk thresholds that need a human.
  5. Stop conditions. When it should finish, and when it should give up and hand off.
  6. 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.

Ways to build an AI agent, as of October 2026
RouteBest forTrade-offs
n8n AI Agent nodeAutomating internal workflows across many apps, visuallyYou still design the trigger, tools and approval steps yourself
ChatGPT workspace agentsTeams on ChatGPT Business, Enterprise, Edu or Teachers plansLives inside ChatGPT; launched as a preview with credit-based pricing
OpenAI Agent BuilderNot recommended for new projectsOpenAI is winding it down; unavailable from November 30, 2026
Model API plus your own loopProducts, custom logic and full controlYou write and maintain the code, the guardrails and the tests
Agent frameworkMulti-agent systems or durable, long-running stateExtra 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:

  1. Add a trigger: a chat message, a new email, a form submission or a schedule.
  2. Add the AI Agent node and connect a chat model sub-node with your provider's API key.
  3. Connect tool sub-nodes for the apps the agent needs, such as a spreadsheet lookup or a ticketing system.
  4. Paste your job card into the agent's system message, including the hard limits and when to stop.
  5. Route anything risky, such as refunds or outgoing emails, through an approval step before it runs.
  6. 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

The client reads ANTHROPIC_API_KEY from the environment
pip install anthropic
export ANTHROPIC_API_KEY="your-key-here"

2. Write the agent

agent.py: two tools, an approval gate, error handling and a step limit
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_result block with the matching tool_use_id. If the tool raises an error, it returns the message with is_error set, so the model can recover instead of your program crashing.
  • `run_agent` is the loop. While the model's stop_reason is tool_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 y before 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:

  1. Least privilege. Give the agent only the tools the job card lists, and make as many of them read-only as you can.
  2. Human approval for high-risk actions. OpenAI recommends escalating to a person for irreversible changes, large refunds and payments, especially early in a deployment.
  3. Step and spending limits. Cap the number of loop iterations, and alert yourself when a single task uses far more tokens than usual.
  4. 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.
  5. 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 search with 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.

Common questions

Can I build an AI agent without coding?

Yes. Visual tools such as n8n's AI Agent node and ChatGPT's workspace agents let you connect a model to tools and describe the job in plain language. You trade some control and portability for speed, so they suit internal workflows more than customer-facing products.

What programming language is best for building AI agents?

Python is a common starting point because the major model providers publish official Python SDKs, and the example in this guide uses one. TypeScript works just as well, especially for web apps. The agent loop itself is short in either language.

Do I need a framework like LangChain or CrewAI to build an AI agent?

No. Anthropic recommends starting with the model provider's API directly, since the core loop takes only a few lines. Reach for a framework when you need features it already solves, such as multi-agent handoffs or durable state, and make sure you understand what it does underneath.

How much does it cost to run an AI agent?

You pay per token for every model call, and an agent makes several calls per task. As of October 2026, Anthropic lists Claude Opus 5.5 at $4 per million input tokens and $20 per million output tokens, and Claude Haiku 5.5 from $0.10 and $0.50, so model choice and step limits drive most of the cost.

What is the difference between an AI agent and a chatbot?

A chatbot answers in text. An agent uses a model to decide which actions to take, calls tools to take them, and keeps going until the task is finished or it needs a human. OpenAI's guide notes that simple chatbots and single-turn LLM calls are not agents.

How long does it take to build a custom AI agent?

A narrow prototype can run the same day, as the example in this guide shows. Most of the real effort goes into writing good tool descriptions, testing against real cases and adding guardrails, and that work grows with how risky the agent's actions are.

Sources

  1. A practical guide to building agents, OpenAI
  2. Building effective agents, Anthropic
  3. Tutorial: Build a tool-using agent, Claude Platform Docs
  4. Define tools (How to implement tool use), Claude Platform Docs
  5. Models overview, Claude Platform Docs
  6. Introducing AgentKit, OpenAI
  7. Introducing workspace agents in ChatGPT, OpenAI
  8. AI Agent node documentation, n8n Docs
ME

About Marcus Ellery

12 years building payments and machine learning infrastructure

Marcus spent a decade building payment and machine learning infrastructure before starting GeeklyPlug in 2026. He writes the AI and technology coverage and tests every workflow he describes before it goes out.

ai agentshow to build an ai agenttool callingpythonno-code

Keep reading

More from AI, then the rest of the archive.

Get plugged in every Tuesday

One email. A handful of things worth knowing from wherever we have been digging that week, and what to actually do about each of them.

No spam. Unsubscribe in one click.