Module: L3-M02 · Duration: ~120 min (estimate, including the independent exercise) · Previous: L01 · Next: L03
1. Introduction
A well-formed tool contract (L01) is not enough: the agent must also choose correctly. On each turn the model decides whether to call a tool and, if so, which one. This decision can go wrong in three different ways: calling the wrong tool, not calling one when it should, and calling one when it should not. With a read-only tool the last error only costs time; with a write tool or a tool that sends something outside, it can become a real effect.
This lesson teaches how to design and run a tool selection test suite: cases whose expectation is "the right tool", "no tool" or "ambiguous", a scoring function with five verdicts, and two side measurements (sensitivity to listing order, consistency over differently worded requests). The "model" in the lab is a simulated policy: a deterministic function written by the lab author, each with a known fault; no real model is called and no number describes a real model. The lesson builds on L3-M01-L01 (policies and tools in a sandbox) and L1-M05-L03 (tool_choice).
2. Learning objectives
- Tell apart the three kinds of expectation (right tool, no tool, ambiguous) and the five verdicts of the scoring function. Read: §4.1, §5.2.
- Design a tool selection suite that has "no tool" cases and ambiguous cases. Practice: §8.3 (lines 1 and 2, the two added cases), §9 (TODO 3).
- Run the suite on the simulated policies and read the rate as a fraction together with each case's verdict. Practice: §8.2, §8.3 (lines 1 and 2).
- Measure sensitivity to listing order and consistency over differently worded requests. Practice: §8.3 (lines 3 to 5).
- Fix a tool description to change the selection result, and state why the result holds only for the case set and the simulated policy. Practice: §9 (TODO 1 and 2).
- State what a tool selection suite does not say. Read: §6.1.
3. Prerequisites and tools
- L01 (tool contract, description lint), L3-M01-L01 (simulated policies, end-state oracle), L1-M05-L03 (
tool_choice), L2-M01-L04 (confidence interval). The lab code iscode-labs/l3-m02; it needs onlypytest. - Separating the senses. Tool selection is the decision of one turn: which tool to call, or none, or ask back; it differs from the "plan" of L3-M01-L03 (a sequence of steps). A policy is a simulated function, not a model. The oracle is how pass or fail is decided; in this lesson it is each case's expectation table.
judgehere is a deterministic function that compares an answer with that table, not the model-based judge of L2-M04. An ambiguous case is one with several acceptable answers; it differs from an edge case (sitting right at the threshold of a constraint). A verdict is the result label of one case. - The earlier policy still stands: offline, fake tools or a sandbox. Lints and validators only flag; the loop guard blocks the run; a person decides.
4. Concept explanation
4.1 Three kinds of expectation, five verdicts
Each case has a user sentence (in English, because the fictional "users" of ThuVien Mini write English) and an expectation:
- tool: exactly one tool is the answer (
expected); - none: no tool should be called (thanks, a greeting, a question out of scope);
- ambiguous: there is a list of accepted answers (
acceptable), which may includeask(ask the user back).
The policy returns tool with a name, or none, or ask. The scoring function returns one of five verdicts: pass; wrong_tool (tool A was needed, tool B was called); missed_call (a tool was needed, but none was called or the policy asked back); spurious_call (no tool was needed, but one was called); bad_choice (an ambiguous case answered outside the list). Splitting the verdicts matters more than one overall rate, because the three errors have different consequences.
4.2 Why "no tool" cases and ambiguous cases
A suite with only "needs a tool" cases gives a high score to a policy that always calls a tool. A "no tool" case catches a needless call, and OWASP lists excessive functionality and excessive autonomy among the three root causes of excessive agency [R3]. An ambiguous case such as "Can S0042 borrow B004?" is a question, not a command: calling borrow_book changes state when the user only asked; asking back or using get_book is acceptable. The acceptable entry records the case designer's decision, and that decision can be argued with; that is why an ambiguous case needs a reader, not a single number.
4.3 What the documentation says about tool selection
The Claude documentation has tool_choice with four values auto, any, tool, none (taught in L1-M05-L03) and adds that not every model or setting supports forcing a tool [R1]. The OpenAI page has the corresponding values, plus allowed_tools (restricting to a subset) and parallel_tool_calls: false to call zero or one tool [R2].
The consequence for a tester: forcing a tool tests the tool body, not the selection. A tool selection suite must run in auto mode, because that is the path the real product uses. The lab calls no API, so it can only simulate the logic of the suite, not how a real model chooses. The pages also advise stating clearly when to use and not use a tool (L01), merging related operations into fewer tools, prefixing names by service [R1], and keeping the initial number of tools small: OpenAI suggests fewer than 20 functions but calls it a soft suggestion [R2]. When combining tools from several servers, the MCP specification notes that two servers may both have a tool named search and advises a way to tell them apart, such as adding the server name as a prefix [R4].
5. Technical deep dive
5.1 Five simulated policies
lab/selection.py has five policies, each with a known fault (all are simulations):
overlap: picks the tool whose name plus description shares the most words with the user sentence (stop words removed); on a tie it takes the tool listed first; if no word is shared it picks none.eager: likeoverlapbut never answers "no tool": with no shared word it takes the first tool in the list.rules: seven keyword rules in order, first match wins. Known fault: the word "about" sends every sentence "about ..." tosearch_books, including sentences that need no tool.cautious:rulesplus one guard: if the sentence has a question mark and the chosen tool is not a read tool (by theeffectfield), ask back.noisy:rules, but when a number drawn from the SHA-256 of the seed and the case id is below 1/10, it takes the next tool in the list (a seeded slip; it does not use therandommodule).
5.2 The scoring function and the measurements
judge(case, answer) returns the five verdicts of §4.1. run_suite runs one policy over every case. summarize returns the number of passed cases, the Fraction rate, the rate per kind of case, the verdict counts and the confusion matrix (kind, chosen). order_sensitivity reruns with the tool list reversed and returns the ids of the cases whose choice changed: a choice that changes with listing order does not come from the description. consistency runs the differently worded requests of a case (variants) and returns the fraction that matched the original sentence.
5.3 Reading the results of the 15-case suite
The data/selection_cases.json suite has eight "tool" cases, four "no tool" cases and three ambiguous cases. Results (see §8.2): overlap 13/15, eager 9/15, rules 13/15, cautious 14/15, noisy 11/15 (with seed 0). eager fails all four "no tool" cases (spurious_call) and two ambiguous cases. rules fails one "no tool" case (c11, because of the word "about") and one ambiguous case (c14, choosing borrow_book for a question). cautious fixes c14 with its ask-back guard, but still fails c11.
overlap is different: 13/15 hides a weakness (the consistency in §8.2 part C only measures agreement with the choice for the original sentence, not correctness). With the list reversed, five cases change their choice (c01, c02, c07, c13, c14). Two causes are visible in the data. One: the get_book description has the phrase "(use search_books)", and because tool names are split on underscores, the word books appears in both descriptions; case c07 ("Find books by Lan Huong.") ties between the two tools and the order decides. Two: c01 ("Which books...") is a three-way tie (search_books and get_book both have books, read_document has have), so fixing the reference does not rescue it. Replacing the reference with "the catalogue search tool" only takes c07 off the list (§8.3, lines 3 and 4).
6. The QA perspective
6.1 What this suite does not say
- Consistency is not correctness: the original sentence can also be wrong.
- Fifteen cases is a small sample. The gap between 13/15 and 14/15 is a single case; it is not enough to say which policy is better. L2-M01-L04 taught the confidence interval; at this sample size the interval is very wide.
- The policies are functions written by the author together with the cases. A real model does not choose by counting shared words, so every rate here belongs to the simulation, not to any model or vendor.
- The cases are English only; accented words and unusually capitalized words have not been tried. The suite does not yet check whether parameters are correct (L03), several tools in one turn or parallel calls, or multi-turn context.
- A description edited to pass ten cases may not pass ten other cases. The suite measures the effect of a description on the cases that exist; it does not prove the description is "good".
- The
acceptablelist of an ambiguous case is the designer's decision; two people may differ.
6.2 Designing the case set
- Include all three kinds of expectation, including "no tool" cases close to the real tool's domain (a question about the library that needs no tool).
- Every write tool (
effectother thanread) has at least one ambiguous case in the form of a question. - Every important case has a few different wordings; report consistency, not only the result for the original sentence.
- Rerun with the list reversed and with one tool removed; record which cases change.
- Report the fraction and each case's verdict, not just one rate.
- Every selection error met in the wild becomes a new case in the suite. The lints and tests here only flag; a person decides whether to fix a description, change a tool or accept the error.
7. Real-world scenarios
Scenario 1 (fictional): "A question that reads like a command". The ThuVien Mini assistant (fictional) meets "Can S0042 borrow B004?" and calls borrow_book; book B004 is already on loan so the tool returns an error, but for an available book it would lend it when the student only asked. A tool selection test with an ambiguous case whose accepted list is get_book or ask back catches the fault before the effect happens; the cautious guard "ask back when it is a question and the tool writes" is one fix, and the decision to use it belongs to a person.
Scenario 2 (fictional): "A reference line changes the result". An editor adds "(use search_books)" to the get_book description to help the model. The functional tests stay green, but the tool selection suite shows that the number of cases that change their choice when the list order is reversed rises from four to five (with the overlap policy, §8.3 lines 3 and 4). One added sentence in a description can change the choice, so every description change reruns the case set.
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l3-m02
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 67 passed
8.2 Run the demo
python -m lab.demo l02
Output (copied from a real run on Python 3.14.6 and 3.12.14, 2026-11-04; the two versions give identical output). Every policy is simulated:
A. selection suite, 15 cases (8 tool, 4 none, 3 ambiguous) on SIMULATED policies
overlap: passed=13/15 rate=13/15 verdicts={'bad_choice': 2, 'pass': 13}
eager: passed=9/15 rate=3/5 verdicts={'bad_choice': 2, 'pass': 9, 'spurious_call': 4}
rules: passed=13/15 rate=13/15 verdicts={'bad_choice': 1, 'pass': 13, 'spurious_call': 1}
cautious: passed=14/15 rate=14/15 verdicts={'pass': 14, 'spurious_call': 1}
noisy: passed=11/15 rate=11/15 verdicts={'bad_choice': 1, 'pass': 11, 'spurious_call': 1, 'wrong_tool': 2}
B. which cases change when the tool list is reversed
overlap: ['c01', 'c02', 'c07', 'c13', 'c14']
eager: ['c01', 'c02', 'c07', 'c09', 'c10', 'c11', 'c12', 'c13', 'c14']
rules: []
C. consistency over paraphrases
overlap: {c01: 1, c02: 1/2, c03: 1/2, c05: 1/2}
rules: {c01: 1, c02: 1, c03: 1, c05: 1/2}
D. what rules does when borrow_book is removed from the listing
[('c03', 'missed_call'), ('c11', 'spurious_call'), ('c14', 'bad_choice')]
E. noisy policy over 20 seeds
slips=23 of 300 answers
Reading the output: part A is the result of the five policies; part B lists the cases that change their choice when the order is reversed (rules changes none); part C is consistency over differently worded requests (c02 has two wordings, and overlap is right on half); part D removes borrow_book from the listing and c03 becomes missed_call; part E counts 23 slips over 300 answers.
8.3 Try it yourself
Save it as try_l02.py in the lab's root directory (next to lab/, not inside lab/), run python try_l02.py, then delete the file:
import copy
from lab import data, selection as SEL
tools, cases = data.load_tools(), data.load_json("selection_cases.json")
extra = {"id": "x1", "text": "Which school has the largest library in the city?", "kind": "none"}
amb = {"id": "x2", "text": "Can S0042 keep B002 longer?", "kind": "ambiguous", "acceptable": ["ask"]}
for name in ("rules", "overlap"):
r = SEL.run_suite(SEL.POLICIES[name], tools, cases + [extra, amb])
print(name, SEL.summarize(r)["passed"], len(r), [x["verdict"] for x in r[-2:]])
print(SEL.order_sensitivity(SEL.policy_overlap, tools, cases))
tools2 = copy.deepcopy(tools)
tools2[1]["description"] = tools2[1]["description"].replace("(use search_books)", "(use the catalogue search tool)")
print(SEL.order_sensitivity(SEL.policy_overlap, tools2, cases))
print({k: str(v) for k, v in SEL.consistency(SEL.policy_overlap, tools, cases).items()})
Output (Python 3.14.6 and 3.12.14 identical):
rules 14 17 ['pass', 'bad_choice']
overlap 13 17 ['spurious_call', 'bad_choice']
['c01', 'c02', 'c07', 'c13', 'c14']
['c01', 'c02', 'c13', 'c14']
{'c01': '1', 'c02': '1/2', 'c03': '1/2', 'c05': '1/2'}
Reading: lines 1 and 2 add two cases: x1 ("Which school has the largest library in the city?", no tool needed) and x2 ("Can S0042 keep B002 longer?", ambiguous, only asking back is accepted). rules passes x1 because no rule matches, but chooses get_book for x2 (bad_choice); overlap fails x1 because school and library appear in the descriptions of a few tools. Line 3: five cases are order-sensitive with the original descriptions. Line 4: removing the search_books reference from the get_book description leaves four cases (c07 is no longer sensitive). Line 5: the consistency of overlap on the cases that have differently worded requests (c01 is a full 1, the other three are one half).
8.4 Run the lesson's tests
python -m pytest tests/test_l02_selection.py -v
Result: 8 passed. Read test_judge_table_covers_every_verdict, test_overlap_depends_on_listing_order_and_rules_does_not and test_noisy_policy_is_seeded_and_slips_about_one_in_ten. The tests run on in-memory values; no network or model is called.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| The rate changes when you add a case | The rate is a fraction over the cases that exist | Compare each case's verdict, not the rates |
order_sensitivity returns a different list than expected |
The tool list you passed differs from the lab's list | Print [t["name"] for t in tools] and compare |
9. Independent exercise
Problem: Ten fictional ThuVien Mini cases run on the overlap policy. Predict where the policy goes wrong, change descriptions to fix it, and find new cases that expose its weakness.
Requirements: complete exercises/test_l02_selection.py:
- TODO 1:
PREDICT: the verdict of each case inexercises/ex_selection_cases.jsonwhen runningpolicy_overlapwith the tool list in the lab's order. Compute the shared words by hand for three or four chosen cases (not all ten) before running. - TODO 2:
NEW_DESCRIPTIONS: new descriptions for the tools you change. After the change, all ten cases must pass with the list in the lab's order and in reversed order; each new description lints clean and is at most 400 characters long; the registry after the change has noAMBIGUOUS_PAIRorDESC_UNKNOWN_REF. - TODO 3:
NEW_CASES: two "none" cases (withid,text,kind) not yet in the suite, for whichpolicy_overlapreturnsspurious_callandpolicy_rulesreturnspass.
Test data: exercises/ex_selection_cases.json (ten fictional cases).
Deliverable: the three variables above, in the file exercises/test_l02_selection.py itself.
Acceptance criteria: python -m pytest exercises/test_l02_selection.py passes (3 tests). The tests do not check that the new descriptions are good for other cases or for a real model (the policy is a simulation).
Hints: TODO 1: for each case, list the words that are not stop words and intersect them with the words in each tool's name and description; watch for ties. TODO 2: check the references between tools inside descriptions too; fix the noise before adding words. TODO 3: find a common word in the descriptions of several tools that no rules rule matches.
10. Knowledge check
0/16 done · Results are kept in this browser only.
P02 · True or false
P04 · Select all that apply
P05 · Put in order
P06 · Match
P07 · Spot the bug
A colleague rewrote judge to add to the product's test suite. The function has one bug that makes the verdict for a "no tool" case wrong when the policy asks the user back. Find it.
def judge(case, answer):
chosen = answer["tool"] if answer["action"] == "tool" else answer["action"]
if case["kind"] == "tool":
return "pass" if chosen == case["expected"] else ("missed_call" if chosen in ("none", "ask") else "wrong_tool")
if case["kind"] == "none":
return "pass" if chosen == "none" else "spurious_call"
return "pass" if chosen in case["acceptable"] else "bad_choice"P08 · Short answer
A colleague edits the get_book description and reports (simulated, overlap): "Picks the tool better, from 9/10 to 10/10 cases in my set of ten cases." State three things to ask or do before accepting the conclusion.
P09 · Essay
Write 5-8 sentences (fictional scenario): ThuVien Mini adds a tool renew_loan (extends one loan, kind write). Describe the tool-selection case set you add for this tool: which kinds of cases, at least two concrete example sentences, the acceptable list of one ambiguous case, the tool_choice mode when running, and what the case set still does not say.
P11 · Recall
Lesson: L2-M01-L04P12 · Recall
Lesson: L3-M02-L01P13 · Multiple choice
P14 · Select all that apply
P15 · Fill in the blank
P16 · True or false
11. Summary
- Concepts: three kinds of expectation and five verdicts; "no tool" cases and ambiguous cases; tool selection differs from forcing a tool [R1][R2].
- Skills: running the case set on simulated policies; reading the fraction and each case's verdict; measuring order sensitivity and consistency.
- Traps: only "needs a tool" cases; comparing two rates that differ by one case; tuning a description to the cases and calling it good; forcing a tool and calling selection tested.
- You can now: look at a tool selection suite and ask: are there "no tool" cases and ambiguous cases, does the result depend on order, and is this number from a simulated policy or a real system.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | Define tools (Claude Platform Docs) | Anthropic | https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools | 2026-11-04 | Read the page text: tool_choice, best practices (merging tools, name prefixes); did not run the sample code |
| R2 | Function calling (OpenAI API guides) | OpenAI | https://developers.openai.com/api/docs/guides/function-calling (via redirect from platform.openai.com/docs/guides/function-calling) | 2026-11-04 | Read the page text: tool choice, parallel calls, best practices; did not read all the per-language examples |
| R3 | LLM06:2025 Excessive Agency (OWASP Gen AI Security Project) | OWASP | https://genai.owasp.org/llmrisk/llm062025-excessive-agency/ | 2026-11-04 | Read the page text: definition, three root causes, example risks and mitigations 1 to 7; did not read the rest |
| R4 | Tools (MCP specification, revision 2026-07-28) | Model Context Protocol | https://modelcontextprotocol.io/specification/2026-07-28/server/tools | 2026-11-04 | Read the page text, to the end: the Tool Names section (name collisions between servers) |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Tool selection | Chọn tool: quyết định của một lượt, gọi tool nào, không gọi, hay hỏi lại |
| Missed call / spurious call | Gọi hụt (cần tool mà không gọi) / gọi thừa (không cần mà gọi) |
| Ambiguous case | Ca mơ hồ: có nhiều đáp án chấp nhận được, ghi trong acceptable |
| Order sensitivity | Độ nhạy thứ tự: lựa chọn đổi khi đổi thứ tự liệt kê tool |
| Consistency (over paraphrases) | Độ nhất quán qua cách diễn đạt khác |