Build an AI Agent in Python from Scratch (Step-by-Step)
Build a working AI customer-support agent in about 100 lines of Python using the Claude API and tool use. No frameworks, every line explained.
In this tutorial you’ll build a real AI agent: a customer-support assistant for an online store that can look up orders, check the refund policy and issue refunds, deciding for itself which tools to use and in what order.
We won’t use any agent framework. Just Python and the official Anthropic SDK, so you can see exactly how agents work. If you’re new to the concept, read What Are AI Agents? first.
What you’ll build:
You: Hi, I want a refund for order A-1001, the mouse is too small.
→ lookup_order({"order_id": "A-1001"})
→ get_refund_policy({})
→ issue_refund({"order_id": "A-1001", "reason": "Item too small"})
Agent: Done! I've refunded $49.00 for order A-1001. You'll see it within 5–7 business days.
Prerequisites
- Python 3.10 or newer
- An Anthropic API key from the Claude Console
- Basic Python knowledge (functions, dicts, loops)
Step 1: Set up the project
Create a folder and a virtual environment, then install the SDK:
mkdir support-agent && cd support-agent
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install anthropic
Set your API key as an environment variable. The SDK reads it automatically:
export ANTHROPIC_API_KEY="sk-ant-..." # Windows PowerShell: $env:ANTHROPIC_API_KEY="sk-ant-..."
Never hard-code API keys in source files or commit them to Git.
Step 2: Create the “business” the agent works with
Real agents call real APIs. To keep this tutorial self-contained, we’ll fake a tiny order database. Create agent.py:
import json
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-opus-5-5"
# A pretend order database. In production these would be API or database calls.
ORDERS = {
"A-1001": {"customer": "[email protected]", "status": "delivered", "total": 49.00, "items": ["Wireless mouse"]},
"A-1002": {"customer": "[email protected]", "status": "shipped", "total": 129.00, "items": ["Mechanical keyboard"]},
}
REFUNDS: list[dict] = []
REFUND_POLICY = (
"Delivered orders can be refunded within 30 days if items are unused or faulty. "
"Orders that have not been delivered yet cannot be refunded, but the customer can refuse delivery."
)
Step 3: Write the tools as normal Python functions
Tools are just functions. The agent will decide when to call them.
def lookup_order(order_id: str) -> dict:
order = ORDERS.get(order_id)
if order is None:
return {"error": f"No order found with ID {order_id}."}
return {"order_id": order_id, **order}
def get_refund_policy() -> dict:
return {"policy": REFUND_POLICY}
def issue_refund(order_id: str, reason: str) -> dict:
order = ORDERS.get(order_id)
if order is None:
return {"error": f"No order found with ID {order_id}."}
if order["status"] != "delivered":
return {"error": "Only delivered orders can be refunded."}
REFUNDS.append({"order_id": order_id, "amount": order["total"], "reason": reason})
order["status"] = "refunded"
return {"success": True, "order_id": order_id, "amount_refunded": order["total"]}
TOOL_FUNCTIONS = {
"lookup_order": lookup_order,
"get_refund_policy": get_refund_policy,
"issue_refund": issue_refund,
}
Notice that issue_refund re-checks the business rule (only delivered orders) in code. Never rely on the model alone to enforce rules that matter.
Step 4: Describe the tools to the model
The model can’t see your Python code. It sees a name, a description and a JSON Schema for each tool’s inputs. Clear descriptions are the single biggest factor in whether an agent picks the right tool.
TOOLS = [
{
"name": "lookup_order",
"description": "Look up an order by its ID. Returns the customer email, status "
"(processing, shipped, delivered, refunded), total in USD and items.",
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "The order ID, e.g. A-1001"},
},
"required": ["order_id"],
},
},
{
"name": "get_refund_policy",
"description": "Get the store's current refund policy. Check this before issuing any refund.",
"input_schema": {"type": "object", "properties": {}},
},
{
"name": "issue_refund",
"description": "Refund a delivered order in full. Only use after confirming the order "
"exists and the refund policy allows it.",
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "The order ID to refund"},
"reason": {"type": "string", "description": "Short reason given by the customer"},
},
"required": ["order_id", "reason"],
},
},
]
SYSTEM_PROMPT = """You are a friendly, concise customer-support agent for Acme Gadgets.
Use the tools to look up real order data. Never guess order details.
Check the refund policy before issuing a refund. If a request falls outside the policy,
explain why politely and suggest what the customer can do instead."""
Step 5: Build the agent loop
This is the heart of every agent. We call the model; if it asks to use tools, we run them and send the results back; we repeat until it gives a final answer.
def execute_tool(name: str, tool_input: dict) -> tuple[str, bool]:
"""Run a tool and return (result_json, is_error)."""
func = TOOL_FUNCTIONS.get(name)
if func is None:
return json.dumps({"error": f"Unknown tool {name}"}), True
try:
result = func(**tool_input)
return json.dumps(result), "error" in result
except Exception as exc: # Never let a tool crash the agent
return json.dumps({"error": str(exc)}), True
def run_agent(messages: list, max_steps: int = 10) -> str:
for _ in range(max_steps):
response = client.messages.create(
model=MODEL,
max_tokens=16000,
system=SYSTEM_PROMPT,
tools=TOOLS,
messages=messages,
)
if response.stop_reason == "refusal":
return "Sorry, I can't help with that request."
# Always append the full assistant content (text + tool calls) to 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 return all results in ONE user message.
tool_results = []
for block in response.content:
if block.type == "tool_use":
print(f" → {block.name}({json.dumps(block.input)})")
output, is_error = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": output,
"is_error": is_error,
})
messages.append({"role": "user", "content": tool_results})
return "I couldn't finish that request. A human agent will follow up shortly."
A few details that trip people up:
- Append
response.content, not just the text. The model needs to see its own tool calls on the next turn. - Every
tool_useneeds a matchingtool_resultwith the sametool_use_id. - Return all tool results together in a single user message when the model calls several tools at once.
- Report failures with
is_error: Trueinstead of hiding them, so the model can recover or explain. - Cap the number of steps so a confused agent can’t loop forever.
Step 6: Add a chat interface and run it
if __name__ == "__main__":
history: list = []
print("Acme support agent. Type 'quit' to exit.\n")
while True:
user = input("You: ").strip()
if user.lower() in {"quit", "exit"}:
break
history.append({"role": "user", "content": user})
print(f"Agent: {run_agent(history)}\n")
Run it:
python agent.py
Try a few conversations:
- “Where is my order A-1002?” → it looks up the order and reports “shipped”.
- “Refund A-1001 please, it’s too small.” → it checks the order and the policy, then refunds.
- “Refund A-1002.” → it declines, because the order isn’t delivered yet, and explains the options.
- “What’s the status of A-9999?” → it reports that the order doesn’t exist instead of making something up.
Because history persists across turns, the agent remembers the conversation: “And what was the total on that one?” works.
Bonus: the same agent with the SDK’s tool runner
Writing the loop yourself is the best way to learn. In real projects, the Python SDK’s tool runner can drive the loop for you. Decorate your functions with @beta_tool, and it generates the JSON schemas from your type hints and docstrings:
import json
import anthropic
from anthropic import beta_tool
client = anthropic.Anthropic()
@beta_tool
def lookup_order(order_id: str) -> str:
"""Look up an order by its ID.
Args:
order_id: The order ID, e.g. A-1001.
"""
return json.dumps(ORDERS.get(order_id) or {"error": "Order not found"})
# ...decorate get_refund_policy and issue_refund the same way...
runner = client.beta.messages.tool_runner(
model="claude-opus-5-5",
max_tokens=16000,
system=SYSTEM_PROMPT,
tools=[lookup_order, get_refund_policy, issue_refund],
messages=[{"role": "user", "content": "Refund A-1001, it's too small."}],
)
final = runner.until_done()
print("".join(block.text for block in final.content if block.type == "text"))
Where to go next
You now have a working agent, but it’s not production-ready. Before real customers use it, you’d add:
- Guardrails and human approval for risky actions like refunds. That’s the next tutorial: Add Guardrails and Human Approval to an AI Agent.
- Knowledge from your documents with retrieval. See Build a RAG Chatbot in Python.
- Evaluation: a set of test conversations you run on every change.
- Logging and monitoring of every tool call.
- Cost controls: estimate them with our LLM cost calculator.
Want this built for your business? We build production AI agents connected to your real systems, with guardrails, evaluation and monitoring included.
Frequently asked questions
Do I need a framework like LangChain to build an AI agent?
No. A basic agent is a loop around an LLM API call with tool use. Frameworks help with larger systems, but building one from scratch first makes it much easier to understand and debug.
Which model should I use for an AI agent?
Use a model with strong tool-use ability. This tutorial uses Claude Opus 5.5; you can swap the model ID for a smaller, cheaper model once your agent works and you have tests in place.
We offer custom ai agent development from $4,000, with a fixed quote after a free 30-minute call.