Tools the Agent Can Use Well

An agent can only be as good as the tools it is given. The model never sees your functions, only their names, their descriptions and what they send back, so the way you define, describe and shape those tools decides which tool the model picks, whether it calls it correctly, and whether a run that hits a mistake can carry on. This page explains how to give an agent several tools through one table, how to write and size them so the model chooses well, and how to turn a failed call into something the model can fix.

One table for every tool

Recall the agent loop: the program calls the model, runs every tool call the reply asks for, sends the results back, and repeats until the model answers without asking for a tool. With one tool, the loop can call that function directly. With several, it needs a way to go from the name the model writes in its tool call to the function that does the work, without a growing chain of if name == ... branches inside the loop.

The answer is a tool registry: one dictionary that maps each tool name to everything the program knows about that tool. Here each entry holds three things: the Python function, a description, and a Pydantic class that describes the arguments. The JSON schema sent to the language model is generated from that class. Later, when a tool call comes back, the same class checks the arguments the language model wrote.

A registry with one entry, and the two functions the loop uses
from pydantic import BaseModel, Field


class GetOrderArgs(BaseModel):
    order_id: str = Field(description="The order id, for example ORD-1042.")


def get_order(order_id: str) -> str:
    ...  # look the order up and return a short text about it


TOOLS = {
    "get_order": {
        "function": get_order,
        "args": GetOrderArgs,
        "description": "Returns the status, items and delivery date of one order.",
    },
    # "search_help", "get_help_page", "find_orders": ...
}


def tool_definitions() -> list[dict]:
    return [
        {
            "type": "function",
            "function": {
                "name": name,
                "description": tool["description"],
                "parameters": tool["args"].model_json_schema(),
            },
        }
        for name, tool in TOOLS.items()
    ]


def run_tool(name: str, arguments: str) -> str:
    tool = TOOLS[name]
    args = tool["args"].model_validate_json(arguments)
    return tool["function"](**args.model_dump())

Two things come out of the table. tool_definitions() builds the tools list sent with every Chat Completions request, in the shape that API expects: each tool is {"type": "function", "function": {name, description, parameters}}. run_tool() takes a tool call from the reply and runs it. The arguments of a tool call arrive as a JSON string, not a dictionary, so model_validate_json parses and checks them in one step.

The loop itself now knows nothing about orders or help pages. For each call in message.tool_calls it passes call.function.name and call.function.arguments to run_tool(), then appends {"role": "tool", "tool_call_id": call.id, "content": result} to the transcript. Adding a tool means adding one entry to the table; the loop does not change.

  • model
  • program: run_tool()
  • search_help
  • get_help_page
  • find_orders
  • get_order
  • tool call
  • result

True or false?

The arguments of a tool call reach your code as a ready Python dictionary.

False. They arrive as a JSON string written by the model. Your code parses it, and the string may not even be valid JSON.

With a registry, adding one more tool means adding an entry to the table, not editing the loop.

True. The loop looks the name up in the table and runs whatever function it finds there, so it never names a tool itself.

Descriptions are instructions

When the model decides what to do next, the tool definitions are part of its input: they are placed in the context next to the system prompt and the messages. The tool name, the tool description and the description of each parameter are the only things it knows about a tool. The Chat Completions reference says the description is used by the model to choose when and how to call the function. So these few lines are not documentation for a colleague; they are instructions to the model, and they deserve the care you give a prompt.

Compare two definitions of the same function. The left one is correct as code and still leaves the model guessing: what kind of id, which format, what comes back, and when it should search instead.

The model has to guess
{
  "name": "order",
  "description": "Gets an order.",
  "parameters": {
    "type": "object",
    "properties": {
      "id": { "type": "string" }
    },
    "required": ["id"]
  }
}
The model knows when and how
{
  "name": "get_order",
  "description": "Returns the status, items and delivery date of one order. Use it when you already know the order id. If you only have the customer's email, call find_orders first. It does not change the order.",
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string",
        "description": "The order id, for example ORD-1042."
      }
    },
    "required": ["order_id"]
  }
}

The right one says four things the model needs: what the tool does, when to use it and when to use another tool instead, what the parameter means with an example of its format, and what the result contains. A useful test, suggested in OpenAI's function calling guide: could a new colleague use the tool correctly given nothing but this text? If they would ask you a question first, put the answer in the description.

A few habits follow from treating the text as a prompt:

  • Names that say what they do. get_order and order_id leave less room for a wrong guess than order and id.
  • Boundaries between tools. When two tools look alike, each description says which one to use when.
  • Arguments that are hard to get wrong. An enum of allowed values beats a free string, and an argument your code already knows (the id of the customer being served, say) is filled in by the code, not asked of the model.
  • A fix where the model trips. When runs show the same mistake again and again, a sentence in the description that addresses it is often the cheapest repair.

With Pydantic, the description of each Field becomes the parameter description in model_json_schema(), so the text lives next to the type it explains.

True or false?

Renaming a parameter from `id` to `order_id` can change how well the model calls the tool, even though the code does the same thing.

True. The model reads the name as part of its instructions. A name that says what it holds removes a guess.

A short description is better, because the model works out the details from the function body.

False. The model never sees the function body. It sees the name, the description and the schema, and nothing else.

A few tools shaped by the task

A support system may offer dozens of functions: list all orders, get a customer, list payments, list shipments, list notes, read the full help archive. It is tempting to wrap each one as a tool so the agent "can do anything". In practice this makes the agent worse, for three reasons.

  • Every definition is sent with every call. Tool definitions count against the context window and are billed as input tokens, on every step of the run, whether the model uses them or not.
  • Overlapping tools blur the choice. With list_orders, get_customer and list_shipments all able to answer "where is my parcel?", the model has to pick between near-equals, and it picks inconsistently.
  • Low-level tools mean more steps. A tool that returns every order makes the model read them all to find one, and each extra step is another chance to go wrong.

The alternative is to shape tools around the steps a person doing the task would take. To answer a customer, a support worker looks for the help page that covers the question, reads it, finds the customer's orders, and checks the one they mean. That gives a handful of tools, each with one clear purpose.

Wrapping every system function
  • Support system
  • list_orders
  • get_customer
  • list_payments
  • list_shipments
  • list_notes
  • read_all_help
Following the steps of the task
  • Answer a customer
  • search_help find the page
  • get_help_page read it
  • find_orders find their orders
  • get_order check the order

Two rules of thumb help. Functions that are always called one after the other can become one tool. A tool that would return a whole collection is usually better as a search that returns only the matching items. There is no fixed right number; OpenAI's guide calls fewer than 20 tools at a time "just a soft suggestion". The useful question for each tool is whether it stands for a step the task needs and whether its purpose is distinct from every other tool's.

True or false?

A tool the model never calls during a run costs nothing.

False. Its definition is part of the input of every model call in the run, so it takes context and input tokens each time.

Replacing a tool that lists every order with a tool that finds the orders of one customer can make the agent both cheaper and more accurate.

True. The model reads only the orders that matter, which saves context and removes a chance to pick the wrong one.

Results sized for the next step

Whatever a tool returns becomes a tool message in the transcript, and the transcript is sent again with every later call. A result that holds ten full help pages is paid for on every remaining step, and it buries the one line that matters among many that do not. So a tool result should hold what the model needs for its next decision and little else.

For a search, the next decision is "which item do I open?". That needs a short listing: an identifier and a title per match, a cap on how many come back, and a note when more exist. The full content is left to a second tool that takes one identifier.

search_help returns every page in full
[{"uuid": "9f3c1e7a-52b0-4d1e-...",
  "title": "Returns and refunds",
  "body": "If you are not happy with an item you can
   return it within 30 days of delivery. To start a
   return, open your account and ... (1,800 words)",
  "created_at": "...", "author_id": "...", ...},
 {"uuid": "b81d...", "title": "Shipping times",
  "body": "... (2,400 words)", ...},
 ... 8 more pages ...]
search_help returns a short listing
returns-policy: Returns and refunds
refund-timing: When a refund arrives
damaged-items: Damaged or faulty items
(3 of 7 matches shown. Open one with
get_help_page, or search with more
specific words.)

The listing on the right does several things at once. Its identifiers are readable slugs, which the model copies more reliably than long random ids. The limit keeps the result small however many pages match. The last line tells the model what to do next, so a truncated result steers instead of misleading. When the model has picked a page, get_help_page("returns-policy") returns its text, and that tool can cap its own length too, ending with a note that the page was cut.

A listing with a limit, and a detail tool with a cap
MAX_RESULTS = 3
MAX_PAGE_CHARS = 4000


def search_help(query: str) -> str:
    matches = [page for page in PAGES if matches_query(page, query)]
    if not matches:
        return f"No help page matches '{query}'. Try other words."
    lines = [f"{page.slug}: {page.title}" for page in matches[:MAX_RESULTS]]
    if len(matches) > MAX_RESULTS:
        lines.append(
            f"({MAX_RESULTS} of {len(matches)} matches shown. Open one with "
            "get_help_page, or search with more specific words.)"
        )
    return "\n".join(lines)


def get_help_page(slug: str) -> str:
    page = PAGES_BY_SLUG.get(slug)
    if page is None:
        return f"No help page has the id '{slug}'. Use search_help to find ids."
    if len(page.text) > MAX_PAGE_CHARS:
        return page.text[:MAX_PAGE_CHARS] + "\n(Page cut at its length limit.)"
    return page.text

The limits here are design choices, not values any API prescribes: pick them from what a typical answer needs. Fields are chosen the same way. An internal database key, a timestamp or an author id rarely helps the model decide anything, so they are left out unless a next step uses them.

True or false?

It is safest to return everything a tool finds, because the model will ignore what it does not need.

False. Everything returned stays in the transcript and is sent again on each later call, and a long result makes the useful part harder for the model to find.

A cut-off result should say that it was cut and how to get more.

True. Without that note the model may treat a partial listing as complete. With it, the model knows to open an item or search more precisely.

Errors the model can act on

Tool calls fail, and in an agent they fail in a few predictable ways. The model may name a tool that is not in the registry. It may send arguments that are not valid JSON, that miss a required field, or that have the wrong type. The Chat Completions reference warns about this: the model does not always generate valid JSON and may invent parameters, so your code should validate the arguments. Or the call is well formed but asks for something that does not exist, such as an order id nobody has.

The plain run_tool() from the start of this page would raise an exception in the first two cases (a KeyError for the unknown name, a Pydantic ValidationError for the bad arguments), and the run would stop. Yet the model could fix each of these on its next step, if it knew what went wrong. So the program catches the failure and returns it as the tool result: a short text that says what went wrong and what to try instead. The call still gets its tool message with its tool_call_id, and the loop goes on.

run_tool that turns failures into results
from pydantic import ValidationError


def run_tool(name: str, arguments: str) -> str:
    tool = TOOLS.get(name)
    if tool is None:
        available = ", ".join(TOOLS)
        return f"Error: there is no tool named '{name}'. Available tools: {available}."
    try:
        args = tool["args"].model_validate_json(arguments)
    except ValidationError as error:
        problems = "; ".join(
            f"{'.'.join(map(str, item['loc'])) or 'arguments'}: {item['msg']}"
            for item in error.errors()
        )
        return (
            f"Error: invalid arguments for {name} ({problems}). "
            f"Call {name} again with arguments that match its parameters."
        )
    return tool["function"](**args.model_dump())

The third case, an item that does not exist, belongs in the tool itself, because only the tool knows what "not found" means and where else to look. get_order("A-1043") can return "No order has the id A-1043. Order ids look like ORD-1042; if you only have the customer's email, use find_orders." Compare what the model can do with each kind of result:

FailureOpaque resultResult the model can act on
Unknown toolKeyError: lookup_orderThere is no tool named lookup_order. Available tools: search_help, get_help_page, find_orders, get_order.
Invalid argumentsfailedInvalid arguments for get_order (order_id: Field required). Call get_order again with an order_id.
Item does not existNoneNo order has the id A-1043. Order ids look like ORD-1042; use find_orders with the email to list them.

Chat Completions has no separate error flag on a tool message: it carries only role, tool_call_id and content. Some providers add such a flag, but the reliable signal everywhere is the text itself, which is why the messages above begin with Error: or say plainly that nothing was found. Here is how a run recovers from the third case:

  • Model
  • Program
  • Model to Program: get_order(A-1043)
  • Program to Model: No order A-1043; ids look like ORD-1042
  • Model to Program: find_orders(email)
  • Program to Model: ORD-1042, ORD-0977
  • Model to Program: get_order(ORD-1042)
  • Program to Model: shipped, arrives Friday

Errors that are not the model's to fix, such as a bug in your own code, are a different matter: hiding them in a tool result only makes them harder to find. The pattern is for the failures a better next call can solve.

True or false?

When the model names a tool that does not exist, the safest response is to end the run with an exception.

False. The model can usually correct itself if the result names the tools that do exist, so the run can continue instead of failing.

An error result should still be sent as a `tool` message with the `tool_call_id` of the call that failed.

True. Every tool call in a reply gets its result, failed or not, and the id ties the error to the call it explains.

If the tool schema is correct, the arguments the model sends will always match it.

False. A schema guides the model but does not bind it, unless a strict mode that some providers offer is turned on. Even then, an id that does not exist still passes the schema. Your code still validates.