LLM Agents
Tool-using agents, planning, and multi-step reasoning
Skills taught: llms.agents
What is an AI Agent?
An agent is an LLM that iteratively calls tools, reasons about results, and decides what to do next until a goal is achieved. Unlike a single API call, agents can take sequences of actions — search, compute, write — and adapt based on what they find.
- Agentic Loop
- The while loop that drives an agent: send messages + tools → if model requests tools, execute them and append results → repeat until model returns end_turn without tool calls.
- ReAct Pattern
- Reason-Act-Observe: at each step, the model reasons (Thought), takes an action (tool call), and observes the result. This structure makes agent reasoning transparent and debuggable.
import anthropic
import json
client = anthropic.Anthropic()
# Define tools the agent can use
tools = [
{
"name": "web_search",
"description": "Search the web for current information. Use for facts, news, prices.",
"input_schema": {"type": "object", "properties": {
"query": {"type": "string", "description": "Search query"}
}, "required": ["query"]}
},
{
"name": "calculator",
"description": "Evaluate a mathematical expression. Input must be a Python expression string.",
"input_schema": {"type": "object", "properties": {
"expression": {"type": "string", "description": "e.g. '2 ** 10 + 3 * 7'"}
}, "required": ["expression"]}
}
]
def execute_tool(name: str, input_data: dict) -> str:
"""Execute a tool and return the result as a string."""
if name == "web_search":
return f"[Search results for '{input_data['query']}': Revenue grew 18% YoY to $2.4M]" # stub
elif name == "calculator":
try:
return str(eval(input_data["expression"], {"__builtins__": {}}))
except Exception as e:
return f"Error: {e}"
return "Tool not found"
def run_agent(goal: str, max_iterations: int = 10) -> str:
messages = [{"role": "user", "content": goal}]
for iteration in range(max_iterations):
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=4096,
tools=tools,
messages=messages
)
if response.stop_reason == "end_turn":
# Agent is done — extract final text
return next((b.text for b in response.content if hasattr(b, "text")), "")
# Execute all tool calls in this response
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result
})
# Append assistant response + tool results to messages
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
return "Max iterations reached"
result = run_agent("What is 18% of Acme Corp's Q3 revenue if they had $2.4M total revenue?")
print(result)
Multi-Agent Architecture
For complex tasks, an orchestrator agent decomposes the goal and delegates to specialist subagents. The orchestrator manages the overall plan; subagents execute specific subtasks in parallel or sequence.
import anthropic
client = anthropic.Anthropic()
# Specialist subagents (each is a focused agent with limited tools)
def researcher_agent(topic: str) -> str:
"""Searches and summarises information on a topic."""
response = client.messages.create(
model="claude-haiku-5-5",
max_tokens=1024,
system="You are a research assistant. Search thoroughly and report key facts.",
messages=[{"role": "user", "content": f"Research: {topic}"}]
)
return response.content[0].text
def writer_agent(outline: str, research: str) -> str:
"""Writes a document section from an outline and research notes."""
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=2048,
system="You are a professional writer. Use the research to write the section.",
messages=[{"role": "user", "content": f"Outline: {outline}\n\nResearch: {research}"}]
)
return response.content[0].text
# Orchestrator coordinates the pipeline
def orchestrate_report(topic: str) -> str:
# Step 1: Research
research = researcher_agent(topic)
# Step 2: Write based on research
outline = f"Introduction, Key Findings, Implications for {topic}"
report = writer_agent(outline, research)
return report
print(orchestrate_report("the impact of AI on software engineering jobs"))
Tip: Always add a max_iterations limit to agent loops. Without it, a confused agent can loop indefinitely and generate thousands of dollars in API costs. Log every iteration for debugging.
Warning: Agents with write access (send email, delete files, deploy code) can cause irreversible damage if they make wrong decisions. Add human-in-the-loop confirmation for all destructive or external-facing actions.
Frequently Asked Questions
What frameworks exist for building agents?
LangChain, LlamaIndex, and Anthropic's own Claude agent SDK. For simple agents, a plain while loop is often clearer and easier to debug than a framework. Use frameworks for multi-agent orchestration and complex memory management.
How do agents handle memory between sessions?
Agents have no built-in memory. Options: (1) in-context — summarise conversation history and prepend to next session; (2) key-value store — save important facts to Redis/DynamoDB; (3) vector memory — embed past interactions for semantic retrieval.
What is a 'computer use' agent?
Anthropic's computer use API lets Claude control a desktop computer — take screenshots, move the mouse, type, and interact with any application. This enables agents that can automate GUI tasks without an API.