Sub topic 17
Testing Tool Selection and Refining Definitions
A tool definition is a prompt. You can't tell whether it works by reading it, because the model reads it differently than you do. This chapter shows how to build a small test set, measure tool selection and argument quality, and change definitions one step at a time.
This chapter assumes you can call an LLM API with tools, read JSON Schema, and read short Python. It builds on the earlier chapters on names, descriptions, parameter schemas, and error messages.
Why you need measurements
Tool failures are quiet. The model calls a plausible but wrong tool, omits an optional filter, or invents an ID. The final answer often still looks fine, so you miss the problem.
Changes also interact. A sharper description for search_orders can pull traffic away from get_order. If you only try the prompt you just fixed, you won't see the new break. A fixed set of test prompts that you rerun after every edit catches these regressions.
What to measure
Measure three things separately. Each one points to a different kind of fix.
| Measurement | Question it answers | Typical fix |
|---|---|---|
| Tool selection | Did the model call the expected tool, or correctly call none? | Names, descriptions, overlap between tools |
| Argument quality | Were the arguments valid and what the prompt asked for? | Parameter descriptions, enums, constraints |
| Recovery | After an error result, did the next call succeed? | Error message wording |
Start with selection. It is the cheapest to check, and a wrong tool makes the argument check meaningless.
Building the test set
Each case is a user prompt paired with the outcome you expect. Collect cases from three sources:
- Real user messages from logs, once you have them. These show phrasing you would not invent.
- Paraphrases of each tool's main use. Write at least three per tool, with different wording.
- Boundary cases between similar tools, and prompts that should call no tool.
Boundary cases matter most. If get_order and search_orders both exist, write prompts that sit near the line: an order ID buried in a long sentence, a vague "my last order", a request with both an ID and a status filter.
Include negative cases too. A prompt like "What is the capital of France?" should produce no tool call. Without negatives, you can reach 100% by making every description pushy.
Keep the set small at first, around 20 to 40 cases. You must be able to read every failure, so a small set you read beats a large one you only count.
A minimal evaluation loop
This loop compares the tool the model chose against the expected one. You supply choose_tool, which wraps your own model call.
CASES = [
("Where is order ord_1001?", "get_order"),
("Show me my cancelled orders from last month", "search_orders"),
("What is the capital of France?", None),
]
def run_eval(choose_tool):
"""choose_tool(prompt) -> name of the tool the model called, or None."""
failures = []
for prompt, expected in CASES:
actual = choose_tool(prompt)
if actual != expected:
failures.append((prompt, expected, actual))
passed = len(CASES) - len(failures)
print(f"{passed}/{len(CASES)} correct")
for prompt, expected, actual in failures:
print(f" {prompt!r}: expected {expected}, got {actual}")
return failuresTo try the harness without an API key, pass a stub. It also shows what a failure report looks like.
def stub_choose_tool(prompt):
if "ord_" in prompt:
return "get_order"
return "search_orders"
if __name__ == "__main__":
run_eval(stub_choose_tool)The stub sends the France question to search_orders, so the run prints 2/3 correct and names the failing case.
For a real model, choose_tool sends the prompt with your tool list and returns the name from the first tool call. With the Anthropic Python SDK, the wrapper looks like this:
import os
import anthropic
client = anthropic.Anthropic()
TOOLS = [] # fill with your tool definitions, for example the search_orders JSON
def choose_tool(prompt):
response = client.messages.create(
model=os.environ["EVAL_MODEL"],
max_tokens=512,
tools=TOOLS,
messages=[{"role": "user", "content": prompt}],
)
for block in response.content:
if block.type == "tool_use":
return block.name
return NoneSet the sampling temperature low if your API allows it, and run borderline cases several times. A case that passes four times out of five is a real finding, not noise to ignore.
Checking arguments
Selection is only half of the result. Extend each case to also check the arguments the model produced. Use checks that tolerate harmless variation. For example, require that status equals "cancelled" and that created_after matches the pattern YYYY-MM-DD, rather than comparing the whole argument object for equality.
Run the arguments through the same server-side validation your tool uses in production. If validation rejects an argument, the case fails, and the rejection message tells you which parameter description to fix. This ties the test set back to the earlier chapter on validating model-generated arguments.
The refinement loop
Treat each edit as an experiment.
Change one thing per run. If you rewrite three descriptions at once and the score rises, you don't know which edit helped. If it falls, you don't know which one hurt.
Diagnosing failures
Match the failure pattern to a likely cause.
| Symptom | Likely cause | Try |
|---|---|---|
| Model calls `search_orders` when the user gave an ID | Descriptions overlap, with no routing rule | Add "If the user gives an order ID, use get_order instead" to the description |
| Model calls a tool for a general-knowledge question | Description is too broad | State what the tool does not cover |
| Model invents `customer_id` | Required field with no source | Say where the value comes from and to ask the user if unknown |
| Dates sent as "last month" | Format not stated | Add the format and an example to the parameter description |
| Model sends `"Shipped"` instead of `"shipped"` | Free-text string for a closed set | Use an enum |
| Model retries the same bad call after an error | Error message gives no next step | Say what was wrong and which tool to call next |
Compare the weak definition do_order_thing with description: "Handles orders." and untyped data and mode strings. Every row above applies to it. Fixing it means more than rewording: it needs a clearer name, a use-and-boundary description, typed parameters, and an enum.
Testing recovery
Error messages are part of the tool design, so test them too. For each error path, build a case where the first call is wrong, return your real error result, and check that the next model call is correct.
For example, give the model "Check order 1001" and see whether it passes 1001. The server's response should then say that IDs look like ord_1001:
def get_order(order_id: str) -> dict:
if not isinstance(order_id, str) or not order_id.startswith("ord_"):
return {
"is_error": True,
"message": (
f"Invalid order_id {order_id!r}. IDs look like 'ord_1001'. "
"If you do not have an ID, call search_orders first."
),
}
return {"is_error": False, "order": {"id": order_id}}Then check whether the model's second call uses ord_1001. If it gives up or repeats 1001, rewrite the message to be more specific, or fix the parameter description so the first call is right.
Pitfalls in testing
- Overfitting to the test set. Adding "Show me my cancelled orders" to a description makes that case pass and teaches nothing general. Fix the underlying rule, then add new paraphrases to check it.
- Testing only happy paths. A set with no negatives and no ambiguous prompts overstates quality.
- Ignoring model changes. A definition tuned for one model can behave differently on another. Rerun the set when you change models or providers.
- Ignoring cost. Longer descriptions can raise selection accuracy but add tokens to every request. Track the size of your tool list next to the score and drop words that don't change any result.
- Judging on one run. Sampling varies. Repeat borderline cases before you decide.
Keeping the set useful
Add every production failure as a new case, after fixing it. Over time the set becomes a record of the mistakes your tools have actually invited. Store it in version control next to the tool definitions, and run it whenever a definition changes, the same way you run unit tests.
Exercise
Your eval shows that "Find my order ord1001" correctly calls getorder, but "Look up ord1001 and any other shipped orders" calls getorder only and never search_orders. A teammate suggests rewriting all of the descriptions at once. What should you do instead, and what kind of test case should you add?
Show answer
Form one hypothesis and change one thing. Here the likely cause is that getorder's description does not say it covers a single order only, and searchorders has no note that it handles status filters. Edit one description, for example by adding "Returns one order. For several orders or filtering by status, use search_orders", then rerun the whole test set. Keep the change only if this case passes and no other case regresses. Add the mixed-intent prompt as a boundary case, with a note on whether you expect both tools to be called, along with paraphrases of it so you can tell a general fix from one that only matches this wording.