rumblr Work in progressWIP

● The AI Primer · Lesson 41 · Part 6: building systems people rely on

Tools

design, validation and safety

This lesson covers How to design a tool so a wrong call is caught before it costs money

Members · open during launch 22 min9 figures and diagrams

What this is

What is a tool?

A tool is a function you let an AI language model ask for, so that its words can turn into an action, such as looking up a record, refunding a payment or sending an email. The language model only writes the request. Your code checks it and decides whether to carry it out, so every safeguard lives in your code. Tool design decides whether that request names the right tool, carries correct arguments and is safe to run.

Why it matters: The moment a language model's output does something rather than says something, a wrong call is visible to a customer, an auditor or a bank. A refund retried after its reply was lost, for one, pays the customer twice unless the tool was built to stop it.

At a glance

Key takeaways

  1. The model only writes a request (tool_use). Your code checks it, runs it and returns a tool_result.
  2. Check both shape (JSON Schema) and meaning (business rules), and return every problem with its fix.
  3. The model picks a tool by its description: say what the tool does, when to use it, and when not to.
  4. A job of calls, each right with probability , succeeds with probability , so fewer, higher-level tools are more reliable.
  5. With a large catalogue, send the model only the tools relevant to each request.
  6. Writes carry idempotency keys, irreversible or high-value actions wait for human approval, and each agent's credentials allow only its job.

How it works, from scratch

A language model can only produce text, so anything it does in the world goes through code you own. Here that code is a tool registry: it holds the tools, shows them to the model, and checks every request the model makes before carrying it out.

Chapter 1

What a tool call is

Picture a new assistant who may not touch anything. When they need something done, they fill in a request form ("refund customer C-100, $20") and hand it to you. You decide whether to carry it out, and hand back a note saying what happened. A language model works with tools the same way. You send it a list of tools, each with a name, a description and the shape of its arguments. When it wants one, it stops and writes a tool call: the tool's name with the arguments filled in, like the form. Here is the whole exchange for "what's 2 + 3?" with one tool, written as the actual messages in the format of Talking to a language model:

you -> model   tools: [{"name": "add", "description": "Add two integers.",
                        "input_schema": {"type": "object",
                          "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
                          "required": ["a", "b"]}}]
               user: "what's 2 + 3?"
model -> you   tool_use {"id": "toolu_1", "name": "add", "input": {"a": 2, "b": 3}}
               stop_reason: "tool_use"          <- "please run this for me"
you            (validate the input, run add(2, 3) -> 5)
you -> model   user: tool_result {"tool_use_id": "toolu_1", "content": "5"}
model -> you   "2 + 3 = 5."   stop_reason: "end_turn"

The input_schema is a JSON Schema, a JSON document that describes the shape other JSON must have: which fields exist, what type each is, and which are required. It is the blank form the model fills in.

Figure 1 · Diagram

Reading it: follow the arrows from top to bottom. The model never talks to the real system; everything it writes goes to your code first. The arrow that loops back on your code, "check the form", is where every safeguard runs. That split is what keeps the system safe: a model can be wrong or tricked, and your code is where you enforce what is allowed.

In code: ToolRegistry.register adds a tool, ToolRegistry.definitions lists them for the model, and ToolRegistry.call runs a call through the checks. View source

Chapter 2

Validate every call before running it

The first thing your code does with a call is check it, the way a bank clerk checks a withdrawal slip twice. First, is it filled in properly: every box, a real date, a positive amount? Then, does it make sense: does the account exist, and does it have the money? For a tool call, the first check is the JSON Schema and the second is your business rules.

Take a payment tool with an amount, a currency (EUR, GBP or USD) and an optional pay_on date. The model sends {"ammount": 5, "currency": "usd", "pay_on": "next friday"}. The validator returns every problem at once, each saying what a correct value looks like:

$: missing required field 'amount'
$: unexpected field 'ammount' (allowed: amount, currency, pay_on)
$.currency: must be one of ['EUR', 'GBP', 'USD'], got 'usd'
$.pay_on: 'next friday' does not match the required format. Expected: date as YYYY-MM-DD

Given these four lines, the model can fix all four mistakes in one retry. Given only invalid input, it has to guess.

Passing the schema is not enough. "C-999" matches the pattern ^C-\d+$ and still names a customer that doesn't exist. With the Claude API you can mark a tool definition "strict": true, and the API then guarantees that the model's arguments match the schema (Structured output explains how such guarantees work). That settles the shape, not the truth, so the business-rule check stays.

A full registry runs these two checks among others, in the order below. The last three (dry run, approval and the idempotency key) guard calls that change something, and are explained with the other safeguards at the end.

Figure 2 · Diagram

Reading it: a call enters at the top and must pass every diamond to reach run the tool at the bottom. Each exit from a diamond ends in a named status, and each returns text the model can act on. Permissions come before anything that reveals how the tool works, and cheap checks come before expensive ones. Approval and idempotency sit last, next to the action they protect.

In code: validate checks a value against a subset of JSON Schema and returns every problem with its path. ToolRegistry.call runs the checks in the order shown and returns a ToolOutcome, and definitions(strict=True) adds the strict flag. View source

Chapter 3

Descriptions are prompts

A call can pass every check and still be to the wrong tool. The model chooses a tool by reading its name and description, so the description is a prompt. Label a wall of drawers "stuff", "things" and "items", and even a careful person opens the wrong one; label them "Policies (PTO, travel, VPN). Not customers", and nobody hesitates.

To measure this without a real model, a stand-in picks the tool whose name and description share the most words with the request. For "billing status for customer 1042", the vague descriptions share no words with any tool, a three-way tie, so the stand-in takes the first. The precise description of lookup_record shares "billing", "status" and "customer", and wins.

Figure 3 · Chart

vague descriptions precise descriptions 0 1 2 3 4 5 6 requests routed to the right tool Same model, same requests, new descriptions 2/6 6/6

Vague descriptions pick the right tool for 2 of 6 requests; precise descriptions of the same tools get all 6 right

Reading it: two bars, one per set of descriptions, each scored on the same six labelled requests. The vague set gets 2 of 6, and those two are the requests that belong to the first tool, which the stand-in picks whenever it can't tell the tools apart. The precise set says what each tool is for, when to use it and when not to, and gets 6 of 6. Only the descriptions changed.

A real model reads far better than a word count, but it chooses from the same text, so the same fixes help it: precise descriptions, few parameters, an enum wherever the values form a closed set, and error messages that say how to fix the call.

In code: pick_tool is the stand-in, and selection_accuracy scores it on VAGUE_TOOLS and PRECISE_TOOLS. View source

Chapter 4

Fewer, higher-level tools

Every choice the model makes is a chance to choose wrong, so the number of calls a job takes matters too. Asking an assistant to "book my trip to Denver" is safer than dictating five separate forms (find a flight, hold a seat, find a hotel, reserve a room, add it to the calendar), because every hand-off is another chance to drop something.

Figure 4 · Diagram

Reading it: with five low-level tools, the model has to pick each one in the right order and carry each output into the next input itself. With one high-level tool, the same work is a single call, and the sequencing lives in ordinary tested code.

If each call is right with probability , independently of the others, a chain of calls all succeed with probability:

The formula and its symbols

Symbols

Symbol Meaning
probability that one call is chosen and filled in correctly
number of calls in the chain

In words: multiply the per-call success rate by itself once per call.

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

On the example: with and , , so about 1 run in 7 fails. With one high-level call it's .

In Python:

p = 0.97
# five calls that must all succeed
round(p ** 5, 3)  # → 0.859
# about 1 run in 7 fails
round(1 - p ** 5, 2)  # → 0.14
# one high-level call
p ** 1  # → 0.97

Figure 5 · Chart

2.5 5.0 7.5 10.0 12.5 15.0 17.5 20.0 calls in the chain (n) 0.0 0.2 0.4 0.6 0.8 1.0 P(every call succeeds) = p^n Reliability compounds: fewer, higher-level tools p = 0.90 per call p = 0.95 per call p = 0.97 per call p = 0.99 per call

Success falls with every extra call: at 99% per call twenty calls succeed about 82% of the time, at 90% ten calls barely a third

Reading it: the x-axis is how many calls the job takes, and the y-axis is the chance the whole job succeeds. Each curve is one per-call reliability. Even at 99% per call, twenty calls succeed only about 82% of the time; at 90% per call, ten calls succeed barely a third of the time.

In code: chain_success evaluates . View source

Chapter 5

Too many tools: load only the relevant ones

Merging tools shortens the chains, but a real product still collects many tools, and a long list makes each choice harder. Selection accuracy drops as the list grows past a few dozen tools, and every definition costs input tokens on every call. So send only the tools a request needs, the way you would hand a plumber the five tools for today's job rather than send them into a warehouse of 500.

Take a catalogue of 30 tools and the request "I forgot my password and I'm locked out". The request is embedded, compared with every tool description, and only the top 5 tools go to the model, with reset_password first.

Figure 6 · Diagram

Reading it: this is the same search as in Retrieval, with tool descriptions as the documents. The catalogue is embedded once, ahead of time; each request costs one embedding and a lookup of the top matches.

Figure 7 · Chart

reset_password enroll_mfa check_vpn_status renew_device_certificate request_laptop report_phishing fix_printer submit_expense book_travel get_per_diem request_pto get_pto_balance report_sick_day request_parental_leave get_payslip get_salary_band start_onboarding list_invoices list_payments reconcile_invoices create_invoice send_email search_policies open_ticket close_ticket get_org_chart book_meeting_room order_office_supplies translate_text summarize_document I forgot my password and I'm locked out submit my car mileage expense how many vacation days are left suspicious email asking for my login reconcile vendor invoices for Q3 Cosine similarity: each request lights up a few tools −0.2 0.0 0.2 0.4 0.6 0.8

Each request is similar to only a small cluster of related tools and dim against the rest of the catalogue

Reading it: each row is a user request and each column a tool from the catalogue, and brighter cells are more similar. Each request lights up a small cluster of related tools and stays dark everywhere else. Sending only that cluster keeps the model's choice small however large the catalogue grows.

Two other designs do the same job: route the request to a sub-agent that holds only the relevant tools, or use a provider's built-in tool search.

In code: select_tools ranks the catalogue against the request and returns the top matches. View source

Chapter 6

Safety: idempotency, dry runs, approval, least privilege

With the right tool and valid arguments, a call can still do harm. It can run twice, it can be impossible to undo, or it can come from a model that was tricked. Four safeguards deal with these.

Idempotency. An operation is idempotent when doing it twice has the same effect as doing it once, like pressing a lift button twice. A refund is not, and agents retry. Suppose a refund call times out after the bank has processed it: the agent cannot tell, so it retries. The fix is an idempotency key, a unique id the caller sends with each write. The registry stores the result under that key, and a call that repeats the key gets the stored result back.

Figure 8 · Diagram

Reading it: the first reply is lost on its way back (the crossed arrow), so the agent cannot know the refund happened, and it retries. The retry carries the same key, so the registry returns the stored result instead of refunding again. Without the key, the customer gets $40.

Dry run. A dry run passes every check, then describes the action instead of doing it. It serves previews and shadow-mode rollouts (Safe deployment).

Human approval. Some actions should wait for a person, as spending over a limit waits for a manager's signature. Irreversible actions, or ones over a threshold such as refunds over $500, park as awaiting_approval until a person decides.

Figure 9 · Diagram

Reading it: the approval gate sits between the model's request and the action, and both branches return text the model can act on. The declined message says "do not retry" because otherwise a persistent model asks again.

Least privilege. Give each agent credentials for its own job only, the way a valet key starts the car but won't open the boot. Credentials come as scopes, named permissions such as payments:write. An agent that reads tickets holds tickets:read, so even if a malicious email tricks it, it cannot issue refunds.

In code: a Tool carries the scopes it needs, whether it reads, writes or acts irreversibly, and an optional approval rule. ToolRegistry.call enforces them, given the caller's credentials, an idempotency key, a dry-run flag and an approver. View source

Test yourself

4 questions

Answer each one out loud or on paper before you open it.

Question 1Q: How do you design tools so the model picks the right one with correct arguments?Think it through, then reveal

A: Give each tool one clear job and a description that says what it does, when to use it and when not to. Keep parameters few, use enums for closed sets, and put the format in the schema description ("date as YYYY-MM-DD"). Prefer one high-level tool over several low-level ones. Validate every call and return actionable errors so the model can self-correct. Measure tool selection accuracy in evals, and load tools dynamically when there are many.

Question 2Q: The schema says customer_id must match ^C-\d+$. Is that enough validation?Think it through, then reveal

A: No. The schema checks shape, not truth. C-999 is well-formed and may not exist. Add a business-rule check before acting, and return an error that tells the model how to find the right id.

Question 3Q: A refund call timed out. Should the agent retry?Think it through, then reveal

A: Only if the call is idempotent. Send an idempotency key with every write, and the retry returns the original result instead of refunding twice.

Question 4Q: Why not give the agent one admin credential for everything?Think it through, then reveal

A: Blast radius. If the agent is tricked (for example by prompt injection in a document it reads), it can do anything the credential allows. Scope credentials per tool and per agent, and put irreversible actions behind human approval.

Primary sources

The papers behind this lesson

Schick et al., Toolformer: Language Models Can Teach Themselves to Use Tools (2023).

It showed a language model can learn when to call an API, which one and with what arguments, by keeping only the self-generated calls that made its predictions better, which is the idea behind tool calling being trained into today's models.

Read on rumblr →The paper

Researcher's shelf

Further reading

  • Anthropic, Writing effective tools for agents: https://www.anthropic.com/engineering/writing-tools-for-agents
  • Anthropic, Building effective agents (appendix on prompt-engineering tools): https://www.anthropic.com/engineering/building-effective-agents
  • Claude tool use overview: https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview
  • Implementing tool use: https://docs.claude.com/en/docs/agents-and-tools/tool-use/implement-tool-use
  • Understanding JSON Schema: https://json-schema.org/understanding-json-schema
  • Stripe, idempotent requests: https://docs.stripe.com/api/idempotent_requests

About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.