5. Agent AI
An agent is a program that calls an LLM in a loop, giving the model access to
tools (functions it can invoke), and continuing until the model decides
it has finished. This chapter covers the tool-use pattern, the agentic loop,
a working file-reading agent, and safety constraints.
Why agents instead of single calls?
- A single call cannot react to its own output. An agent can read a file,
see what’s in it, and decide what to read next.
- Tool use turns the model into an orchestrator: it plans, delegates to
tools, and synthesizes results — all without your intervention.
- Agents can retry failed steps, ask clarifying questions, and handle
unexpected inputs gracefully.
5.1 Defining a Tool
tools = [{
"name": "read_file",
"description": "Read a source file and return its contents as a string.",
"input_schema": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Relative path to the file"}
},
"required": ["path"]
}
}]
5.2 The Tool Loop
import anthropic, pathlib
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Summarize the file main.py."}]
while True:
resp = client.messages.create(
model="claude-sonnet-4-6", max_tokens=2048,
tools=tools, messages=messages
)
if resp.stop_reason == "end_turn":
print(resp.content[0].text)
break
for block in resp.content:
if block.type == "tool_use":
text = pathlib.Path(block.input["path"]).read_text()
messages += [
{"role": "assistant", "content": resp.content},
{"role": "user", "content": [{
"type": "tool_result",
"tool_use_id": block.id,
"content": text
}]}
]
5.3 Safety Constraints
An unconstrained agent can do more than intended. Useful guards:
- Cap iterations:
for _ in range(MAX_STEPS) — raise an error if exceeded
- Whitelist allowed paths: reject tool calls outside the sandbox directory
- Separate read tools from write tools and require explicit user confirmation
before any write tool runs
- Log every tool call and its result to a file for post-session review
5.4 References
| Resource | Description |
|
Tool Use Docs
|
Anthropic’s guide to defining and using tools with the Claude API. |
| CodeBites: Agent AI |
Track page with agent demos and design notes. |