Build Your First AI Agent
Go from chatbot to autonomous AI—agents that decide, act, and learn
Published July 1, 2026
•
15 min read
Difference: Chatbots respond to prompts. Agents act autonomously: they decide what to do, use tools, remember context, and iterate until solving problems.
What Makes an AI Agent?
An agent has three core components:
- Reasoning: "What should I do?" — Plan based on goal
- Tool Use: "How do I do it?" — Call APIs, search, calculate
- Memory: "What happened?" — Remember context across steps
Agent Loop Explained
1. User: "Find me the best Python books and their prices"
2. Agent thinks: "I need to search for books and check prices"
3. Agent uses tools: search_books(), check_amazon_price()
4. Agent reasons: "These are the top 3 by rating"
5. Agent responds: "Here are the books and prices..."
Simple Example: Weather Agent
Let's build an agent that finds weather and book recommendations:
import anthropic
import json
# Initialize Claude with tool use
client = anthropic.Anthropic()
tools = [
{
"name": "get_weather",
"description": "Gets current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
}
},
"required": ["city"]
}
},
{
"name": "get_books",
"description": "Searches for books on a topic",
"input_schema": {
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "Book topic"
}
},
"required": ["topic"]
}
}
]
def get_weather(city):
# Mock API call
return {"temperature": 72, "condition": "Sunny", "humidity": 60}
def get_books(topic):
# Mock search
return [
{"title": "The Pragmatic Programmer", "topic": "programming"},
{"title": "Python Crash Course", "topic": "python"}
]
def process_tool_call(tool_name, tool_input):
if tool_name == "get_weather":
return get_weather(tool_input["city"])
elif tool_name == "get_books":
return get_books(tool_input["topic"])
# Agent loop
def run_agent(user_message):
print(f"User: {user_message}\n")
messages = [{"role": "user", "content": user_message}]
while True:
# Ask Claude what to do
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=tools,
messages=messages
)
# Check if Claude wants to use tools
if response.stop_reason == "tool_use":
# Claude used tools
for block in response.content:
if block.type == "tool_use":
tool_name = block.name
tool_input = block.input
print(f"Agent: Using tool {tool_name} with {tool_input}")
# Call the tool
result = process_tool_call(tool_name, tool_input)
# Add to conversation
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result)
}]
})
else:
# Claude finished reasoning
for block in response.content:
if hasattr(block, "text"):
print(f"Agent: {block.text}")
break
# Run it!
run_agent("What's the weather in San Francisco and recommend a Python book?")
Agent Patterns
1. ReAct (Reasoning + Acting)
Thought: I need to search for this information
Action: search_google("Python performance tips")
Observation: Found 5 relevant articles
Thought: Now I should summarize this
Final Answer: Here are the tips...
2. Chain of Thought
Agent breaks complex problems into steps and solves sequentially.
3. Multi-Agent Systems
Multiple agents coordinate: one researches, one analyzes, one synthesizes.
Key Challenges
- Hallucinations: Agent makes up tool calls or facts. Use clear tool schemas.
- Infinite loops: Agent gets stuck repeating same action. Add max iterations.
- Tool errors: API fails, agent panics. Handle errors gracefully.
- Cost escalation: Agent makes 100 API calls instead of 5. Monitor carefully.
Safety: Constraining Agent Actions
ALLOWED_TOOLS = ["search", "calculator", "weather"]
def run_agent_safely(user_message):
# Only allow specific tools
available_tools = [t for t in ALL_TOOLS if t["name"] in ALLOWED_TOOLS]
# Set iteration limit
max_iterations = 10
iterations = 0
while iterations < max_iterations:
# ... rest of loop
iterations += 1
if iterations == max_iterations:
return "Agent reached max iterations. Stopping."
Real-World Example: Research Agent
An agent that researches market trends:
- Search for recent news on topic
- Fetch articles and extract key data
- Analyze sentiment and trends
- Generate summary report
Tools available:
search_news()- Find recent articlesfetch_article(url)- Get full textanalyze_sentiment(text)- Extract opiniongenerate_report(data)- Format findings
Testing Your Agent
def test_agent():
test_cases = [
("Simple query", "What's 2+2?"),
("Multi-step", "Find weather in NYC and recommend restaurants"),
("Error case", "Get weather for planet Mars"), # Should handle gracefully
]
for name, query in test_cases:
print(f"\nTest: {name}")
try:
result = run_agent(query)
print(f"Result: {result}")
except Exception as e:
print(f"Error: {e}")
Deployment Considerations
- Monitor cost: agents can be expensive if not constrained
- Add timeouts: prevent hanging on API calls
- Implement retry logic: handle transient failures
- Log all actions: debug and audit trail
- Rate limit: prevent abuse
Master AI Agents
Build production agents with reasoning, memory, and multi-step workflows.
Start AI Agents Course →