Skip to content
AI15 min read

How to build an AI agent (or create your own): no-code and Python routes

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.

By

Editor

Published

Updated

Cover image for “Build an AI agent”: 5 steps, with or without code, illustrated with an AI agent robot being built.

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.

Build your own AI agent: a loop where a task goes to the model, the model calls tools, and the result feeds back until the job is done
Every AI agent runs the same loop: the model decides, tools act, and the result feeds back until the job is done.

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

  1. 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.
  2. 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.
  3. 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.
  4. Add guardrails. Grant the fewest permissions possible, require human approval for risky actions, and cap steps and spending.
  5. 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, 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. 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:

  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

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.

Ways to build an AI agent
RouteBest forTrade-offs
No-code builderAutomating internal workflows across many apps, visuallyLess control and portability; you still design the trigger, tools and approval steps
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

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.

No-code AI agent builders, free options and entry prices from official pages
BuilderFree optionEntry paid planBest 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 cardCloud Starter: 20 euros/month billed annually, 2,500 executionsTechnical teams that want to self-host
Zapier Agents (opens in a new tab)Agents Free: 400 activities a monthAgents Pro: $400/year ($33.33/month), 1,500 activitiesTeams already automating with Zapier
Make AI Agents (opens in a new tab)Free plan: 1,000 credits a monthCore: from $9/month for 10,000 creditsVisual workflows with agents on the same canvas
Lindy (opens in a new tab)$50 of credits that last 7 daysTeam: $49.99/month per active user, 5,000 creditsEmail, 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 goCompanies on Microsoft 365
ChatGPT workspace agents (opens in a new tab)None; free only during the preview, until May 6, 2026Credit-based, on ChatGPT Business, Enterprise, Edu or TeachersTeams 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.

  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, 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

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):
    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_result block with the matching tool_use_id. If the tool raises an error, or the model names a tool that does not exist, it returns a clear 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. If the reply was cut off by max_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 y before 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_tokens and 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:

  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. 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 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. No-code builders such as n8n's AI Agent node, Zapier Agents and Make AI Agents let you connect a model to tools and describe the job in plain language, and each had a free option at the time of writing. 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. At the time of writing, 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
  9. Pricing, n8n
  10. Choose how to use n8n, n8n Docs
  11. Pricing, Zapier
  12. Make AI Agents, Make
  13. Make vs n8n, Make
  14. Pricing, Lindy
  15. Copilot Studio pricing, Microsoft

Revision history

  • : Retested the agent on anthropic SDK 2.14.0 with ten scripted cases. Fixed five weaknesses the tests found (unknown tools, refund checks, no approver, cut-off replies) and documented each one.
  • : Retitled the guide, added a five-step summary and a no-code builder table checked against official pricing pages, removed the year from the search title and added links to related guides.

About Marcus E.

Qualified software engineer with 10+ years of experience building payments and machine learning infrastructure

Marcus is a qualified software engineer who spent 10+ years building payment and machine learning infrastructure before joining GeeklyPlug. He writes AI and technology guides, with a focus on models, machine learning and the tools developers use.

ai agentshow to build an ai agenttool callingpythonno-code

Keep reading

More from AI, then the rest of the archive.