Giving Agents Tools

Updated · 5 min read
hardPython 3.13aiagentstool-usepythondesign

An agent tool is a function your code exposes to a model, with a name, a description and an input schema. Tools are how agents get information and take action, so the quality of an agent depends heavily on the quality of its tools: what they do, how clearly they are described, and how they behave when something goes wrong.

What Makes a Good Tool

Clear tools, helpful errors, least privilege
PrincipleDescription
One clear jobIt is used to keep each tool simple, such as look_up_fee, not do_school_stuff
A description like instructionsIt is used to tell the model what the tool does, when to use it and what inputs mean
Strict inputsIt is used to reject wrong types and missing fields before anything runs
Helpful errorsIt is used to tell the model what went wrong and what to try next
Least privilegeIt is used to give each tool only the access it needs, such as read-only data

Example: A Safe Tool Dispatcher

Python
FEES = {(10, "lab"): 45, (10, "field trip"): 30, (11, "lab"): 50}
EXAMS = {"math": "December 9", "science": "December 11"}
 
def look_up_fee(grade, item):
    return f"${FEES[(grade, item.lower())]}"
 
def next_exam(subject):
    return EXAMS[subject.lower()]
 
TYPE_NAMES = {int: "a whole number", str: "text"}
# name: (function, {input: type}, kind); "read" tools only look things up
REGISTRY = {
    "look_up_fee": (look_up_fee, {"grade": int, "item": str}, "read"),
    "next_exam": (next_exam, {"subject": str}, "read"),
}
 
def execute(name, args):
    """Run a tool safely and always return a result the model can read."""
    if name not in REGISTRY:
        return {"is_error": True, "content": f"Unknown tool '{name}'. Available: {', '.join(REGISTRY)}."}
    function, inputs, kind = REGISTRY[name]
    for field, kind_of in inputs.items():
        if not isinstance(args.get(field), kind_of):
            return {"is_error": True, "content": f"'{field}' must be {TYPE_NAMES[kind_of]}."}
    try:
        return {"is_error": False, "content": function(**args)}
    except KeyError:
        return {"is_error": True, "content": f"No record found for {args}. Ask the person to check the details."}
 
for name, args in [("look_up_fee", {"grade": 10, "item": "Lab"}),
                   ("look_up_fee", {"grade": "ten", "item": "lab"}),
                   ("next_exam", {"subject": "Art"}),
                   ("delete_fees", {})]:
    print(f"{name} {args}\n  -> {execute(name, args)}")
Output
look_up_fee {'grade': 10, 'item': 'Lab'}
  -> {'is_error': False, 'content': '$45'}
look_up_fee {'grade': 'ten', 'item': 'lab'}
  -> {'is_error': True, 'content': "'grade' must be a whole number."}
next_exam {'subject': 'Art'}
  -> {'is_error': True, 'content': "No record found for {'subject': 'Art'}. Ask the person to check the details."}
delete_fees {}
  -> {'is_error': True, 'content': "Unknown tool 'delete_fees'. Available: look_up_fee, next_exam."}

Explanation: REGISTRY lists every tool with its function, expected input types and kind. execute() refuses unknown tools, checks each input's type, and turns a missing record into a clear message instead of a crash. Every result has is_error, which maps directly to the is_error flag on a tool_result, so the model knows to fix its request or tell the person.

Read Tools and Write Tools

KindExamplesRule
ReadLook up a fee, search documents, check a calendarUsually safe to allow
WriteBook a meeting, send an email, update a recordConfirm with a person first
IrreversiblePayments, refunds, deletionsAvoid giving to agents, or require strict approval

Common Mistakes

Vague descriptions. "Gets data" tells the model nothing; say what, when and how.

Crashing on bad input. Validate and return an error result the model can act on.

One powerful tool for everything. Split it into small tools with narrow permissions.

Interview Corner

What makes a well-designed agent tool?

One clear job, a precise description, strict input validation, helpful error messages, and the minimum permissions needed.

Why return errors to the model instead of raising them?

So the model can recover: retry with corrected inputs, try another approach, or explain the problem to the person, instead of the whole agent failing.

Practice

Exercise: add a tool. Add school_hours(day) to the registry, returning opening hours for each weekday. Test it with "Monday", "monday", 5 and "Holiday", and make every error message tell the model what to do next.

Check your understanding:

  1. Why does a tool need a precise description?
  2. What should happen when inputs have the wrong type?
  3. Which tools need a person's confirmation?

Quick check: giving agents tools

4 questions
1What did execute() return for grade "ten"?
2What does least privilege mean for tools?
3Which kind of tool should require confirmation?
4Why is "Unknown tool 'delete_fees'. Available: ..." a good error?

Key Takeaways

Quick reference

NeedApproach
Unknown toolError listing the available tools
Bad inputError naming the field and expected type
Missing recordError suggesting what to check
Write actionConfirmation before running

Was this tutorial helpful?

Lesson 104 of 186