How to Make an AI Agent in 2026 (Step by Step)
The five parts every AI agent has, a runnable Python example in about 40 lines, and an honest guide to the guardrails and framework choices most tutorials skip.
On this page
Quick Answer (July 2026): To make an AI agent you give a language model three things and wrap them in a loop: instructions (what it should do), tools (functions it can call to act or fetch data), and a loop that runs the model, executes any tool it asks for, feeds the result back, and repeats until the task is done. Every agent, from a 40-line script to a production system, is built from the same five parts: a model, instructions, tools, the loop, and guardrails. Below is a runnable Python example you can paste and run today.
What an AI agent actually is
An AI agent is a language model that can take actions in a loop, not just answer once. A plain chatbot returns a single reply. An agent decides it needs more information or an action, calls a tool to get it, reads the result, and keeps going until the task is finished or it hits a limit you set.
That is the whole idea. Everything else is plumbing around it.
The five parts of every AI agent
Strip away the frameworks and every agent has the same anatomy. Learn these five parts once and every tutorial, SDK, and product starts to look familiar.
Scroll to see more
| Part | What it is | In the example below |
|---|---|---|
| Model | The reasoning engine that decides what to do next | claude-sonnet-5 |
| Instructions | The goal and rules, usually a system prompt | The user request + tool descriptions |
| Tools | Functions the model can call to act or fetch data | A calculator function |
| The loop | Run model, run tools, feed results back, repeat | The for loop in run_agent |
| Guardrails | The limits that stop it running forever or unsafely | max_turns, input validation |
Most beginners think an agent is the model. It is not. The model is one of five parts, and the loop is the part that actually makes it an agent.
Make a minimal AI agent in Python
You need Python 3.10 or newer, the official Anthropic SDK, and an API key.
Install the SDK and set your key:
pip install anthropic
export ANTHROPIC_API_KEY="sk-ant-..."
Now the whole agent. It has one tool, a calculator, because language models are unreliable at arithmetic and a tool is the honest fix. Paste this into
agent.py:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
CALCULATOR = {
"name": "calculator",
"description": "Evaluate a basic arithmetic expression and return the result. "
"Always use this for math instead of computing it yourself.",
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "A safe arithmetic expression, e.g. '(1500 * 12) * 0.7'.",
}
},
"required": ["expression"],
},
}
def run_calculator(expression: str) -> str:
# Locked-down evaluator. Never eval() untrusted input in production (see guardrails).
if not set(expression) <= set("0123456789+-*/(). "):
return "error: unsupported characters"
try:
return str(eval(expression, {"__builtins__": {}}, {}))
except Exception as e:
return f"error: {e}"
def run_agent(user_message: str, max_turns: int = 6) -> str:
messages = [{"role": "user", "content": user_message}]
for _ in range(max_turns):
response = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
tools=[CALCULATOR],
messages=messages,
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
# No tool call means the agent is done. Return its final text.
return "".join(b.text for b in response.content if b.type == "text")
# The model asked for one or more tools. Run each and send the results back.
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = run_calculator(**block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result,
})
messages.append({"role": "user", "content": tool_results})
return "Stopped: hit the turn limit before finishing."
if __name__ == "__main__":
print(run_agent(
"A SaaS makes $1,500 MRR and grows 7% each month. "
"Roughly what is the MRR after 12 months? Use the calculator."
))
Run it:
python agent.py
The agent calls the calculator (it evaluates 1500 * 1.07 ** 12), reads the number, and answers in plain English. You just built an AI agent in about 40 lines with no framework.
Read the loop, line by line
The loop is the part worth understanding, because every agent framework is a fancier version of it.
- You send the user message and the list of tools to the model.
- The model replies. If
stop_reasonis"tool_use", it wants to call a tool; the reply contains one or moretool_useblocks with anidand the arguments it chose. - You run the real function, then append a
tool_resultblock that references the sameid. This is how the model connects its request to your answer. - You call the model again with the tool result in the history. It either asks for another tool or, when it has enough, returns a normal text answer and
stop_reasonis no longer"tool_use". That is your exit condition.
Swap the calculator for a web search, a database query, or an HTTP call and the shape does not change. That is why the loop matters more than any single tool.
The guardrails most tutorials skip
The 40-line version works on your machine. The reason it is not production is that it has almost no guardrails, and this is exactly where real agents fail.
- Turn limits. Without
max_turnsa confused model can loop forever and burn your budget. Always cap it. Ours stops at six. - Tool errors. Our
run_calculatorreturns an error string instead of raising. Feed errors back to the model as normal results so it can recover, rather than crashing the whole run. - Cost caps. Every turn is another paid model call. Track token usage from the response and stop when a run crosses a ceiling you set. Model API usage is billed per token, so a runaway loop is a runaway bill (Anthropic list pricing, 2026).
- Untrusted input. The single most common security mistake is calling
eval(), shell commands, or SQL with arguments the model produced from user text. Validate every tool argument, give tools the least privilege they need, and never let a tool do something you would not let a stranger do. Prompt injection is real: treat tool inputs as hostile.
None of the top-ranked "make an AI agent" tutorials show these four together. They are the difference between a demo and something you can leave running.
When to reach for a framework
You do not need a framework to start, and starting framework-free is the fastest way to actually understand agents. Reach for more structure when the loop above stops being enough.
Scroll to see more
| You have | Use | Why |
|---|---|---|
| One agent, a few tools, learning | Framework-free (this article) | Nothing to learn but the loop |
| Real tool permissions, sessions, subagents | The Claude Agent SDK | Batteries included, same loop underneath |
| Complex branching, long-running state, human approval steps | A graph framework like LangGraph | Explicit control flow and durable state |
If you want to go deeper on the raw version, our walkthrough on how to build this same loop from scratch takes it further. When you outgrow hand-rolling, we compared the Claude Agent SDK versus writing the loop yourself so you can decide where the line is. For the underlying API, see Anthropic's tool use documentation (2026); the same loop applies to OpenAI's Agents SDK if you are on that stack. The pattern itself was formalized in the 2022 ReAct paper, which is still the clearest description of why the reason-then-act loop works.
Where your agent runs and acts on real data
A script on your laptop is a fine place to learn, but a useful agent usually needs somewhere to live and something real to act on: a database, authentication, and an API it can call as tools. For a hobby project a single server and a few functions is enough. When the agent needs to drive a real application, you either build that backend yourself or use a platform that gives the agent one. Totalum, an AI app builder, exposes its backend over API and MCP so an agent can create and drive a real app with hosting, database, and auth, rather than you wiring all of it by hand. Either path works; the point is that the agent is only as capable as the tools and backend you connect to it.
Sources
- Anthropic, tool use documentation, 2026: https://docs.claude.com/en/docs/build-with-claude/tool-use/overview
- OpenAI Agents SDK for Python, 2026: https://github.com/openai/openai-agents-python
- Yao et al., ReAct: Synergizing Reasoning and Acting in Language Models, 2022: https://arxiv.org/abs/2210.03629
Written by
Ren OkabeRen builds agent infrastructure and writes copy-paste tutorials for engineers shipping LLM tool-use systems.
Frequently asked questions
Is it free to make an AI agent?
The code and the open-source SDKs are free. What you pay for is model usage, billed per token every time the agent calls the model. A small learning agent like the one in this guide costs a fraction of a cent per run in 2026; a busy production agent that loops many times per task costs more, which is why token and turn caps matter.
Can I make an AI agent without coding?
Yes. No-code agent builders let you assemble tools and prompts visually, and they are a good way to prototype. The trade-off is control: once you need custom tools, precise guardrails, or to run the agent inside your own product, writing the loop yourself (about 40 lines of Python) gives you far more room than a no-code canvas.
Can you build an AI agent with ChatGPT?
Yes. OpenAI's API and Agents SDK follow the same reason, call a tool, feed the result back, repeat pattern shown here. The provider and the SDK names change; the five parts (model, instructions, tools, loop, guardrails) and the loop do not.
How is an AI agent different from a chatbot?
A chatbot answers once. An agent runs in a loop and can take actions between the question and the answer: it calls tools, reads the results, and decides what to do next until the task is done. The loop is what makes it an agent rather than a single-shot responder.
What are the main types of AI agents?
In practice the useful split is by how much autonomy you give the loop: a single tool-using agent (one model, a few tools, like this guide), a multi-step agent with memory and planning, and multi-agent systems where several agents hand work to each other. Start with the single tool-using agent; the other two are the same loop with more parts.
Which programming language should I use to build an AI agent?
Python and TypeScript are the two most supported in 2026, because the official Anthropic and OpenAI SDKs target both. Pick the one your project already uses. The concepts in this guide are identical in either language.
Related tutorials
Build your first AI agent from scratch in 30 minutes
An AI agent is just a loop: you call a model, the model asks to run a tool, you run it, you feed the result back, and you repeat until the model is done. In this tutorial you build that loop yourself in plain TypeScript against the Anthropic Messages API, no framework. You will wire up two tools (read a file, run a calculation), let the model orchestrate them, add a turn cap and basic guardrails, then verify the whole thing end to end. The result is a small research agent you fully understand and can extend with your own tools.
Claude Agent SDK vs Writing the Agent Loop Yourself (2026): When Each Wins
Should you use the Claude Agent SDK or hand-roll the agent loop with the Anthropic Client SDK? An honest 2026 comparison with runnable TypeScript for both and a decision table.
AI Agent Memory: Long-Term Memory for a Claude Agent in TypeScript (2026)
A runnable 2026 tutorial: build short-term and long-term memory for a Claude agent in TypeScript with message buffers, rolling summaries, and a durable fact store. No vector database required.