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 5 of 6 · Lab · 20 min · revision 3

Measuring Tool Selection Accuracy

Build a harness that scores tool choice on labelled requests, including requests that need no tool, over repeated runs with 95% intervals. Compare two description versions, tools on and off, and a hosted tool on and off. Runs offline against a scripted fake model.

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.
  • Explain what happens in a tool call (the model emits a structured request, your code runs it) and when to force, allow or disable tool use.

Prerequisites: LLM API Integration

01. Goal and setup

In lesson 2 you rewrote the order tool descriptions and said they were better. This lab turns that claim into a measurement. You build a harness that sends labelled requests to a model, reads which tools it called, and reports how often the choice was right, including the requests where the right choice is no tool at all. You then use it to answer three questions: did the rewrite help, what happens if you disable tools, and is a hosted web search tool worth switching on for this assistant?

One rule shapes the whole design: a single run proves nothing. The same request can get a different reply on the next run. Hosted models are not deterministic even at low temperature: details on the provider's side, such as how requests are batched and in which order floating-point sums run, can change the result. OpenAI calls its seed parameter a best effort and states that determinism is not guaranteed. Many current models do not accept a temperature setting. From API version 2026-10-21, which the anthropic 2.x SDKs send, Claude no longer accepts temperature, top_p or top_k at all, even at their default values, and many OpenAI reasoning models accept only the default. So the harness runs every case several times and reports each number with a 95% interval.

You need: Python 3.12 or later; no packages, no key. A scripted fake model stands in for the provider and returns Claude- or OpenAI-shaped responses. Step 7 shows how to point the same harness at a real model.

Project layout at the end of the lab
tool-eval/
├── catalog.py      step 1: the four order tools, two description versions
├── cases.py        step 2: 24 labelled requests
├── fake_model.py   step 3: scripted stand-in for a model
├── eval_tools.py   step 4: harness, metrics, intervals
├── test_eval.py    step 5: tests for the scorer
└── real_model.py   step 7: optional, real providers
Terminal
mkdir tool-eval && cd tool-eval

02. Step 1: The tool catalogue

The tools are the order tools from lesson 2, in short form. Version 1 and version 2 have the same names and schemas and differ only in their descriptions, so any change in the results comes from the descriptions.

Python · catalog.py
"""The four order tools. v1 and v2 differ only in their descriptions."""
ORDER_ID = {"type": "string", "pattern": "^ORD-[0-9]{4,6}$"}
SCHEMAS = {
    "get_order": {"properties": {"order_id": ORDER_ID},
                  "required": ["order_id"]},
    "track_shipment": {"properties": {"order_id": ORDER_ID},
                       "required": ["order_id"]},
    "list_orders": {"properties": {
        "status": {"type": "string",
                   "enum": ["any", "processing", "shipped", "delivered"]}},
        "required": []},
    "request_refund": {"properties": {
        "order_id": ORDER_ID,
        "amount": {"type": "string", "pattern": "^[0-9]+\\.[0-9]{2}$"},
        "reason": {"type": "string",
                   "enum": ["damaged", "not_received", "wrong_item", "other"]}},
        "required": ["order_id", "amount", "reason"]},
}
DESCRIPTIONS = {
    "v1": {"get_order": "Gets an order.",
           "track_shipment": "Shipping info.",
           "list_orders": "Lists orders.",
           "request_refund": "Refunds an order."},
    "v2": {"get_order": "Look up one order by ID: items, total, status. Use "
                        "for questions about a specific order's contents or "
                        "payment. For where a parcel is, use track_shipment.",
           "track_shipment": "Live delivery status of a shipped order. Use "
                             "when asked where a parcel is or when it "
                             "arrives.",
           "list_orders": "List the customer's orders, newest first. Use "
                          "when they do not know the order ID.",
           "request_refund": "Refund a delivered order. SIDE EFFECT: moves "
                             "money. Only call once the customer has given "
                             "the order, amount and reason."},
}


def tools_for(version: str) -> list:
    """Neutral definitions; convert per provider as in lessons 2 and 3."""
    return [{"name": n, "description": DESCRIPTIONS[version][n],
             "input_schema": {"type": "object", **s,
                              "additionalProperties": False}}
            for n, s in SCHEMAS.items()]

03. Step 2: Labelled cases, including "no tool"

Each case is a request, the expected tool and the arguments it should get. None means the model should answer without calling a tool. Those six cases are what let you measure when tools should be used, not just which one: a model that calls list_orders when the customer says "Thanks!" costs a request and can confuse the conversation. Case c22 is a trap on purpose: "I want a refund." names no order or amount, so the right move is to ask, not to call request_refund with invented values.

Write cases from real traffic, cover every tool, and include near-misses between similar tools. Twenty-four cases are enough to build the harness, but small for decisions.

Python · cases.py
"""Labelled requests. tool=None means: answer without calling a tool."""
CASES = [
    ("c01", "What did I buy in order ORD-1044?", "get_order",
     {"order_id": "ORD-1044"}),
    ("c02", "How much did I pay for order 2210?", "get_order",
     {"order_id": "ORD-2210"}),
    ("c03", "Was ORD-3307 paid with my credit card?", "get_order",
     {"order_id": "ORD-3307"}),
    ("c04", "Which size did I pick in ORD-1044?", "get_order",
     {"order_id": "ORD-1044"}),
    ("c05", "Is order ORD-4410 still processing?", "get_order",
     {"order_id": "ORD-4410"}),
    ("c06", "Where is my parcel for ORD-1044?", "track_shipment",
     {"order_id": "ORD-1044"}),
    ("c07", "When will order 2210 arrive?", "track_shipment",
     {"order_id": "ORD-2210"}),
    ("c08", "The courier page for ORD-3307 has not moved in days. Why?",
     "track_shipment", {"order_id": "ORD-3307"}),
    ("c09", "Has ORD-4410 left the warehouse yet?", "track_shipment",
     {"order_id": "ORD-4410"}),
    ("c10", "Can you see if my ORD-5120 parcel is out for delivery?",
     "track_shipment", {"order_id": "ORD-5120"}),
    ("c11", "I don't remember my order number. What have I ordered?",
     "list_orders", {}),
    ("c12", "Show me everything I've ordered that has shipped.",
     "list_orders", {"status": "shipped"}),
    ("c13", "Which of my orders were delivered?", "list_orders",
     {"status": "delivered"}),
    ("c14", "What are my most recent orders?", "list_orders", {}),
    ("c15", "ORD-1044 arrived broken. Please refund the full 49.90.",
     "request_refund", {"order_id": "ORD-1044", "amount": "49.90",
                        "reason": "damaged"}),
    ("c16", "Refund 12.00 on ORD-2210, it was the wrong colour.",
     "request_refund", {"order_id": "ORD-2210", "amount": "12.00",
                        "reason": "wrong_item"}),
    ("c17", "ORD-3307 never came. I want my 30.00 back.", "request_refund",
     {"order_id": "ORD-3307", "amount": "30.00", "reason": "not_received"}),
    ("c18", "Yes, go ahead with the 8.50 refund on ORD-4410 (damaged).",
     "request_refund", {"order_id": "ORD-4410", "amount": "8.50",
                        "reason": "damaged"}),
    ("c19", "Thanks, that's all for today!", None, {}),
    ("c20", "What does 'out for delivery' mean?", None, {}),
    ("c21", "Can you say that again in simpler words?", None, {}),
    ("c22", "I want a refund.", None, {}),  # must ask which order and amount
    ("c23", "Hello!", None, {}),
    ("c24", "How do I write a polite complaint to a courier?", None, {}),
]

04. Step 3: A scripted stand-in for the model

Be clear about what this file is. It is not a model and it does not read your descriptions the way a model does. It looks up the right answer in cases.py and then makes mistakes at set rates: the wrong but similar tool, a missing call, an order ID without its prefix, an extra parallel call, a call where none was needed, and, when a hosted web search tool is switched on, an occasional search. The rates shrink as descriptions get longer, a crude stand-in for "clearer descriptions help". Its random choices are seeded so your numbers match the ones below; a real model has no such seed.

It returns the provider's response shape: tool_use and server_tool_use blocks for Claude, function_call and web_search_call items for OpenAI. With tool_choice set to none it never calls a client tool.

Python · fake_model.py
"""A scripted stand-in for a model choosing tools. Not a real model.

It knows the labels in cases.py and makes mistakes at set rates. The
rates shrink as the tool descriptions get longer, which is a crude stand-in
for "clearer descriptions help". Answers are random, like a real model's,
but seeded, so the lab prints the same numbers on every machine.
"""
import json
import random

from cases import CASES

LABELS = {prompt: (tool, args) for _, prompt, tool, args in CASES}
PARTNER = {"get_order": "track_shipment", "track_shipment": "get_order",
           "list_orders": "get_order", "request_refund": "get_order"}


class FakeModel:
    def __init__(self, provider: str, seed: str):
        self.provider, self.rng, self.ids = provider, random.Random(seed), 0

    def create(self, **req):
        if "temperature" in req:
            raise ValueError("temperature is not supported for this model")
        tools = [t for t in req["tools"] if "description" in t]  # yours
        hosted = len(tools) < len(req["tools"])  # a provider-run tool is on
        choice = req["tool_choice"]
        choice = choice["type"] if isinstance(choice, dict) else choice
        words = sum(len(t["description"].split()) for t in tools) / len(tools)
        quality = min(1.0, words / 25)
        if self.provider == "claude":
            prompt = req["messages"][-1]["content"]
        else:
            prompt = req["input"][-1]["content"]
        calls = [] if choice == "none" else self.decide(prompt, quality)
        web = hosted and choice != "none" and self.rng.random() < (
            0.06 if LABELS[prompt][0] else 0.25)
        return self.render(calls, web)

    def decide(self, prompt, q):
        tool, args = LABELS[prompt]
        r = self.rng.random()
        if tool is None:  # should answer in text
            if r < 0.35 - 0.25 * q:
                return [("list_orders", {})]
            return []
        if r < 0.16 - 0.12 * q:
            return [(PARTNER[tool], {"order_id": "ORD-1044"})]
        r -= 0.16 - 0.12 * q
        if r < 0.04 - 0.02 * q:
            return []
        r -= 0.04 - 0.02 * q
        if r < 0.10 - 0.07 * q and "order_id" in args:
            return [(tool, dict(args, order_id=args["order_id"][4:]))]
        r -= 0.10 - 0.07 * q
        if r < 0.05 - 0.03 * q:
            return [(tool, args), ("list_orders", {})]
        return [(tool, args)]

    def render(self, calls, web):
        self.ids += 1
        if self.provider == "claude":
            content = []
            if web:
                content.append({"type": "server_tool_use", "name": "web_search",
                                "id": f"srvtoolu_{self.ids}",
                                "input": {"query": "..."}})
            content += [{"type": "tool_use", "id": f"toolu_{self.ids}_{i}",
                         "name": n, "input": a}
                        for i, (n, a) in enumerate(calls)]
            if not calls:
                content.append({"type": "text", "text": "..."})
            return {"content": content,
                    "stop_reason": "tool_use" if calls else "end_turn"}
        output = [{"type": "web_search_call", "id": f"ws_{self.ids}",
                   "status": "completed"}] if web else []
        output += [{"type": "function_call", "call_id": f"call_{self.ids}_{i}",
                    "name": n, "arguments": json.dumps(a)}
                   for i, (n, a) in enumerate(calls)]
        if not calls:
            output.append({"type": "message", "role": "assistant",
                           "content": [{"type": "output_text", "text": "..."}]})
        return {"status": "completed", "output": output}

05. Step 4: The harness

The harness builds a real request for each case (Claude or OpenAI format, model name from an environment variable, no temperature), extracts the calls from the response and scores them:

  • selection: the model called exactly the expected tool once, or nothing when no tool was expected;
  • args valid: calls whose name exists and whose arguments pass the schema;
  • superfluous: on no-tool cases, how often the model called a tool anyway;
  • missed: on tool cases, how often it called nothing;
  • extra calls: on tool cases, replies with more than one call;
  • hosted calls per 100 requests: searches the provider ran, which you pay for.

Each case is run several times. For the 95% interval, the harness resamples cases, not single runs, 2,000 times (a bootstrap). Runs of the same case are not independent: a case the model finds hard is hard on every run. Treating 120 runs as 120 independent trials would make the intervals look much narrower than they are. The difference between two versions uses the same resampled cases for both (a paired bootstrap).

Python · eval_tools.py
"""Measure tool selection over repeated runs and report 95% intervals."""
import argparse
import json
import os
import random
import re
import textwrap

from cases import CASES
from catalog import SCHEMAS, tools_for
from fake_model import FakeModel

CONDITIONS = [  # (label, description version, tool_choice, hosted web search)
    ("v1 auto", "v1", "auto", False),
    ("v2 auto", "v2", "auto", False),
    ("v2 none", "v2", "none", False),
    ("v2 auto+web", "v2", "auto", True),
]


def build_request(provider, version, choice, web, prompt):
    tools = tools_for(version)
    model_var = "ANTHROPIC_MODEL" if provider == "claude" else "OPENAI_MODEL"
    model = os.environ.get(model_var, "claude-sonnet-5-5"
                           if provider == "claude" else "gpt-6-astra")
    if provider == "claude":  # no temperature: API 2026-10-21 rejects it
        tools = [dict(t, strict=True) for t in tools]
        if web:
            tools.append({"type": "web_search_20260318", "name": "web_search"})
        # Thinking counts toward max_tokens, so leave it plenty of room.
        return {"model": model, "max_tokens": 16000, "tools": tools,
                "tool_choice": {"type": choice},
                "messages": [{"role": "user", "content": prompt}]}
    tools = [{"type": "function", "name": t["name"],
              "description": t["description"],  # strict needs the null
              "strict": False,                   # trick from lesson 2
              "parameters": t["input_schema"]} for t in tools]
    if web:
        tools.append({"type": "web_search"})
    return {"model": model, "tools": tools, "tool_choice": choice,
            "input": [{"role": "user", "content": prompt}]}


def extract(provider, resp):
    """-> (client calls as (name, args), number of provider-run calls),
    or None if the reply was cut off before the model finished choosing"""
    if resp.get("stop_reason") == "max_tokens" or resp.get(
            "status") == "incomplete":
        return None
    if provider == "claude":
        blocks = resp["content"]
        calls = [(b["name"], b["input"]) for b in blocks
                 if b["type"] == "tool_use"]
        return calls, sum(b["type"] == "server_tool_use" for b in blocks)
    items = resp["output"]
    calls = [(i["name"], i["arguments"]) for i in items
             if i["type"] == "function_call"]
    return calls, sum(i["type"] == "web_search_call" for i in items)


def load(args):
    """OpenAI sends a JSON string, Claude an object. None if unreadable."""
    if not isinstance(args, str):
        return args
    try:
        return json.loads(args)
    except json.JSONDecodeError:
        return None


def valid(name, args):
    """Is this call to a known tool with schema-valid arguments?"""
    args = load(args)
    if name not in SCHEMAS or not isinstance(args, dict):
        return False
    props, spec = SCHEMAS[name]["properties"], SCHEMAS[name]
    if set(args) - set(props) or set(spec["required"]) - set(args):
        return False
    for key, value in args.items():
        rule = props[key]
        if not isinstance(value, str):
            return False
        if "enum" in rule and value not in rule["enum"]:
            return False
        if "pattern" in rule and not re.search(rule["pattern"], value):
            return False
    return True


def score(expected, exp_args, calls, hosted):
    names = [n for n, _ in calls]
    parsed = [load(a) for _, a in calls]
    right = names == [expected] if expected else names == []
    return {
        "selection": (right, 1),
        "args_valid": (sum(valid(n, a) for n, a in calls), len(calls)),
        "args_match": (right and expected is not None and parsed[0] == exp_args,
                       int(right and expected is not None)),
        "superfluous": (bool(names), 1) if expected is None else (0, 0),
        "missed": (not names, 1) if expected else (0, 0),
        "extra_calls": (len(names) > 1, 1) if expected else (0, 0),
        "hosted_per_100": (100 * hosted, 1),
    }


def run_condition(provider, version, choice, web, runs, seed):
    # Swap in a real client here. Each condition gets its own random stream.
    model = FakeModel(provider, f"{seed}:{version}:{choice}:{web}")
    per_case = []
    for _, prompt, expected, exp_args in CASES:
        totals = {}
        for _ in range(runs):
            req = build_request(provider, version, choice, web, prompt)
            got = extract(provider, model.create(**req))
            if got is None:  # a cut-off reply is not a choice: report it
                print(f"cut off, not scored: {prompt[:50]!r}")
                continue
            calls, hosted = got
            for k, (num, den) in score(expected, exp_args, calls,
                                       hosted).items():
                n, d = totals.get(k, (0, 0))
                totals[k] = (n + num, d + den)
        per_case.append(totals)
    return per_case


def ratio(per_case, key, idx):
    num = sum(per_case[i].get(key, (0, 0))[0] for i in idx)
    den = sum(per_case[i].get(key, (0, 0))[1] for i in idx)
    return num / den if den else float("nan")


def interval(per_case, key, boots=2000, seed=0):
    """Bootstrap over cases: runs of one case are not independent."""
    rng, n = random.Random(seed), len(per_case)
    stats = [ratio(per_case, key, [rng.randrange(n) for _ in range(n)])
             for _ in range(boots)]
    stats = sorted(x for x in stats if x == x)  # drop NaN (no eligible case)
    return stats[int(0.025 * len(stats))], stats[int(0.975 * len(stats)) - 1]


def paired_diff(a, b, key, boots=2000, seed=0):
    """Interval for b minus a, resampling the same cases for both."""
    rng, n = random.Random(seed), len(a)
    diffs = []
    for _ in range(boots):
        idx = [rng.randrange(n) for _ in range(n)]
        diffs.append(ratio(b, key, idx) - ratio(a, key, idx))
    diffs.sort()
    return diffs[int(0.025 * boots)], diffs[int(0.975 * boots) - 1]


def fmt(per_case, key):
    point = ratio(per_case, key, range(len(per_case)))
    if point != point:
        return "n/a (no calls)"
    lo, hi = interval(per_case, key)
    return f"{point:.2f} [{lo:.2f}, {hi:.2f}]"


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--provider", choices=["claude", "openai"], default="claude")
    p.add_argument("--runs", type=int, default=5, help="runs per case")
    p.add_argument("--seed", type=int, default=7)
    a = p.parse_args()
    n_tool = sum(1 for c in CASES if c[2])
    print(f"{len(CASES)} cases ({n_tool} need a tool, {len(CASES) - n_tool} "
          f"do not) x {a.runs} runs, provider={a.provider} (fake model)")
    print("95% intervals: bootstrap over cases")
    results = {}
    for label, version, choice, web in CONDITIONS:
        pc = run_condition(a.provider, version, choice, web, a.runs, a.seed)
        results[label] = pc
        print(f"\n{label}")
        print(f"  selection   {fmt(pc, 'selection')}   "
              f"args valid  {fmt(pc, 'args_valid')}")
        print(f"  superfluous {fmt(pc, 'superfluous')}   "
              f"missed      {fmt(pc, 'missed')}")
        hosted = ratio(pc, "hosted_per_100", range(len(pc)))
        print(f"  extra calls {fmt(pc, 'extra_calls')}   "
              f"hosted calls per 100 requests: {hosted:.0f}")
    lo, hi = paired_diff(results["v1 auto"], results["v2 auto"], "selection")
    every = range(len(CASES))
    diff = (ratio(results["v2 auto"], "selection", every)
            - ratio(results["v1 auto"], "selection", every))
    print(f"\nv2 - v1 selection: {diff:+.2f} [{lo:+.2f}, {hi:+.2f}]")
    weak = [(c[0], ratio([pc], "selection", [0]))
            for c, pc in zip(CASES, results["v2 auto"])]
    weak = [f"{cid}:{r:.1f}" for cid, r in weak if r < 1]
    print(textwrap.fill("v2 auto cases below 1.0: " + (", ".join(weak) or
                                                        "none"), 78))


if __name__ == "__main__":
    main()

06. Step 5: Test the scorer before you trust it

A harness with a scoring bug produces confident nonsense. Check the scorer on hand-made responses first: a correct "no call", an extra parallel call, an unknown tool, broken JSON and OpenAI string arguments. As in lesson 4, sed removes the run time from the Ran 5 tests line.

Python · test_eval.py
"""Check the scorer on hand-made responses before trusting its numbers."""
import unittest

from eval_tools import extract, score

ORDER = {"order_id": "ORD-1044"}


def claude(*blocks):
    return {"content": list(blocks), "stop_reason": "tool_use"}


def use(name, args):
    return {"type": "tool_use", "id": "t", "name": name, "input": args}


class ScoreTests(unittest.TestCase):
    def test_no_call_is_right(self):
        calls, hosted = extract("claude", {"content": [{"type": "text"}]})
        s = score(None, {}, calls, hosted)
        self.assertEqual(s["selection"], (True, 1))
        self.assertEqual(s["superfluous"], (False, 1))

    def test_extra_call_counted(self):
        resp = claude(use("get_order", ORDER), use("list_orders", {}))
        s = score("get_order", ORDER, *extract("claude", resp))
        self.assertEqual(s["selection"], (False, 1))
        self.assertEqual(s["extra_calls"], (True, 1))

    def test_unknown_and_bad_args(self):
        resp = claude(use("get_orders", ORDER),
                      use("get_order", {"order_id": "1044"}))
        s = score("get_order", ORDER, *extract("claude", resp))
        self.assertEqual(s["args_valid"], (0, 2))

    def test_broken_json_is_invalid(self):
        resp = {"output": [{"type": "function_call", "name": "get_order",
                            "call_id": "c", "arguments": '{"order_id": '}]}
        s = score("get_order", ORDER, *extract("openai", resp))
        self.assertEqual(s["args_valid"], (0, 1))
        self.assertEqual(s["args_match"], (False, 1))

    def test_openai_args_parsed(self):
        resp = {"output": [{"type": "function_call", "name": "get_order",
                            "call_id": "c", "arguments": '{"order_id": '
                                                         '"ORD-1044"}'},
                           {"type": "web_search_call"}]}
        s = score("get_order", ORDER, *extract("openai", resp))
        self.assertEqual(s["args_match"], (True, 1))
        self.assertEqual(s["hosted_per_100"], (100, 1))


if __name__ == "__main__":
    unittest.main()
Terminal
python3 -m unittest -v test_eval 2>&1 | sed -E 's/ in [0-9.]+s$//'
Expected output (Python 3.12)
test_broken_json_is_invalid (test_eval.ScoreTests.test_broken_json_is_invalid) ... ok
test_extra_call_counted (test_eval.ScoreTests.test_extra_call_counted) ... ok
test_no_call_is_right (test_eval.ScoreTests.test_no_call_is_right) ... ok
test_openai_args_parsed (test_eval.ScoreTests.test_openai_args_parsed) ... ok
test_unknown_and_bad_args (test_eval.ScoreTests.test_unknown_and_bad_args) ... ok

----------------------------------------------------------------------
Ran 5 tests

OK

07. Step 6: Run the comparison

Terminal
python3 eval_tools.py
Expected output (fake model, seed 7)
24 cases (18 need a tool, 6 do not) x 5 runs, provider=claude (fake model)
95% intervals: bootstrap over cases

v1 auto
  selection   0.72 [0.64, 0.79]   args valid  0.95 [0.91, 0.99]
  superfluous 0.33 [0.16, 0.48]   missed      0.02 [0.00, 0.06]
  extra calls 0.07 [0.02, 0.13]   hosted calls per 100 requests: 0

v2 auto
  selection   0.82 [0.76, 0.88]   args valid  0.97 [0.94, 1.00]
  superfluous 0.20 [0.05, 0.40]   missed      0.01 [0.00, 0.04]
  extra calls 0.07 [0.03, 0.11]   hosted calls per 100 requests: 0

v2 none
  selection   0.25 [0.08, 0.42]   args valid  n/a (no calls)
  superfluous 0.00 [0.00, 0.00]   missed      1.00 [1.00, 1.00]
  extra calls 0.00 [0.00, 0.00]   hosted calls per 100 requests: 0

v2 auto+web
  selection   0.90 [0.84, 0.96]   args valid  0.95 [0.89, 1.00]
  superfluous 0.20 [0.07, 0.35]   missed      0.01 [0.00, 0.04]
  extra calls 0.01 [0.00, 0.04]   hosted calls per 100 requests: 17

v2 - v1 selection: +0.10 [+0.01, +0.19]
v2 auto cases below 1.0: c01:0.6, c02:0.8, c03:0.8, c04:0.8, c05:0.8, c07:0.8,
c09:0.8, c12:0.8, c13:0.6, c14:0.8, c15:0.6, c17:0.8, c18:0.8, c20:0.8,
c21:0.4, c23:0.8, c24:0.8

Read the four blocks as answers to the three questions:

  • Did the rewrite help? Selection went from 0.72 to 0.82, and the paired difference is +0.10 with an interval of +0.01 to +0.19. The interval just excludes zero, so the improvement is probably real but could be as small as one point. Note that the two separate intervals overlap; the paired comparison is the right test.
  • Should tools be disabled? With tool_choice none, superfluous calls drop to zero, and selection drops to 0.25: the model is right only on the six requests that needed no tool and misses all eighteen that did. Disabling tools suits a step that must answer from what was already gathered; over-eager calls are fixed in the descriptions and the prompt, then measured again.
  • Is hosted web search worth it here? The fake uses the same decision rules and error rates for client tools with or without web search, yet selection reads 0.82 in one block and 0.90 in the other. That gap is pure run-to-run noise, which is exactly why the intervals matter. What web search did add is 17 provider-run searches per 100 requests, each billed, for an order assistant whose answers come from your own systems. Leave it off.

The weak cases show where to look: c21 ("say that again in simpler words") drew a tool call in three of five runs. Read such transcripts before changing a description.

Run python3 eval_tools.py --provider openai too: the numbers are the same, and only the parsing path differs.

08. Step 6b: See why one run is not enough

Now do what many teams do: run each case once, with five different seeds, and look only at the difference between version 2 and version 1.

Terminal
for s in 1 2 3 4 5; do
  echo "seed $s: $(python3 eval_tools.py --runs 1 --seed $s | grep 'v2 - v1')"
done
Expected output
seed 1: v2 - v1 selection: -0.04 [-0.29, +0.21]
seed 2: v2 - v1 selection: +0.29 [+0.08, +0.50]
seed 3: v2 - v1 selection: +0.08 [-0.12, +0.29]
seed 4: v2 - v1 selection: +0.21 [-0.04, +0.46]
seed 5: v2 - v1 selection: -0.04 [-0.25, +0.17]

Same tools, same cases, same fake model: one single run says the rewrite made things worse by 4 points, another says it gained 29. With one run per case you would ship or revert on noise. More runs per case shrink the noise of each case; more cases shrink the interval of the whole estimate, and usually matter more. Report the number of cases, the number of runs, the model and the date next to every result.

09. Step 7 (optional): Measure a real model

To measure a real model, add the adapter below and replace FakeModel(...) in run_condition with RealModel(provider). Set the model in ANTHROPIC_MODEL (for example claude-sonnet-5-5) or OPENAI_MODEL, and the API key in the usual variable. It needs the provider's SDK and costs money: the default run is 24 cases x 5 runs x 4 conditions = 480 requests. It was not run for this lesson, so there is no expected output. Current Claude models think by default, and thinking counts toward max_tokens, so build_request asks for 16,000. A reply that still stops early (max_tokens, or OpenAI status incomplete) has made no choice yet: run_condition prints it as cut off and does not score it. Repeat the comparison on two or three current models from different vendors if you need to know whether your descriptions work beyond one model.

Python · real_model.py (not run here: needs an API key)
"""Use a real model instead of the fake. Needs an API key and costs money.

In eval_tools.run_condition, replace FakeModel(...) with RealModel(provider).
"""


class RealModel:
    def __init__(self, provider: str):
        self.provider = provider
        if provider == "claude":
            import anthropic  # pip install anthropic; reads ANTHROPIC_API_KEY
            self.client = anthropic.Anthropic()
        else:
            from openai import OpenAI  # pip install openai; OPENAI_API_KEY
            self.client = OpenAI()

    def create(self, **req):
        if self.provider == "claude":
            return self.client.messages.create(**req).to_dict()
        return self.client.responses.create(**req).to_dict()

10. Check your understanding

Practice check · 3 questions

Reading the measurements

Use the harness and the results from this lab. Each question has one best answer.

Q1. In the v2 auto block, selection reads 0.82 [0.76, 0.88] but superfluous reads 0.20 [0.05, 0.40]. Why is the superfluous interval so much wider?
Q2. Why does the harness resample cases for its interval instead of treating all 120 runs as independent trials?
Q3. With tool choice set to none, superfluous calls fall to 0.00. Should the assistant run that way?
Practice only: not graded, not saved, not evidence.

11. Apply it: stretch tasks

  1. The practice report. For the practice project, write 25 labelled requests (at least five that need no tool), run your version 1 and version 2 tool descriptions against one real model with five runs per case, and report selection and argument correctness with intervals, the paired difference, and the five weakest cases.
  2. A confusion count. Extend score to record which tool was called instead of the expected one, and print the most frequent pairs. That tells you which two descriptions to sharpen.
  3. Recovery rate. Combine this harness with the lab 3 loop: after an error result, record whether the model's next call is valid. That turns "useful error messages" into a number you can compare.

12. Review prompt

Without looking back:

  1. Why must a tool-selection benchmark run each case several times, and why does a low temperature not replace that?
  2. Which metrics need the "no tool expected" cases, and what do they tell you about when to allow or disable tools?
  3. What does a paired comparison give you that two separate intervals do not?
  4. Which numbers would you look at before switching on a hosted tool such as web search?

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