Skip to content
codewithanjum
AI agents

How to build an AI agent: a practical guide for founders

How to build an AI agent that works: the loop, one narrow job, tool design and guardrails, plus no-code and code options with a working Python example.

By Md Anjum Kamali · · 6 min read

Painting of a hand placing a block with a sunburst symbol on top of a small pyramid of coloured wooden blocks
On this page
  1. What are the parts of an AI agent?
  2. How do you build an AI agent, step by step?
  3. No-code or code: which should you use?
  4. Start this week
  5. Questions people ask

To build an AI agent, you give a language model a goal, a short list of tools it can call, somewhere to keep what it has learned so far, and a rule for when to stop. Then you run it in a loop: the model picks a tool, your code runs it, the result goes back to the model, and it repeats until the job is done or it hits the limit. Everything else is making that loop reliable for one specific job.

An AI agent is a program where a language model decides its own next step, calling tools in a loop until a goal is met, instead of following a fixed script you wrote in advance.

I built one inside Prospectee, the data enrichment tool I co-founded. It browses company websites using the user's own LLM key. One user ran it on 45,000 rows and paid under $2 in model fees. It does one narrow job, and that's the first lesson in this guide.

What are the parts of an AI agent?

Every agent, whether it's a node in n8n or 2,000 lines of Python, has the same four parts.

Part What it does What goes wrong if you skip it
Model Reads the goal and the history, picks the next action Nothing works
Tools Functions the model can call: search, fetch a page, query a DB, send a message The model can only talk, not act
Memory The running message history, plus anything saved between runs It repeats work or forgets what it found
Stop condition A turn limit, a "done" signal, a budget cap It loops forever and burns money

Anthropic's guide on building effective agents puts it simply: agents usually stop when the task is complete, and it's common to add a maximum number of iterations to keep control. Do both.

How do you build an AI agent, step by step?

1. Pick one narrow job

"An agent that does sales research" fails. "Given a company domain, read the homepage and return the industry, what they sell and who they sell to, as JSON" works.

A narrow job has a clear input, a clear output and a way to check if the output is right. If you can't describe a correct answer, you can't test the agent, and you won't know if a prompt change made it better or worse.

Ask one more question before you start: does this need an agent at all? If the steps are always the same (fetch page, extract fields, save row), a fixed workflow with one LLM call is cheaper and easier to debug. Agents earn their place when the number of steps changes from case to case. I go deeper on this in AI agents vs workflows.

2. Design the tools

Tools are where most agents succeed or fail. The model chooses tools by reading their names and descriptions, so write those for the model the way you'd write docs for a new hire.

What I've found works:

  • Fewer tools. Three clear tools beat twelve overlapping ones.
  • Descriptions that say when to use the tool, what it returns and what it can't do.
  • Inputs that are hard to get wrong. Anthropic's guide calls this poka-yoke: in their coding agent, switching to absolute file paths removed a whole class of errors. Same idea for you: ask for a full URL, an ID or an enum, not free text.
  • Small outputs. Whatever a tool returns gets sent back to the model on every later turn. A tool that returns a whole HTML page will wreck your cost and your accuracy.
  • Errors as text. If a tool fails, return the error message so the model can try another way instead of crashing.

If you already have tools you want to reuse across apps, wrap them in an MCP server. I explain how in what is MCP.

3. Write the loop

Here's a complete agent in Python using the Anthropic SDK. It has one tool that fetches a web page, a turn limit, and error handling. No framework.

import os
import re
import urllib.request

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY
MODEL = os.environ["ANTHROPIC_MODEL"]  # any current Claude model id
MAX_TURNS = 8  # the stop condition

def fetch_page(url: str) -> str:
    req = urllib.request.Request(url, headers={"User-Agent": "tiny-agent/1.0"})
    html = urllib.request.urlopen(req, timeout=10).read().decode("utf-8", "ignore")
    text = re.sub(r"<script.*?</script>|<style.*?</style>|<[^>]+>", " ", html, flags=re.S)
    return re.sub(r"\s+", " ", text)[:4000]  # keep the context small

TOOLS = [{
    "name": "fetch_page",
    "description": "Download a web page and return its visible text (first 4,000 characters). "
                   "Use it to read a company's homepage before answering questions about it.",
    "input_schema": {
        "type": "object",
        "properties": {"url": {"type": "string", "description": "Full URL, e.g. https://example.com"}},
        "required": ["url"],
    },
}]
HANDLERS = {"fetch_page": fetch_page}

def run(task: str) -> str:
    messages = [{"role": "user", "content": task}]
    for _ in range(MAX_TURNS):
        response = client.messages.create(
            model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":
            return "".join(b.text for b in response.content if b.type == "text")

        results = []
        for block in response.content:
            if block.type == "tool_use":
                try:
                    output = HANDLERS[block.name](**block.input)
                    results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
                except Exception as e:
                    results.append({"type": "tool_result", "tool_use_id": block.id,
                                    "content": f"Error: {e}", "is_error": True})
        messages.append({"role": "user", "content": results})

    return "Stopped: hit the turn limit."

if __name__ == "__main__":
    print(run("What does the company at https://example.com do? One sentence."))

The model ID comes from an environment variable so you can swap models without touching code. The messages list is the agent's short-term memory. When stop_reason is anything other than tool_use, the model has decided it's done.

Read this loop until it feels obvious. Every agent framework is a more featured version of these 40 lines.

4. Build a small eval set before you tune anything

Collect 20 to 50 real inputs with the answers you expect. Run the agent on all of them after every prompt or tool change and count how many come out right. A spreadsheet is fine.

Without this, you'll fix one case and quietly break three others. With it, you can try a cheaper model and know within minutes whether it holds up.

Look at the full transcripts of failures, not only the final answers. Most bugs are visible in the tool calls: a wrong URL format, a tool called five times in a row, a description the model misread.

5. Add guardrails

Guardrails are the rules that stop a confused model from doing damage.

  1. Cap turns and tokens per run, and cap spend per day at the provider level.
  2. Give tools the least access that works. A research agent doesn't need a delete endpoint.
  3. Require a human to approve anything that sends, pays, deletes or posts.
  4. Validate the final output in code. If you asked for JSON with four fields, check it in code and retry when it doesn't match.
  5. Treat text from web pages and emails as data. A page can contain instructions aimed at your agent, so never let fetched content change what tools the agent can use.

6. Watch the cost

Every turn resends the whole conversation. So cost grows with turns times context size, and the two levers that matter most are both in your control: fewer turns and smaller tool outputs.

The cheap fixes are boring: trim text before it reaches the model, keep the turn limit low, and ask for a short structured answer. If you're building for customers, letting them bring their own LLM key (BYOK, which is how Prospectee works) means you don't pay for their usage at all.

No-code or code: which should you use?

Option Good for Watch out for
n8n AI Agent node Prototypes, internal automations, connecting SaaS apps Custom logic gets clunky; the loop is capped at 10 iterations unless you change it
Raw API loop (above) Learning, small focused agents, full control You write retries and logging yourself
Claude Agent SDK Agents that work with files, run commands, use MCP servers It's built on the same engine as Claude Code, so it's tied to Claude models
OpenAI Agents SDK Multi-agent setups with tracing built in More concepts to learn up front

The n8n AI Agent node docs list the default of 10 max iterations and note that its memory doesn't persist between sessions. I run n8n self-hosted for my own automations, like the signup alert flow in my n8n workflow for outbound, and for a quick agent it's the fastest way to see if an idea holds up.

The Claude Agent SDK installs with pip install claude-agent-sdk or npm install @anthropic-ai/claude-agent-sdk. The OpenAI one is pip install openai-agents. Both are moving fast, so check their docs for current APIs before you copy anything from a blog post, including this one.

Start this week

Pick the most repetitive research task on your plate, write down ten examples with correct answers, and build the 40-line version above with one tool. If it gets eight of ten right, you have something worth hardening. If it gets three, fix the tool descriptions before you touch the prompt.

Questions people ask

Can I build an AI agent without coding?

Yes. n8n's AI Agent node gives you a model, memory and tools on a visual canvas, and it caps the loop at 10 iterations by default. You'll hit limits on custom logic sooner than with code, but it's a fine way to prove the job is worth automating.

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

In a workflow, you write the steps and the model fills in blanks. In an agent, the model decides which step to take next and when it's done. Anthropic's guide on building agents suggests starting with the simplest version that works, which is often a workflow.

Which framework should I use to build an AI agent?

For a first agent, the model provider's plain API and a 40-line loop is enough and teaches you the most. Reach for something like the Claude Agent SDK or the OpenAI Agents SDK when you need file access, sessions, handoffs between agents or tracing out of the box.

How much does it cost to run an AI agent?

It depends on the model, how many turns the loop runs and how much text each tool returns, since all of it gets sent back to the model every turn. Capping turns, trimming tool output and using a small model for easy steps keeps it cheap.

Keep reading