Building Your First AI Agent: A Practical Guide
Learn how to build AI agents that can browse the web, use tools, and complete complex tasks autonomously.
AI agents are the next evolution beyond chatbots. Instead of just answering questions, agents can take actions, use tools, and work autonomously toward goals. This guide walks you through building your first agent.
What Makes an Agent Different?
Chatbot: Responds to messages Agent: Takes actions to achieve goals
An agent can:
- Break down complex tasks into steps
- Use external tools (search, code execution, APIs)
- Make decisions based on intermediate results
- Recover from errors and try alternative approaches
The Agent Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Agent โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โ
โ โ Planner โโ โExecutor โโ โObserver โ โ
โ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โ
โ โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Tools โ
โ โโโโโโ โโโโโโ โโโโโโ โโโโโโ โโโโโโ โ
โ โWeb โ โCodeโ โFileโ โAPI โ โMailโ โ
โ โโโโโโ โโโโโโ โโโโโโ โโโโโโ โโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Components
- Planner: Breaks goals into actionable steps
- Executor: Runs tools and actions
- Observer: Evaluates results and decides next steps
- Tools: External capabilities the agent can use
Building a Simple Agent
Letโs build an agent that can research topics and summarize findings.
Step 1: Set Up Your Environment
# Install dependencies
# pip install anthropic requests beautifulsoup4
import anthropic
import requests
from bs4 import BeautifulSoup
Step 2: Define Your Tools
def search_web(query: str) -> list[dict]:
"""Search the web and return results."""
# Using a search API (you'd use your preferred search service)
# Returns list of {title, url, snippet}
pass
def fetch_page(url: str) -> str:
"""Fetch and extract text from a webpage."""
response = requests.get(url, timeout=10)
soup = BeautifulSoup(response.text, 'html.parser')
# Remove scripts and styles
for element in soup(['script', 'style', 'nav', 'footer']):
element.decompose()
return soup.get_text(separator='\n', strip=True)[:5000]
def save_file(filename: str, content: str) -> str:
"""Save content to a file."""
with open(filename, 'w') as f:
f.write(content)
return f"Saved to {filename}"
Step 3: Create the Agent Loop
def run_agent(goal: str, max_steps: int = 10):
client = anthropic.Anthropic()
tools = [
{
"name": "search_web",
"description": "Search the web for information",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"}
},
"required": ["query"]
}
},
{
"name": "fetch_page",
"description": "Fetch content from a URL",
"input_schema": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "URL to fetch"}
},
"required": ["url"]
}
},
{
"name": "save_file",
"description": "Save content to a file",
"input_schema": {
"type": "object",
"properties": {
"filename": {"type": "string"},
"content": {"type": "string"}
},
"required": ["filename", "content"]
}
}
]
messages = [{"role": "user", "content": f"Goal: {goal}"}]
for step in range(max_steps):
response = client.messages.create(
model="claude-sonnet-4-6-20250514",
max_tokens=4096,
tools=tools,
messages=messages
)
# Check if agent wants to use a tool
if response.stop_reason == "tool_use":
tool_use = next(b for b in response.content if b.type == "tool_use")
# Execute the tool
result = execute_tool(tool_use.name, tool_use.input)
# Add result to conversation
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": result
}]
})
else:
# Agent is done
return response.content[0].text
return "Max steps reached"
def execute_tool(name: str, inputs: dict) -> str:
if name == "search_web":
return str(search_web(inputs["query"]))
elif name == "fetch_page":
return fetch_page(inputs["url"])
elif name == "save_file":
return save_file(inputs["filename"], inputs["content"])
Step 4: Run Your Agent
result = run_agent(
"Research the latest developments in AI agents and "
"save a summary to 'ai_agents_summary.md'"
)
print(result)
Making Agents More Robust
Error Handling
def execute_tool_safely(name: str, inputs: dict) -> str:
try:
result = execute_tool(name, inputs)
return result
except Exception as e:
return f"Error: {str(e)}. Please try a different approach."
Memory and Context
For longer tasks, implement memory:
class AgentMemory:
def __init__(self):
self.facts = []
self.completed_steps = []
def add_fact(self, fact: str):
self.facts.append(fact)
def get_context(self) -> str:
return f"""
Known facts: {self.facts}
Completed steps: {self.completed_steps}
"""
Rate Limiting and Costs
import time
class RateLimiter:
def __init__(self, calls_per_minute: int = 20):
self.calls_per_minute = calls_per_minute
self.calls = []
def wait_if_needed(self):
now = time.time()
self.calls = [c for c in self.calls if now - c < 60]
if len(self.calls) >= self.calls_per_minute:
sleep_time = 60 - (now - self.calls[0])
time.sleep(sleep_time)
self.calls.append(now)
Common Agent Patterns
ReAct (Reason + Act)
The agent explicitly reasons before each action:
- Thought: What do I need to do?
- Action: What tool should I use?
- Observation: What was the result?
- Repeat until goal is achieved
Plan-and-Execute
- Create a full plan upfront
- Execute each step
- Revise plan if needed
Tree of Thoughts
- Generate multiple possible approaches
- Evaluate each branch
- Pursue the most promising path
Best Practices
1. Start Simple
Begin with a single tool and expand gradually.
2. Limit Scope
Agents with narrow, well-defined goals perform better than general-purpose agents.
3. Add Guardrails
- Limit iterations
- Restrict tool access
- Require confirmation for destructive actions
4. Log Everything
Youโll need detailed logs to debug agent behavior.
5. Test Extensively
Agents can behave unpredictably. Test with many scenarios.
Whatโs Next?
Once youโve built a basic agent, explore:
- Multi-agent systems: Agents that collaborate
- Tool creation: Agents that build their own tools
- Learning agents: Agents that improve over time
- Production deployment: Scaling agents reliably
The agent landscape is evolving rapidly. The patterns that work today may be replaced by better approaches tomorrow. Stay curious and keep experimenting.
Have you built an AI agent? What challenges did you face? Share your experience!