Dev tools
How to Build an AI Agent: Step by Step
Learn how to build an AI agent step by step: pick a job, give it tools and instructions, run the loop, add guardrails, and test it. Includes a Python example.
Learning how to build an AI agent is easier than it sounds. At its core, an agent is an AI model that can use tools in a loop: it reads a goal, decides what to do, takes an action, looks at the result, and repeats until the job is done. You can build a useful one in an afternoon with a no-code tool, or in about 70 lines of Python.
This guide explains what an agent is, how the loop works, and the parts every agent needs. It then walks through building one step by step, with a working Python example and the guardrails that keep it safe.
What is an AI agent?
An AI agent is software that uses a large language model to work toward a goal on its own. Instead of just answering a question, it can take actions, like searching the web, reading a file, calling an API, sending an email, or updating a database. It decides which action to take next based on what it has learned so far.
AI agent vs chatbot
The AI agent vs chatbot difference comes down to actions. A chatbot talks: you ask, it answers, and that's the end of the turn. An agent acts: you give it a goal, and it may take several steps, using tools and checking results, before it replies.
Ask a chatbot "is my order late?" and it can only tell you how to check. Ask an agent, and it looks up the order, sees it's delayed, checks the refund policy, and offers you a refund.
Agents already show up in many places. Coding tools like Claude Code are agents that read and edit your files. AI voice agents answer phone calls and book appointments. Research assistants search dozens of pages and write a report.
How AI agents work: the agent loop
Almost every agent, however complex, runs the same simple loop.
- Think. The model reads the goal and everything that has happened so far, then decides what to do next.
- Act. It asks to use a tool, for example "look up order A101."
- Observe. Your code runs the tool and sends the result back to the model.
- Repeat or finish. The model either picks another action or decides it has enough to give a final answer.
The important detail is that the model never runs anything itself. It only asks to use a tool. Your code decides whether to run it, runs it, and reports back. That gives you a natural place to add checks and approvals.
The four parts of every AI agent
1. A model
The large language model is the agent's brain. It understands the goal, plans, and decides which tool to use. Models from Anthropic, OpenAI, Google, and open-source projects all support tool use. Stronger models handle long, messy tasks better; smaller ones are faster and cheaper for simple jobs.
2. Instructions
A system prompt tells the agent who it is, what it's for, and what rules to follow. For example: "You are a support agent for an online shop. Always check the order before answering. Never promise a refund without approval."
3. Tools
Tools are functions the agent can call, such as a search, a database query, a calculator, or an API. Each tool has a name, a description, and a list of inputs. The description matters a lot, because the model decides when to use a tool based on what the description says.
4. Memory and knowledge
Short-term memory is the conversation so far, which the model sees on every step. It has a size limit, so long tasks need summarizing or trimming. Long-term memory and business knowledge, such as documents, policies, and past cases, usually live outside the model and are searched when needed, a technique called retrieval-augmented generation (RAG).
Before you build: do you need an agent?
Agents are flexible, but flexibility has costs. They're slower, harder to predict, and more expensive than simpler automation. Many tasks don't need one.
Use a fixed workflow when the steps are always the same, such as "when a form is submitted, summarize it and post it to Slack." You can still use AI inside a step.
Use an agent when the steps depend on what happens along the way, such as "investigate why this customer's payment failed and fix it if you can."
A good rule: start with the simplest thing that works. Add agent behavior only where you need the AI to make decisions.
How to build an AI agent: step by step
Here is how to build an AI agent from idea to deployment.
Step 1: Pick one narrow job
Start with a single, clear task, such as answering order questions, triaging support tickets, or researching a company before a sales call. "Run my business" is not a job. Write down what a good result looks like, so you can test against it later.
Step 2: Choose how you'll build it
You have three main routes:
- No-code tools: build visually by dragging and connecting blocks. This is the fastest way to start, with less control.
- Frameworks: libraries that handle the loop, memory, and multi-step logic for you.
- Plain code: call a model's API directly. This gives you the most control and teaches you how agents really work.
The tools for each route are covered later in this guide. If you're a developer, building one small agent in plain code first is worth it, even if you later switch to a framework.
Step 3: Choose a model
Pick a model that supports tool use (sometimes called function calling). Start with a capable model while you build, so you know failures are your design and not the model's limits. Then try a smaller, cheaper model and see if quality holds.
Step 4: Write the instructions
Keep the system prompt short and concrete. Cover the agent's role, its goal, when to use each tool, what it must never do, and when to stop or hand off to a human.
Step 5: Define the tools
Give the agent only the tools the job needs. For each one, write a clear name, a description of when to use it, and a simple input format. Return clear results, including helpful error messages, so the model can recover when something fails.
If you want to reuse tools across agents and apps, look at the Model Context Protocol (MCP). It's an open standard for connecting AI models to tools and data, and many services now offer ready-made MCP servers.
Step 6: Build the loop
Connect the model and tools with the think, act, observe loop. Always set a maximum number of steps, so a confused agent can't run forever and run up costs. The Python example below shows the whole loop.
Step 7: Add knowledge and memory
If the agent needs your business information, give it a search tool over your documents rather than pasting everything into the prompt. For long tasks, summarize older steps so the conversation stays within the model's limits.
Step 8: Add guardrails
Decide which actions are safe to run automatically and which need a human to approve, such as refunds, emails to customers, deleting data, or spending money. Limit what each tool can access, keep secrets out of prompts, and log every action.
Step 9: Test and evaluate
Write 20 to 50 realistic test cases, including tricky ones: missing information, rude users, requests outside the agent's job, and attempts to trick it into breaking its rules. Run them after every change and compare results. Agents can behave differently from run to run, so test each case more than once.
Step 10: Deploy and monitor
Start small, with a few users or a share of traffic. Review logs regularly, watch costs, and collect the cases where the agent failed. These become new test cases and guide your next round of improvements.
How to build an AI agent with Python: a working example
Here's a complete, small agent you can run. It's a customer support agent with two tools: one to look up an order, and one to issue a refund, which always asks a human to approve first. It uses Anthropic's official Python SDK, but the same pattern works with any model that supports tool use.
To build an AI agent with Python using this example, install the SDK with pip install anthropic, set your API key as the ANTHROPIC_API_KEY environment variable, save the code as agent.py, and run python agent.py.
import json
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from your environment
# 1. The tools: plain Python functions the agent is allowed to use
ORDERS = {"A100": {"status": "shipped", "total": 49.0},
"A101": {"status": "delayed", "total": 120.0}}
def lookup_order(order_id):
order = ORDERS.get(order_id)
return order if order else {"error": f"No order found with ID {order_id}"}
def issue_refund(order_id, amount):
# Guardrail: a human must approve every refund
answer = input(f"Approve refund of {amount} for order {order_id}? (y/n) ")
if answer.strip().lower() != "y":
return {"result": "Refund declined by a human reviewer"}
return {"result": f"Refund of {amount} issued for order {order_id}"}
TOOLS = [
{"name": "lookup_order",
"description": "Look up an order's status and total by its order ID.",
"input_schema": {"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"]}},
{"name": "issue_refund",
"description": "Refund an order. Only use when the customer asks for a refund "
"and the order is delayed.",
"input_schema": {"type": "object",
"properties": {"order_id": {"type": "string"},
"amount": {"type": "number"}},
"required": ["order_id", "amount"]}},
]
FUNCTIONS = {"lookup_order": lookup_order, "issue_refund": issue_refund}
# 2. The instructions
SYSTEM = ("You are a polite support agent for an online shop. Use your tools to "
"check orders before answering. Never promise anything you can't do.")
# 3. The loop
def run_agent(user_message, max_steps=10):
messages = [{"role": "user", "content": user_message}]
for _ in range(max_steps):
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
system=SYSTEM,
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":
output = FUNCTIONS[block.name](**block.input)
results.append({"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(output)})
messages.append({"role": "user", "content": results})
return "Stopped: too many steps."
if __name__ == "__main__":
print(run_agent("My order A101 is late. Can I get a refund?"))What the code does
The tools are ordinary Python functions. lookup_order reads from a small dictionary standing in for your real database. issue_refund stops and asks a person for approval before doing anything. That single input() line is the human-in-the-loop guardrail.
The tool definitions in TOOLS tell the model what each tool does and what inputs it takes. The model reads these descriptions to decide when to use each one.
The loop in run_agent sends the conversation to the model. If the model asks for a tool (stop_reason == "tool_use"), the code runs it and sends back the result. If not, the model is done, and its text is the final answer. max_steps stops runaway loops.
To grow this into a real agent, swap the dictionary for your actual database or API, add more tools, log every step, and replace input() with a proper approval step, such as a button in your admin dashboard.
No-code AI agent tools and AI agent frameworks
No-code AI agent builders
A no-code AI agent builder lets you connect a model to apps like Gmail, Slack, Google Sheets, or your CRM through a visual editor. Popular options include n8n, Zapier, Make, and Microsoft Copilot Studio. They're a great way to automate everyday business tasks and to test an idea before writing code.
The trade-off is control. Complex logic, custom tools, and detailed testing are harder in a visual builder, and costs can grow as usage grows.
AI agent frameworks
AI agent frameworks are code libraries that handle common needs, such as the loop, memory, multi-step plans, and multiple agents working together. Well-known open-source options include:
- LangGraph: builds agents as graphs of steps, with fine control over flow and state.
- CrewAI: organizes several agents with different roles into a team.
- OpenAI Agents SDK: a lightweight framework for building agents with OpenAI models.
- Claude Agent SDK: Anthropic's toolkit built on the same foundation as Claude Code, with file, command, and tool access built in.
- Google Agent Development Kit (ADK): Google's framework for building and deploying agents.
- Pydantic AI and smolagents: lighter, Python-first options.
Frameworks save time on bigger projects, but they add a layer you need to learn and debug. For a first agent, plain code is often simpler.
What does it cost to build an AI agent?
You can build and test an agent for very little. The frameworks above are free and open source, and many no-code tools have free tiers. The main ongoing cost is the AI model, which is usually charged by the amount of text processed. Agents use more than chatbots, because each step in the loop sends the conversation to the model again.
To keep costs under control, set a step limit, use smaller models where they're good enough, keep prompts and tool results short, and set spending limits in your provider's dashboard. You can also run open models on your own hardware, which removes per-use fees but needs a capable computer and gives up some quality compared with the strongest hosted models.
Common mistakes when building an AI agent
Too many tools. Dozens of overlapping tools confuse the model. Start with a few clear ones.
Vague tool descriptions. If the description doesn't say when to use a tool, the model will guess.
No step limit. A stuck agent can loop for a long time and burn through your budget.
Full autonomy too soon. Keep a human in the loop for risky actions until you've seen the agent handle many real cases well.
No tests. Without a test set, you can't tell whether a change made the agent better or worse.
Trusting outside content. Web pages, emails, and documents the agent reads can contain hidden instructions. This is called prompt injection. Treat anything the agent reads as data, not as commands, and limit what it can do after reading untrusted content.
FAQ
Can I build an AI agent for free?
Mostly, yes. Open-source frameworks are free, and many no-code tools and model providers offer free tiers or trial credits for testing. Running an agent at real scale usually means paying for model usage.
Do I need to know how to code to build an AI agent?
No. No-code tools like n8n, Zapier, Make, and Microsoft Copilot Studio let you build agents visually. Coding skills give you much more control, especially for custom tools, testing, and production use.
What is the best programming language for AI agents?
Python is the most popular, with the widest choice of frameworks and examples. TypeScript and JavaScript are a close second, especially for web apps. Most model providers offer official SDKs for both.
How long does it take to build an AI agent?
A simple prototype can take an afternoon. A reliable agent for real users, with integrations, guardrails, testing, and monitoring, usually takes weeks of iteration.
What's the difference between an AI agent and an AI workflow?
A workflow follows fixed steps you design in advance. An agent decides its own steps based on the situation. Workflows are cheaper and more predictable, and agents are more flexible. Many real systems combine both.