Learn/Agentic AI/Building Your First Agent
Agentic AI

Building Your First Agent

The best way to understand agents is to build one. This walkthrough uses the Anthropic API directly — no framework — so you can see exactly what happens at each step.

Building Your First Agent

This walkthrough uses the Anthropic API directly — no framework — so you see exactly what happens at each step.

What You'll Build

A simple research agent with two tools: web_search(query) and read_page(url). Give it a question; it searches, reads, and synthesizes an answer.

Step 1: Define Tools as JSON Schema

python tools = [ { "name": "web_search", "description": "Search the web for current information. Returns titles, URLs, and snippets.", "input_schema": { "type": "object", "properties": { "query": {"type": "string", "description": "The search query"} }, "required": ["query"] } } ]

Step 2: The Agent Loop

```python import anthropic client = anthropic.Anthropic()

def run_agent(question: str) -> str: messages = [{"role": "user", "content": question}] for i in range(10): # max 10 iterations response = client.messages.create( model="claude-opus-4-5", max_tokens=4096, tools=tools, messages=messages ) if response.stop_reason == "end_turn": return next(b.text for b in response.content if b.type == "text") # Handle tool calls messages.append({"role": "assistant", "content": response.content}) results = [] for block in response.content: if block.type == "tool_use": result = execute_tool(block.name, block.input) results.append({ "type": "tool_result", "tool_use_id": block.id, "content": result }) messages.append({"role": "user", "content": results}) return "Max iterations reached." ```

Key Tips

  • Start with 2-3 tools max — more tools means more wrong choices
  • Log everything — tool name, inputs, truncated results at every step
  • Cap iterations — always set a MAX_ITERATIONS guard
  • Validate arguments — check required fields before executing
  • Test simple cases first — verify each tool in isolation before complex tasks

Have a follow-up question about this topic?

Ask AI