Chapter 33Tool Use: Giving Agents Hands
Tools are how an agent reaches out and affects the world — the hands attached to the model's brain. Chapter 29 introduced the mechanism of tool calling; this chapter is about the craft of *building* tools well: designing them so the model uses them correctly, validating what the model sends, handling the inevitable failures, and keeping everything safe. Good tools are the difference between an agent that reliably gets things done and one that flails. We will build several real tools and cover the practices that make them dependable.
Recap: Tools Are How Agents Act
From Chapter 29: a tool is a capability you give the model, the model requests a call by producing a structured request, and your code executes it and returns the result. That last point bears repeating because it governs everything in this chapter — since you write and run the tools, their quality, safety, and reliability are entirely in your hands. This chapter is about exercising that responsibility well.
Anatomy of a Tool
A tool has four parts: a name the model uses to call it, a description telling the model what it does and when to use it, the parameters it accepts, and the function that actually runs when the tool is called. Here is a well-formed example.
tool = {
"name": "get_weather",
"description": "Get the current weather for a city. Use when the user asks "
"about current conditions or temperature in a specific place.",
"parameters": {"city": "the city name, e.g. 'Paris'"},
}
def get_weather(city): # the function that runs on a call
# ... look up and return the weather ...
return f"Currently 14C and cloudy in {city}."Writing Tools the Model Can Use Well
Here is the single most important skill in tool design: the model decides whether and how to use a tool by reading its description. A clear, specific description leads to correct use; a vague one leads to confusion and misuse. Treat the description as a message to the model, written in plain language, stating exactly what the tool does and when it applies.
# Poor description -- the model cannot tell when or how to use it:
{"name": "data", "description": "gets data", "parameters": {"q": "query"}}
# Good description -- specific about purpose, timing, and inputs:
{"name": "search_orders",
"description": "Look up a customer's orders by their email address. Use when the "
"user asks about order status, history, or tracking.",
"parameters": {"email": "the customer's email address"}}Common Kinds of Tools
Agents draw on a few broad categories of tools, and most real agents combine several.
- Information tools — fetch knowledge the model lacks: web search, or retrieval over your own documents. In fact, the RAG system of Chapter 36 is most naturally exposed to an agent as a tool it can choose to call.
- Computation tools — do things the model is bad at, like exact arithmetic (a calculator) or running code.
- Data-access tools — read from databases, spreadsheets, or external APIs.
- Action tools — change the world: send an email, create a file, book an appointment. These are the most powerful and the most dangerous.
Building a Few Tools
Let us build a small toolbox and register it with an agent. Each tool is just a function plus a description.
from datetime import datetime
def calculator(expression):
return eval(expression) # use a safe evaluator in real code
def clock():
return datetime.now().strftime("%Y-%m-%d %H:%M")
def fetch_page(url):
# ... fetch and return the text of a web page ...
return get_text_from(url)
# Register them so the agent knows what is available.
toolbox = {
"calculator": calculator,
"clock": clock,
"fetch_page": fetch_page,
}Validating Tool Inputs
Never run a tool on the model's arguments without checking them first. The model can produce wrong, malformed, or even unsafe inputs, and your tool is the gatekeeper (Chapter 29). Validate before you execute, and reject anything that does not pass.
def fetch_page(url):
if not url.startswith("https://"): # validate before acting
return "Error: only https URLs are allowed."
if is_blocked(url):
return "Error: that address is not permitted."
return get_text_from(url)Handling Tool Errors
Tools fail — bad input, a network glitch, a missing record. The key insight is that a tool should return a useful error rather than crash, so the agent can read it as an Observation and adapt (recall ReAct, Chapter 32). A well-behaved tool turns a failure into information the agent can act on.
def safe_run(tool_fn, args):
try:
return tool_fn(**args)
except Exception as error:
# Return the error TO THE AGENT so it can try a different approach.
return f"Tool error: {error}"Because the error comes back as an observation, a good agent can respond intelligently — fixing its arguments, trying a different tool, or telling the user it could not complete the step. The agent recovers instead of collapsing.
How the Agent Chooses a Tool
When the agent reasons, it looks at the goal and the descriptions of the available tools, and selects the one whose description best matches what it needs. This is why descriptions matter so much, and it also implies a subtler lesson: too many tools can confuse the model. A focused toolbox of clearly-described tools leads to better choices than a sprawling one where several tools sound similar. When in doubt, keep the toolset small and sharp.
Tools That Return Too Much
Remember that a tool's output goes straight into the context window (Chapter 12). A tool that returns an enormous web page or a huge database dump can swamp the agent's limited context, crowding out everything else and driving up cost. Design tools to return just what is useful — summarize, truncate, or extract the relevant part before handing it back. A tool that floods the context is nearly as bad as one that fails.
Security Considerations
Tools are where an agent touches the real world, which makes them the main risk surface. An action tool that can send money, delete files, or email people carries real danger if misused. Three principles keep this in check: grant each tool the least privilege it needs and no more; validate every input; and require confirmation for dangerous or irreversible actions rather than letting the agent perform them unsupervised. We devote Chapter 45 to agent safety; for now, treat every powerful tool as something to wrap in caution.
Summary
Tools are the hands of an agent, and since you build and run them, their quality is your responsibility. A tool has a name, a description, parameters, and a function — and the description matters most, because the model reads it to decide when and how to use the tool, so clarity here directly improves reliability. Tools fall into information, computation, data-access, and action categories; you should validate every input before executing, return useful errors instead of crashing so the agent can adapt, keep the toolset focused so the model chooses well, and avoid flooding the context with oversized outputs. Above all, guard powerful tools carefully, because they are where an agent's actions can do real harm.
Tools let an agent act, but to act coherently over many steps it must remember what it has done. Chapter 34 builds the agent's memory — short-term, long-term, and episodic.
Exercises
- 1Write three tools — a calculator, a clock, and a web-fetch tool — each with a clear name, description, and parameters, and register them in a toolbox dictionary.
- 2Take a vague tool description and rewrite it to be clear and specific. Explain how the better description would change when and how the model uses the tool.
- 3Add input validation to your web-fetch tool so it rejects anything that is not an https URL, and returns a useful error message instead of crashing.
- 4Wrap a tool so that when it fails, it returns the error to the agent as text rather than raising an exception. Explain why this lets the agent recover.
- 5Explain how an agent decides which tool to call, and why having too many similar tools can hurt rather than help.
- 6Identify a tool that could take a dangerous or irreversible action, and describe the specific guardrails (least privilege, validation, confirmation) you would put around it.
