Building Agents
The grand finale — design, configure, and build a real AI agent with working code
What Is an AI Agent?
An AI agent is Claude given a goal, tools, memory, and guardrails — then set free to accomplish complex tasks autonomously. Unlike simple prompting (one question, one answer), agents can plan multi-step workflows, execute actions, observe results, adapt their approach, and even ask for help when stuck.
You have already learned all the components. System prompts define the agent's identity. Chain-of-thought enables its reasoning. Tools give it hands. Now it is time to assemble them into something powerful.
The Four Components of an Agent
A clear objective, defined in the system prompt. "Research the top 5 competitors and produce a comparison table." "Monitor this API endpoint every hour and alert if response time exceeds 500ms." The goal shapes every decision the agent makes.
The set of actions available to the agent: web search, file read/write, database queries, API calls, email sending. More tools = more capable agent, but also more surface area for errors. Start minimal and add tools as needed.
Conversation memory: The messages array — ephemeral, lost when the conversation ends. Persistent memory: Database-backed storage that survives across sessions. RAG memory: Vector search over documents for retrieval (see the RAG course).
Safety boundaries: max steps (prevent infinite loops), budget caps (prevent runaway API costs), human approval gates (for destructive actions like deleting data or sending emails), scope locks (prevent the agent from drifting to unrelated tasks).
Building an Agent from Scratch
Here is a complete, working agent that can research topics using web search and produce structured reports. This code runs as-is with the Anthropic SDK:
import anthropic, json
client = anthropic.Anthropic()
# Agent system prompt — defines identity, goal, and guardrails
AGENT_SYSTEM = (
"You are a research agent. Your goal is to research topics "
"thoroughly and produce structured reports.\n\n"
"Process:\n"
"1. Break the research question into sub-questions\n"
"2. Use search to find information for each sub-question\n"
"3. Synthesize findings into a structured report\n\n"
"Rules:\n"
"- Always cite your sources\n"
"- If you cannot find reliable information, say so\n"
"- Produce the final report in markdown format"
)
# Agent tools
TOOLS = [
{
"name": "web_search",
"description": "Search the web for current information.",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"}
},
"required": ["query"]
}
},
{
"name": "save_report",
"description": "Save the final research report to a file.",
"input_schema": {
"type": "object",
"properties": {
"filename": {"type": "string"},
"content": {"type": "string"}
},
"required": ["filename", "content"]
}
}
]
def execute_tool(name: str, params: dict) -> str:
if name == "web_search":
# Replace with real search API (Brave, Tavily, etc.)
return json.dumps({"results": ["Example search result..."]})
elif name == "save_report":
with open(params["filename"], "w") as f:
f.write(params["content"])
return f"Saved to {params['filename']}"
raise ValueError(f"Unknown tool: {name}")
def run_agent(task: str, max_steps: int = 15) -> str:
"""Run the research agent until it completes the task."""
messages = [{"role": "user", "content": task}]
for step in range(max_steps):
print(f"Step {step + 1}...")
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=4096,
system=AGENT_SYSTEM,
tools=TOOLS,
messages=messages
)
# If done, return the final text
if response.stop_reason == "end_turn":
return response.content[0].text
# Process tool calls
messages.append({"role": "assistant", "content": response.content})
tool_results = []
for block in response.content:
if block.type == "tool_use":
print(f" Calling {block.name}({block.input})")
try:
result = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result
})
except Exception as e:
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": f"Error: {e}",
"is_error": True
})
messages.append({"role": "user", "content": tool_results})
return "Agent reached max steps."
# Run it
report = run_agent("Research the current state of AI agents in 2026.")
print(report)
This lesson is for Pro members
Unlock all 520+ lessons across 52 courses with Academy Pro.
Already a member? Sign in to access your lessons.