Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 3

Writing Tools a Model Can Use Well

Rewrite a weak order-support tool set step by step: make every required argument reachable, write descriptions that say when to use each tool, constrain formats, and convert the same definitions to Claude and OpenAI strict mode.

Contentsand lesson path

What you will learn

  • Define tools with names, descriptions and JSON Schema parameters that a model selects correctly on a test set of requests.

Prerequisites: LLM API Integration

01. The problem

A model chooses a tool from two things only: the conversation and the text of your tool definitions, meaning names, descriptions and parameter schemas. It has no access to your codebase, your wiki or the habits of your team. If the definitions are vague, the model guesses, and guesses show up as the wrong tool, a missing call, or arguments it made up.

Here is the first version of an order-support tool set, the kind that gets written in an afternoon:

  • lookup_order(id), described as "Gets an order."
  • check_shipping(tracking_number, carrier), described as "Shipping info for an order."
  • refund(order, amount), described as "Refund an order.", with amount as a number.

Now walk one real request through it: "Where is my package for order 1044?" The obvious tool is check_shipping, but it requires a tracking number and a carrier. The customer has neither, and nothing in lookup_order's description says it returns them. The model has three bad options: invent a tracking number, call lookup_order and hope, or ask the customer for data they do not have. Better wording alone cannot fix this; the tool set itself has a gap.

In this worked example you fix the set in four steps, ending with definitions you can send to both Claude and OpenAI with strict mode on. Lesson 5 then measures whether the rewrite helped.

02. Step 1: Walk real requests through the tools

Before you polish any wording, take five to ten real requests and check one rule: every required argument must come either from the user or from the result of an earlier tool call. Where the rule fails, the model is forced to guess, and no description can stop that.

For the order set, the walk gives three changes:

  1. Tracking takes the order ID. The new track_shipment(order_id) looks up the carrier and tracking number itself, so the model only needs what the customer already has.
  2. A customer who has lost the order number needs a way in, so list_orders lists the signed-in customer's orders. The customer comes from the session, never from an argument.
  3. The refund tool takes the amount as a string with two decimals and a reason from a fixed list, and its description says it moves money.

Also look at the format the user actually types. Customers write "1044", not "ORD-1044", so the order ID description says what to do with bare digits, and what to do when there is no ID at all: ask, never guess.

03. Step 2: Say when to use each tool, not just what it does

A good description answers the questions a new colleague would ask. Claude's tool documentation recommends at least three or four sentences per tool, and Anthropic's guide to writing tools for agents makes the same case. Cover these points:

  • What it does and returns, including fields the model may need next, such as the carrier.
  • When to use it, phrased as a trigger: "Use when the customer asks where a parcel is."
  • When not to use it, and what to use instead, for any tool with a close neighbour.
  • Side effects, in capitals if they move money or delete data, plus the condition for calling.
  • Parameter formats with an example, and an enum for every closed set of values.

Save the rewritten set as order_tools.py. The tools are written once in a neutral form; two small functions convert them for each provider.

Python · order_tools.py
"""Order-support tools, written once and converted for each provider."""
ORDER_ID = {
    "type": "string",
    "pattern": "^ORD-[0-9]{4,6}$",
    "description": "Order ID such as ORD-1044. If the customer gives only "
                   "digits (1044), add the ORD- prefix. If no order ID was "
                   "given, ask for it; never guess one.",
}

TOOLS = [
    {
        "name": "get_order",
        "description": (
            "Look up one order of the signed-in customer by order ID. "
            "Returns status, items, total paid and, once shipped, the "
            "carrier and tracking number. Use when the customer asks about "
            "the contents, price or status of a specific order. To see "
            "where a parcel is now, use track_shipment instead."),
        "properties": {"order_id": ORDER_ID},
        "required": ["order_id"],
    },
    {
        "name": "track_shipment",
        "description": (
            "Get the live delivery status of a shipped order: latest scan, "
            "location and estimated delivery date. Use when the customer "
            "asks where a parcel is or when it will arrive. Takes the "
            "order ID; the service finds the carrier and tracking number."),
        "properties": {"order_id": ORDER_ID},
        "required": ["order_id"],
    },
    {
        "name": "list_orders",
        "description": (
            "List the signed-in customer's orders, newest first. Use when "
            "the customer does not know the order ID or asks about several "
            "orders. Returns at most `limit` orders (default 5)."),
        "properties": {
            "status": {"type": "string",
                       "enum": ["any", "processing", "shipped", "delivered"],
                       "description": "Filter by status. Default: any."},
            "limit": {"type": "integer",
                      "description": "How many orders, 1 to 20. Default 5."},
        },
        "required": [],
    },
    {
        "name": "request_refund",
        "description": (
            "Refund part or all of a delivered order. SIDE EFFECT: moves "
            "money back to the customer and cannot be undone. Only call "
            "after the customer has confirmed the order and the amount in "
            "this conversation. Do not use for cancellations of orders that "
            "have not shipped."),
        "properties": {
            "order_id": ORDER_ID,
            "amount": {"type": "string", "pattern": "^[0-9]+\\.[0-9]{2}$",
                       "description": "Amount in the order currency, as a "
                                      "string with two decimals: 19.99"},
            "reason": {"type": "string",
                       "enum": ["damaged", "not_received", "wrong_item",
                                "other"]},
        },
        "required": ["order_id", "amount", "reason"],
    },
]


def to_claude(tool: dict) -> dict:
    """Claude Messages API: name, description, input_schema, strict."""
    return {
        "name": tool["name"],
        "description": tool["description"],
        "strict": True,
        "input_schema": {"type": "object", "properties": tool["properties"],
                         "required": tool["required"],
                         "additionalProperties": False},
    }


def to_openai(tool: dict) -> dict:
    """OpenAI Responses API. Strict mode wants every property in
    `required`, so an optional property becomes 'type or null'."""
    props = {}
    for name, schema in tool["properties"].items():
        schema = dict(schema)
        if name not in tool["required"]:
            schema["type"] = [schema["type"], "null"]
        props[name] = schema
    return {
        "type": "function",
        "name": tool["name"],
        "description": tool["description"],
        "strict": True,
        "parameters": {"type": "object", "properties": props,
                       "required": list(props), "additionalProperties": False},
    }

Three details in this file are easy to miss. get_order and track_shipment both name the other one, so the boundary is stated from both sides. ORDER_ID is shared, so the format rule cannot drift between tools. And nothing takes a customer or account ID: those come from your authentication layer, which closes the easiest way for a model, or a prompt injection, to act on someone else's data.

04. Step 3: Convert for each provider with strict mode on

Both converters set strict: true. With strict mode, the provider constrains generation so the arguments match the schema: an enum value is one of the listed ones and a required field is present. Without it the schema is only guidance: the model can still send "United Parcel Service" for an enum of carrier codes, and your own validation (lesson 4) is the only guard. One provider detail: if you leave strict out, the OpenAI Responses API tries to make the schema strict and silently falls back to best effort when it cannot, while Chat Completions and Claude stay non-strict. Set strict explicitly so you know which one you got.

Strict mode has rules of its own, and they differ:

  • OpenAI requires every property to be listed in required and additionalProperties: false. An optional field is expressed as "this type or null", which is what to_openai does for status and limit.
  • Claude accepts optional properties as usual, but supports only part of JSON Schema in strict mode. Numeric limits such as minimum and maximum and string lengths are not supported and a raw request that uses them is rejected with HTTP 400. That is why limit says "1 to 20" in its description; your code checks the range.

Check the converted output with a short script.

Python · show_tools.py
import json

from order_tools import TOOLS, to_claude, to_openai

list_orders = next(t for t in TOOLS if t["name"] == "list_orders")
print(json.dumps(to_claude(list_orders)["input_schema"]["required"]))
oa = to_openai(list_orders)["parameters"]
print(json.dumps(oa["required"]), json.dumps(oa["properties"]["limit"]["type"]))
Terminal
python3 show_tools.py
Expected output
[]
["status", "limit"] ["integer", "null"]

The first line is the Claude schema: nothing is required. The second is the OpenAI schema: both fields are required, and limit may be null. The model sends null when it has no value, and your handler treats null as "use the default".

05. Step 4: Lint the definitions before you measure

Some problems can be caught without calling a model at all. The linter below checks a few of the rules from step 2 on the original set and on the rewrite. It is a smoke test, not proof: a description can pass every check and still confuse the model.

Python · lint_tools.py
"""Flag tool definitions that make the model guess."""
import re

from order_tools import TOOLS

NAIVE = [
    {"name": "lookup_order", "description": "Gets an order.",
     "properties": {"id": {"type": "string"}}, "required": ["id"]},
    {"name": "check_shipping", "description": "Shipping info for an order.",
     "properties": {"tracking_number": {"type": "string"},
                    "carrier": {"type": "string"}},
     "required": ["tracking_number", "carrier"]},
    {"name": "refund", "description": "Refund an order.",
     "properties": {"order": {"type": "string"}, "amount": {"type": "number"}},
     "required": ["order", "amount"]},
]


def lint(tools: list[dict]) -> list[str]:
    problems = []
    for t in tools:
        name, desc = t["name"], t["description"]
        if len(re.findall(r"[.!?](\s|$)", desc)) < 2:
            problems.append(f"{name}: description under 2 sentences")
        if not re.search(r"\b(use when|use this when|only call)", desc, re.I):
            problems.append(f"{name}: does not say when to use it")
        for pname, schema in t["properties"].items():
            if "description" not in schema and "enum" not in schema:
                problems.append(f"{name}.{pname}: no description or enum")
            if schema.get("type") == "number" and "amount" in pname:
                problems.append(f"{name}.{pname}: money as float")
        if re.search(r"refund|delete|freeze|send", name) and "SIDE EFFECT" \
                not in desc:
            problems.append(f"{name}: side effect not stated")
    return problems


for label, tools in [("naive", NAIVE), ("rewritten", TOOLS)]:
    found = lint(tools)
    print(f"{label}: {len(found)} problems")
    for p in found:
        print("  -", p)
Terminal
python3 lint_tools.py
Expected output
naive: 13 problems
  - lookup_order: description under 2 sentences
  - lookup_order: does not say when to use it
  - lookup_order.id: no description or enum
  - check_shipping: description under 2 sentences
  - check_shipping: does not say when to use it
  - check_shipping.tracking_number: no description or enum
  - check_shipping.carrier: no description or enum
  - refund: description under 2 sentences
  - refund: does not say when to use it
  - refund.order: no description or enum
  - refund.amount: no description or enum
  - refund.amount: money as float
  - refund: side effect not stated
rewritten: 0 problems

Zero lint problems does not mean the model now picks the right tool. Clearer descriptions usually raise selection accuracy, but by how much depends on the model, the tool set and the requests. The only honest number is one you measure on a labelled set of requests, over several runs, before and after the change. Lesson 5 builds exactly that harness and uses this tool set.

06. Check your understanding

Practice check · 3 questions

Designing the order tools

Use the order tool set from this lesson. Each question has one best answer.

Q1. Only `get_invoice(invoice_number)` can answer "Why was I charged twice in March?", and customers never know their invoice numbers. What is the best fix?
Q2. You add `freeze_card` to `TOOLS`, described as "Freezes the card. Use when the customer reports fraud.", with one property, `reason`, that has an enum. What does `lint_tools.py` now report for the rewritten set?
Q3. A raw Claude request sets `strict: true` on a tool whose `limit` schema has `minimum: 1`. What happens?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the practice project (look up an order, list a customer's orders, request a refund):

  1. Keep your first, quick definitions as version 1. You will need them in lesson 5.
  2. Walk ten realistic requests through version 1 and note every argument the model would have to guess.
  3. Write version 2 using steps 2 and 3, run the linter on both, and convert version 2 for the provider you use with strict mode on.
  4. Write down what you expect to improve, so you can compare it with what lesson 5 measures.

08. Review prompt

Without looking back:

  1. State the rule you use to check whether a tool set can serve a request at all.
  2. Name five things a good tool description says.
  3. What does strict mode guarantee, and what does it not? How do OpenAI and Claude differ in what a strict schema may contain?
  4. Why should an account ID come from the session instead of a tool argument?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check