Sub topic 6
Designing tools a model can use well
This chapter assumes you have read the chapter on tool calling. You should know that the model emits a tool name and JSON arguments, and that your code runs the function and returns the result. Here the focus is the tool itself: its name, description, schema, output, and errors. These are the only things the model sees, so they decide whether it picks the right tool and uses it correctly.
The model only sees the interface
A model cannot read your function body. It sees three things: a name, a description, and an argument schema. After a call, it also sees whatever text you return. Treat these four as documentation written for a reader with no other context. A new colleague who saw only this interface should be able to use the tool correctly.
Most tool failures fall into a few groups:
| Symptom | Usual cause |
|---|---|
| Model never calls the tool | The description does not say when to use it |
| Model calls the wrong tool | Two tools have overlapping names or descriptions |
| Model passes bad arguments | Vague schema, missing enums, undocumented formats |
| Model loops on the same call | Error text gives no hint about what to change |
| Model forgets earlier facts | Tool output is huge and fills the context window |
Names and descriptions
Use a verb and an object, such as search_orders or create_ticket. Avoid names like handle, process, or data_tool. Keep names distinct enough that no two could plausibly do the same job.
A good description answers four questions:
- What does the tool do?
- When should the model use it, and when should it not?
- What does each argument mean, including units and formats?
- What does the result look like?
Compare "Looks up orders" with "Search a customer's orders by status. Use this when the user asks about an existing order. Do not use it to create or cancel orders. Returns at most limit orders, newest first." The second version costs more tokens, but it prevents most wrong calls.
Argument schemas
Describe arguments with JSON Schema. Constrain them as tightly as the domain allows:
- Use
enumfor closed sets such as status values. - Give every property a
descriptionwith an example value. - Mark only truly necessary properties as
required, and give the rest defaults in your code. - Set
additionalPropertiestofalseso invented arguments are rejected instead of ignored. - Prefer a few flat arguments over deeply nested objects, which models fill in less reliably.
Schemas steer the model, but they do not guarantee valid input. Some providers enforce them and some do not. Always validate in your own code before running anything.
A complete example
The following code defines one tool with a schema, a small validator, and a run_tool that returns errors the model can act on. It extends the run_tool pattern from the agent loop chapter.
import json
ORDERS = [
{"id": "A100", "customer_id": "c1", "status": "open", "total": 40.0},
{"id": "A101", "customer_id": "c1", "status": "shipped", "total": 15.5},
{"id": "A102", "customer_id": "c1", "status": "open", "total": 22.0},
{"id": "A103", "customer_id": "c2", "status": "open", "total": 99.0},
]
def search_orders(customer_id: str, status: str = "open", limit: int = 2) -> str:
rows = [
o for o in ORDERS
if o["customer_id"] == customer_id and (status == "any" or o["status"] == status)
]
shown = rows[:limit]
return json.dumps({
"orders": shown,
"returned": len(shown),
"total_matches": len(rows),
"truncated": len(rows) > limit,
})
SPECS = {
"search_orders": {
"name": "search_orders",
"description": (
"Search one customer's orders by status. Use when the user asks about "
"existing orders. Does not create or cancel orders. Returns at most "
"'limit' orders and reports whether results were truncated."
),
"parameters": {
"type": "object",
"properties": {
"customer_id": {"type": "string", "description": "Customer ID, e.g. 'c1'."},
"status": {
"type": "string",
"enum": ["open", "shipped", "any"],
"description": "Order status filter. Use 'any' for all statuses.",
},
"limit": {"type": "integer", "description": "Maximum orders to return, e.g. 5."},
},
"required": ["customer_id"],
"additionalProperties": False,
},
}
}
FUNCTIONS = {"search_orders": search_orders}
TYPES = {"string": str, "integer": int, "boolean": bool}
def validate(spec: dict, arguments: dict):
schema = spec["parameters"]
props = schema["properties"]
for key in schema.get("required", []):
if key not in arguments:
return f"missing required argument '{key}'"
for key, value in arguments.items():
if key not in props:
return f"unknown argument '{key}'. Allowed: {sorted(props)}"
rule = props[key]
expected = TYPES[rule["type"]]
if not isinstance(value, expected) or (rule["type"] != "boolean" and isinstance(value, bool)):
return f"argument '{key}' must be of type {rule['type']}"
if "enum" in rule and value not in rule["enum"]:
return f"argument '{key}' must be one of {rule['enum']}"
return None
def run_tool(name: str, arguments: dict) -> str:
if name not in SPECS:
return json.dumps({"error": f"unknown tool: {name}", "available": sorted(SPECS)})
problem = validate(SPECS[name], arguments)
if problem:
return json.dumps({"error": problem, "hint": "Fix the arguments and call again."})
try:
return FUNCTIONS[name](**arguments)
except Exception as exc:
return json.dumps({"error": f"tool failed: {exc}"})
print(run_tool("search_orders", {"customer_id": "c1"}))
print(run_tool("search_orders", {"customer_id": "c1", "status": "late"}))
print(run_tool("search_orders", {"customer": "c1"}))The first call returns two orders and "truncated": true. The second and third return errors that name the exact problem and the allowed values. A model that reads those errors can correct itself on the next step.
Designing results
The result is part of the prompt for the next step, so shape it deliberately.
- Return what the model needs, not everything you have. Drop internal IDs, audit fields, and raw HTML. Every extra field costs tokens and gives the model something to misread.
- Cap the size. Use a
limitargument with a small default. Reporttotal_matchesandtruncatedso the model knows more exists and can narrow its query instead of assuming it saw everything. - Use stable, readable keys. Names like
statuswork better thanst. Use the same names across tools. - Say so when nothing matches. An empty list with a message such as "no open orders for c1" is clearer than an empty string, which the model may read as a failure.
Designing errors
Errors are a form of instruction. A message like KeyError: 'id' helps no one. A message like "unknown argument 'customer'. Allowed: ['customer_id', 'limit', 'status']" lets the model fix the call in one step. Good error text names the problem, states the valid options, and distinguishes mistakes the model can fix from failures it cannot, such as a service outage. Retry limits and stop conditions are covered in a later chapter.
Scope and granularity
Two opposite mistakes are common. A tool with a mode argument that switches between unrelated behaviors is hard to describe, so split it. A set of tiny tools that must be chained in a fixed order wastes steps and invites mistakes, so merge them into one operation that matches the user's task. Keep the total number of tools modest. Accuracy in choosing among tools usually drops as the list grows into the dozens.
Mark the difference between read and write tools. Reading is safe to retry. Writing is not, so make write tools idempotent where possible, for example by accepting a request ID that prevents a duplicate charge. The guardrails chapter covers approval for risky actions.
Common mistakes
- Overlapping tools such as
search_docsandfind_documentswith near-identical descriptions. - Returning whole database rows or full web pages.
- Raising raw exceptions that crash the loop instead of returning text.
- Optional arguments with hidden behavior, such as a default that silently filters results.
- Putting rules for when to use a tool in the system prompt and leaving the description empty. Keep tool guidance next to the tool.
Exercise
A tool get_data(source, query, mode) has mode values "read", "delete", and "export", and returns the full result set as JSON. The model often deletes records when the user only asked to look. Name three design changes that address this.
Show answer
First, split the tool into separate tools such as search_records, export_records, and delete_records, so each has one clear description and the model cannot trigger deletion by choosing a mode value. Second, put the delete tool behind a permission check and human approval, enforced in code and not only in the prompt. Third, cap and trim the output with a limit argument and a truncated flag so large results do not fill the context window.