An AI agent is an LLM that can decide to take actions, such as searching, calculating, reading a file or calling an API, then look at the results and decide what to do next. That loop of think → act → observe → repeat is what separates an agent from a chatbot.
In this guide you'll build a real agent in plain Python using tool calling (also called function calling). There's no framework, so you'll see exactly how every agent library works underneath.
The agent loop in one picture
- You send the model a task plus a list of tools it may use.
- The model replies with either a final answer or a request to call a tool with specific inputs.
- Your code runs the tool and sends the result back.
- Repeat until the model gives a final answer (or you hit a step limit).
The model never runs code itself. Your program decides what each tool does, which is how you stay in control.
What you need
pip install anthropic
export ANTHROPIC_API_KEY="your-key-here"
We'll use Anthropic's Python SDK. OpenAI's API follows the same pattern with slightly different field names.
Step 1: Write the tools as normal Python functions
Our agent will help with simple business questions. It gets two tools: a calculator and a lookup over a small product database.
import ast
import operator as op
PRODUCTS = {
"starter": {"price": 19, "monthly_users": 1200},
"pro": {"price": 49, "monthly_users": 430},
"team": {"price": 129, "monthly_users": 85},
}
# Safe calculator: only allows numbers and basic math, never runs arbitrary code
_OPS = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.USub: op.neg}
def _eval(node):
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_eval(node.left), _eval(node.right))
if isinstance(node, ast.UnaryOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_eval(node.operand))
raise ValueError("Unsupported expression")
def calculator(expression: str) -> str:
return str(_eval(ast.parse(expression, mode="eval").body))
def get_product(name: str) -> str:
product = PRODUCTS.get(name.lower())
return str(product) if product else f"No product named '{name}'. Options: {', '.join(PRODUCTS)}"
TOOL_FUNCTIONS = {"calculator": calculator, "get_product": get_product}
Notice the calculator doesn't use Python's eval(). Never let model output run as code without strict limits.
Step 2: Describe the tools to the model
The model only sees the name, description and input schema. Good descriptions matter: they're how the model decides when to use each tool.
TOOLS = [
{
"name": "calculator",
"description": "Evaluate a math expression. Use for any arithmetic. Supports + - * / ** and parentheses.",
"input_schema": {
"type": "object",
"properties": {"expression": {"type": "string", "description": "e.g. '49 * 430'"}},
"required": ["expression"],
},
},
{
"name": "get_product",
"description": "Look up a subscription plan's monthly price and number of paying users.",
"input_schema": {
"type": "object",
"properties": {"name": {"type": "string", "description": "Plan name: starter, pro or team"}},
"required": ["name"],
},
},
]
Step 3: Write the agent loop
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5" # check the provider's docs for current model names
MAX_STEPS = 10
def run_agent(task: str) -> str:
messages = [{"role": "user", "content": task}]
for step in range(MAX_STEPS):
response = client.messages.create(
model=MODEL,
max_tokens=1024,
system="You are a careful business analyst. Use tools for facts and math. Show your final numbers clearly.",
tools=TOOLS,
messages=messages,
)
# Keep the model's full reply (text + tool requests) in the history
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
return "".join(block.text for block in response.content if block.type == "text")
# Run every tool the model asked for and send the results back
results = []
for block in response.content:
if block.type == "tool_use":
func = TOOL_FUNCTIONS.get(block.name)
try:
output = func(**block.input) if func else f"Unknown tool {block.name}"
is_error = func is None
except Exception as e:
output, is_error = f"Error: {e}", True
print(f" [tool] {block.name}({block.input}) -> {output}")
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": output,
"is_error": is_error,
})
messages.append({"role": "user", "content": results})
return "Stopped: reached the step limit without a final answer."
if __name__ == "__main__":
print(run_agent("What's our total monthly revenue across all three plans, and which plan earns the most?"))
Run it and you'll see the agent look up each plan, call the calculator, and then write a summary. It works out the steps itself; you never told it the order.
Why each piece matters
stop_reason == "tool_use"tells you the model wants to act rather than answer.tool_use_idlinks each result to the request that asked for it. The model may ask for several tools at once.- Errors are returned, not raised. Sending the error back lets the model fix its own mistake, such as a misspelled plan name.
MAX_STEPSstops a confused agent from looping forever and running up your bill.
Building your first LLM app?
Pair this with the step-by-step RAG tutorial and the AI agent guide.
Making agents reliable
Building a demo agent is easy. Making one reliable is where AI engineers earn their pay.
- Few, clear tools. Five well-described tools beat twenty vague ones.
- Validate inputs inside every tool. Treat model output like user input from the internet.
- Human approval for risky actions. Sending emails, spending money or deleting data should need a human "yes".
- Log everything: every prompt, tool call and result. You'll need it for debugging.
- Evaluate with real tasks. Keep a list of 20+ tasks with known good outcomes and rerun them after every change.
- Watch for prompt injection. If a tool returns web pages or emails, that text could contain instructions aimed at your agent. Never let retrieved text grant new permissions.
When to use a framework
Once you need persistent memory, multi-agent workflows, pausing for human approval, or resuming long tasks after a crash, a framework saves real time. LangGraph is the most widely used option for stateful agents; LangChain and LangGraph both reached version 1.0 in October 2025. LlamaIndex Workflows is a good fit when your agent is mostly about document retrieval. See LangChain vs LlamaIndex.
Ideas for your first real agent
- A research agent that searches, reads sources and writes a cited summary
- A support agent that answers from your docs using RAG and creates a ticket when it can't
- A data agent that queries a read-only database and builds a weekly report
- A sales-ops agent that enriches leads from a spreadsheet
Each of these also makes a strong portfolio project. Pair it with our AI engineer resume keywords when you apply, or turn it into a product with our AI business ideas.