How to Design Tools an LLM Agent Uses Correctly: Names, Descriptions and Errors

9 min read

The problem: the model only knows your tool from a few lines of text

Your tool might be a carefully written function with tests. The model never sees any of that. It sees a name, a description, and a JSON Schema, and from those few lines it must decide when to call the tool, what to pass, and how to read what comes back.

When agents fail, the cause is often here, not in the model or the loop. A tool called get_data with the description "gets data" invites guessing. A tool that crashes on a typo ends the run. A tool that returns None on failure leaves the model to invent an answer.

Anthropic's "Building effective agents" calls this the agent computer interface and recommends putting as much care into tool documentation and testing as you would into a human facing interface. OpenAI's function calling guide gives similar advice, including what it calls the intern test: could a person use the function correctly given only what you gave the model?

In this lesson you will build trip_tools.py, a set of trip helper tools designed for a model, with a dispatcher that turns every failure into a message the model can act on. Later lessons import this file.

Bad tool, better tool

Here is a tool definition that technically works:

json
{"name": "weather", "description": "weather info",
 "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}}

The model has to guess: is q a city, a country, coordinates? What does it return? Can it call it for three cities at once? Compare the version in this lesson:

json
{"name": "get_weather",
 "description": "Get the 3 day forecast for one city: summary, high and low in Celsius, and chance of rain from 0 to 1. Call once per city.",
 "parameters": {"type": "object",
   "properties": {"city": {"type": "string", "description": "City name in English, e.g. 'Lisbon'."}},
   "required": ["city"]}}

Each phrase removes a guess:

  • A verb and object name (get_weather) says what it does and that it is read only.
  • What it returns, with units, so the model can reason about the result before seeing it.
  • "Call once per city" answers the question the model would otherwise get wrong.
  • An example value ('Lisbon') shows the expected format.
  • required says the argument cannot be skipped.

Rules that make tools easier for a model

  1. Name tools as verb plus noun: search_hotels, convert_currency, book_hotel. Avoid abbreviations and internal jargon.
  2. Describe when to use it, not only what it does. "Use this instead of doing exchange math yourself" changes behaviour more than any amount of detail about the algorithm.
  3. Use enum for closed sets. If only five currencies are supported, list them. OpenAI's guide recommends enums and object structure to prevent invalid states.
  4. Keep arguments few and flat. Every argument is a chance for a mistake. If your code already knows a value, such as the user id, do not ask the model to fill it in.
  5. Return structured, labelled data. {"high_c": 17, "rain_chance": 0.7} is easier to reason about than "17 degrees, likely rain".
  6. Keep the tool list short. OpenAI's guide suggests aiming for fewer than 20 functions available at the start of a turn, as a soft guideline. Fewer, clearer tools beat many overlapping ones.
  7. Fix predictable mistakes in code. If people write "Lisboa", accept it. Do not rely on the model to retry. Anthropic's guide calls this poka-yoke: change the arguments so mistakes are harder to make.

The trip helper tool file

Save this as trip_tools.py. All data is made up for the course:

python
# file: trip_tools.py
"""Trip helper tools. All data here is made up for the course."""
import json

FAKE_WEATHER = {
    "lisbon": {"forecast": "sunny", "high_c": 22, "low_c": 14, "rain_chance": 0.1},
    "kyoto": {"forecast": "light rain", "high_c": 17, "low_c": 9, "rain_chance": 0.7},
    "oslo": {"forecast": "cloudy", "high_c": 6, "low_c": -1, "rain_chance": 0.4},
}
FAKE_RATES_TO_EUR = {"EUR": 1.0, "USD": 0.92, "JPY": 0.0061, "INR": 0.011, "NOK": 0.085}
FAKE_HOTELS = [
    {"hotel_id": "LIS-01", "city": "lisbon", "name": "Casa Azul", "price_eur": 95},
    {"hotel_id": "LIS-02", "city": "lisbon", "name": "Hotel Miradouro", "price_eur": 160},
    {"hotel_id": "KYO-01", "city": "kyoto", "name": "Ryokan Hana", "price_eur": 140},
    {"hotel_id": "OSL-01", "city": "oslo", "name": "Fjord Inn", "price_eur": 130},
]


# Spellings people (and models) often use. Fixing them in code beats hoping the model retries.
CITY_ALIASES = {"lisboa": "lisbon", "kioto": "kyoto", "kyōto": "kyoto"}


class ToolError(Exception):
    """An error the model should read and react to."""


def normalize_city(city: str) -> str:
    key = city.strip().lower()
    return CITY_ALIASES.get(key, key)


def get_weather(city: str) -> dict:
    data = FAKE_WEATHER.get(normalize_city(city))
    if data is None:
        known = ", ".join(c.title() for c in FAKE_WEATHER)
        raise ToolError(f"Unknown city '{city}'. Try one of: {known}.")
    return {"city": normalize_city(city).title(), **data}


def convert_currency(amount: float, from_currency: str, to_currency: str) -> dict:
    src, dst = from_currency.upper(), to_currency.upper()
    for code in (src, dst):
        if code not in FAKE_RATES_TO_EUR:
            raise ToolError(f"Unsupported currency '{code}'. Supported: {sorted(FAKE_RATES_TO_EUR)}.")
    if amount < 0:
        raise ToolError("amount must be zero or more.")
    return {"amount": round(amount * FAKE_RATES_TO_EUR[src] / FAKE_RATES_TO_EUR[dst], 2), "currency": dst}


def search_hotels(city: str, max_price_eur: int = 1000) -> dict:
    matches = [h for h in FAKE_HOTELS if h["city"] == normalize_city(city) and h["price_eur"] <= max_price_eur]
    return {"city": normalize_city(city).title(), "count": len(matches), "hotels": matches}


TOOLS = [
    {"type": "function", "function": {
        "name": "get_weather",
        "description": "Get the 3 day forecast for one city: summary, high and low in Celsius, and "
                       "chance of rain from 0 to 1. Call once per city.",
        "parameters": {"type": "object", "properties": {
            "city": {"type": "string", "description": "City name in English, e.g. 'Lisbon'."}},
            "required": ["city"]}}},
    {"type": "function", "function": {
        "name": "convert_currency",
        "description": "Convert money between currencies. Use this instead of doing exchange math yourself.",
        "parameters": {"type": "object", "properties": {
            "amount": {"type": "number", "description": "Amount to convert, e.g. 250"},
            "from_currency": {"type": "string", "enum": sorted(FAKE_RATES_TO_EUR)},
            "to_currency": {"type": "string", "enum": sorted(FAKE_RATES_TO_EUR)}},
            "required": ["amount", "from_currency", "to_currency"]}}},
    {"type": "function", "function": {
        "name": "search_hotels",
        "description": "List hotels in a city, optionally under a nightly price in EUR. Returns hotel_id values.",
        "parameters": {"type": "object", "properties": {
            "city": {"type": "string", "description": "City name in English"},
            "max_price_eur": {"type": "integer", "description": "Highest nightly price in EUR"}},
            "required": ["city"]}}},
]
FUNCTIONS = {"get_weather": get_weather, "convert_currency": convert_currency, "search_hotels": search_hotels}


def run_tool(name: str, raw_arguments: str, functions: dict = FUNCTIONS) -> str:
    """Run one tool call and ALWAYS return a string for the tool message."""
    if name not in functions:
        return json.dumps({"error": f"No tool named '{name}'. Available: {sorted(functions)}."})
    try:
        args = json.loads(raw_arguments or "{}")
    except json.JSONDecodeError as exc:
        return json.dumps({"error": f"Arguments were not valid JSON ({exc.msg}). Send a JSON object."})
    try:
        return json.dumps(functions[name](**args))
    except ToolError as exc:  # expected problems: tell the model how to fix the call
        return json.dumps({"error": str(exc)})
    except TypeError as exc:  # wrong or missing argument names
        return json.dumps({"error": f"Bad arguments for {name}: {exc}"})
    except Exception as exc:  # anything else: report it without crashing the loop
        return json.dumps({"error": f"{name} failed: {type(exc).__name__}"})

There are four ideas in this file worth looking at closely.

Idea 1: a custom error type for expected problems

ToolError is raised when the input is understandable but wrong: an unknown city, an unsupported currency, a negative amount. Its message is written for the model, and every message says how to fix the call: "Try one of: Lisbon, Kyoto, Oslo." An error that only says "invalid input" gives the model nothing to work with.

Idea 2: normalize input before rejecting it

normalize_city lowercases and trims the input, then maps known alternative spellings through CITY_ALIASES. This was added after testing. An earlier version returned a helpful error for "Lisboa", and the expectation was that the model would read "Try one of: Lisbon" and call again. With qwen2.5:1.5b it did not: in two runs, even with a system prompt telling it to retry, it passed the error on to the user instead.

The fix that worked every time was in code. A one line alias table does not depend on the model's judgement. This is a general rule: anything you can make deterministic, make deterministic, and save the model's reasoning for what code cannot decide.

Animation: A helpful error did not make the small model retry. An alias table in code fixed "Lisboa" every time.

Idea 3: the dispatcher always returns a string

run_tool is the only place the agent loop calls tools. It handles every way a call can fail:

flowchart TD
    IN["run_tool(name, raw_arguments)"] --> N{"Tool name known?"}
    N -->|no| E1["error: No tool named ...<br/>plus the available list"]
    N -->|yes| J{"Arguments valid JSON?"}
    J -->|no| E2["error: Arguments were not valid JSON"]
    J -->|yes| R["Call the function with **args"]
    R -->|ToolError| E3["error: the ToolError message"]
    R -->|TypeError| E4["error: Bad arguments for ..."]
    R -->|any other exception| E5["error: exception type only"]
    R -->|success| OK["JSON result"]
    E1 & E2 & E3 & E4 & E5 & OK --> OUT["Always a string for the tool message"]

Diagram: Every path through run_tool ends in a string the model can read, never a crash.

FailureExampleWhat the model receives
Unknown toolbook_flightthe list of available tools
Broken JSONa missing brace"Arguments were not valid JSON"
Wrong argument nametown instead of citythe Python TypeError text
Expected problemunknown citythe ToolError message
Anything elsea bug in your toolthe exception type only

The last case reports only the exception type, not the full message or traceback. Internal errors can contain file paths, keys or other details that should not end up in a prompt, a log, or an answer to the user.

The point of this table: errors are tool results. The model sees them in the conversation and can correct course, explain the problem, or try another tool. The MCP Python SDK follows the same approach, as you will see in lesson 13: a tool that raises comes back as a normal result with an error flag, so the model can read it.

Idea 4: tools and functions stay together

TOOLS (what the model sees) and FUNCTIONS (what runs) sit next to each other in one file. When you rename a tool or add an argument, both change in the same place. Lesson 3 showed how to generate the schema from the function to remove even that duplication.

Test your tools without a model

Tools are plain functions, so test them like plain functions before an LLM is involved. Save this as check_tools.py:

python
# file: check_tools.py
from trip_tools import run_tool

# Every failure becomes a readable result instead of a crash.
print(run_tool("get_weather", '{"city": "Lisboa"}'))   # alias fixed in code
print(run_tool("get_weather", '{"city": "Paris"}'))    # unknown city
print(run_tool("get_weather", '{"town": "Lisbon"}'))
print(run_tool("get_weather", '{"city": "Lisbon"'))
print(run_tool("book_flight", '{}'))
print(run_tool("convert_currency", '{"amount": 100, "from_currency": "usd", "to_currency": "EUR"}'))

Output from the tested run:

text
{"city": "Lisbon", "forecast": "sunny", "high_c": 22, "low_c": 14, "rain_chance": 0.1}
{"error": "Unknown city 'Paris'. Try one of: Lisbon, Kyoto, Oslo."}
{"error": "Bad arguments for get_weather: get_weather() got an unexpected keyword argument 'town'"}
{"error": "Arguments were not valid JSON (Expecting ',' delimiter). Send a JSON object."}
{"error": "No tool named 'book_flight'. Available: ['convert_currency', 'get_weather', 'search_hotels']."}
{"amount": 92.0, "currency": "EUR"}

None of these crash. That is the whole goal: a bad call from the model becomes one more message in the conversation, not an exception that ends the run.

Use the tools in an agent

Save this as recover.py. It is the loop from lesson 2, now using run_tool:

python
# file: recover.py
from llm import client, MODEL
from trip_tools import TOOLS, run_tool

SYSTEM = (
    "You are a trip helper. Use tools for weather, money and hotels. "
    "If a tool returns an error, read it, fix your arguments and call the tool again "
    "before answering. Do not ask the user to fix it if the error suggests a valid value."
)

def run_agent(user_text: str, max_steps: int = 6) -> str:
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": user_text}]
    for _ in range(max_steps):
        msg = client.chat.completions.create(
            model=MODEL, messages=messages, tools=TOOLS, temperature=0
        ).choices[0].message
        messages.append(msg)
        if not msg.tool_calls:
            return msg.content
        for call in msg.tool_calls:
            result = run_tool(call.function.name, call.function.arguments)
            print(f"  {call.function.name}({call.function.arguments}) -> {result}")
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
    return "Stopped at the step limit."

if __name__ == "__main__":
    print(run_agent("What's the weather in Lisboa this weekend?"))
    print(run_agent("I can go to Paris or Oslo. Which one is warmer?"))

In the tested run with qwen2.5:1.5b:

  • "Lisboa": the alias table mapped it to Lisbon, so the first call succeeded and the answer included the forecast and the 10% chance of rain.
  • "Paris or Oslo": the model called get_weather for both. Paris returned the error, Oslo returned a forecast. The answer said Paris was not recognized and described Oslo's weather, but it did not directly answer "which one is warmer". The facts were right; the answer missed the question.

That second result is typical of a small model, and it shows what tool design can and cannot fix. Good errors made sure the model knew Paris was unavailable instead of inventing a forecast. Answering the actual question well is a model quality issue, which you can measure with the eval harness in lesson 14 and improve with a larger model or a clearer system prompt.

Descriptions are prompts: treat them like code

Tool descriptions are part of every request, and OpenAI's guide notes that function definitions count against the context limit and are billed as input tokens. So:

  • Keep them precise rather than long. One or two sentences per tool plus argument descriptions is usually enough.
  • Put rules about when to use tools in the system message, and rules about how to use a tool in its description.
  • Change one description at a time and rerun your tests. A small wording change can shift behaviour.
  • Version them with your code. They are code.

Common mistakes in tool design

  • Overlapping tools, such as search_hotels and find_accommodation. The model picks one at random.
  • Returning huge payloads. A tool that returns 500 hotels fills the context window. Return the top few and a count.
  • Silent failures. Returning {} or None lets the model fill the gap with an invented answer. Return an explicit error.
  • Leaking internals in errors. Stack traces and paths do not help the model and can expose details you would not show a user.
  • Asking the model for values your code knows. Dates, user ids, session ids: pass them in code.

What to try next

  • Add a get_local_time(city) tool to trip_tools.py following the same rules, including a helpful error.
  • Remove "Call once per city" from the description and ask about two cities. Does the model try to pass both in one call?
  • Shorten every description to three words and run recover.py again to see how behaviour changes.
  • Add "Paris" to FAKE_WEATHER and confirm the second question now gets a direct comparison.

Next you will handle the other direction: getting the model's final answer back in a shape your code can rely on, using structured outputs and validation.

Sources