Sub topic 1
How a Model Sees and Calls Your Tools
Prerequisites
This chapter assumes you have:
- Basic familiarity with calling an LLM API (sending messages, reading a response).
- Comfort reading and writing JSON.
- A working knowledge of JSON Schema types: string, integer, object, array.
- Enough Python to read short examples.
You do not need to have built a tool-calling agent before. This chapter gives you the mental model that the rest of the tutorial builds on.
What a tool is, from the model's side
A language model cannot run code, query a database, or call your API. It can only produce text. Tool calling is a protocol that lets the model produce structured text that your program recognizes as a request: "run this function with these arguments."
Your program runs the function, then sends the result back to the model. The model reads the result and either answers the user or asks for another tool call.
The model never sees your function body. It sees only what you put in the tool definition: a name, a description, and an input schema (a JSON Schema object describing the arguments). Everything the model knows about when to use a tool and how to fill its arguments comes from those three parts. If the definition is vague, the model guesses.
The tool-calling loop
One round of tool use has these steps:
- You send the user's message plus a list of tool definitions to the model.
- The model decides whether to answer directly or call a tool.
- If it calls a tool, the response contains the tool name and a JSON object of arguments. The model stops and waits.
- Your code validates the arguments, runs the tool, and captures the output.
- You send the output back as a tool result message.
- The model reads the result and either answers or calls another tool.
This repeats until the model produces a final answer.
Two points matter for design:
- The model does not execute anything. Your application is in control at every step. This is why you can, and must, validate arguments before running a tool.
- The loop can run several times for one user message. Each tool result goes back into the conversation, so what you return shapes the model's next decision.
What the model actually receives
Providers differ in wire format, but the idea is the same. Your tool definitions are placed into the model's context, typically rendered into the prompt by the provider. The model reads them as text, much as it reads the user's message.
This has consequences:
- Tool definitions cost tokens on every request. A large set of tools with long descriptions takes space away from the conversation.
- The model chooses based on language. A good name and a clear description matter more than clever schema structure.
- There is no hidden understanding. If a distinction exists only in your head, such as "use this tool for refunds, not returns," the model cannot see it unless you write it down.
The three parts of a definition
Here is a well-formed definition. It is shown in the Anthropic-style input_schema layout. OpenAI-style APIs name this field parameters, and the content is otherwise the same idea.
{
"name": "search_orders",
"description": "Search a customer's orders by status and date. Use this when the user does not give an order ID. If the user gives an order ID, use get_order instead. Returns up to `limit` orders, newest first, each with id, status, total, and created_at.",
"input_schema": {
"type": "object",
"properties": {
"customer_id": {
"type": "string",
"description": "Customer ID, for example 'cus_4821'. Ask the user if you do not know it."
},
"status": {
"type": "string",
"enum": ["pending", "shipped", "delivered", "cancelled"],
"description": "Only return orders with this status. Omit to include all statuses."
},
"created_after": {
"type": "string",
"description": "Only return orders created on or after this date, in YYYY-MM-DD format."
},
"limit": {
"type": "integer",
"minimum": 1,
"maximum": 50,
"description": "Maximum number of orders to return. Defaults to 10 if omitted."
}
},
"required": ["customer_id"]
}
}Reading it as the model would:
- Name:
search_orderssays what the tool does and on what. - Description: it states the purpose, when to use the tool, when to use a different one (
get_order), and what comes back. - Schema:
customer_idis required.statusis limited to four values.limitis bounded. Each parameter says its format or default.
Compare it with a weak definition:
{
"name": "do_order_thing",
"description": "Handles orders.",
"input_schema": {
"type": "object",
"properties": {
"data": { "type": "string" },
"mode": { "type": "string" }
}
}
}The model cannot tell what this tool does, when it applies, or what data and mode should contain. It must guess, and guesses vary from call to call. Later chapters take each part of the good definition apart. For now, notice that every line in the first example answers a question the model would otherwise have to guess.
Where choices go wrong
Tool-calling failures fall into a few groups. Knowing them tells you which part of the definition to fix.
| Failure | Typical cause | Where to fix it |
|---|---|---|
| Model calls no tool when it should | Description does not say when to use the tool | Description |
| Model calls the wrong tool | Two tools overlap, or names are vague | Names, descriptions |
| Model calls a tool when it should answer directly | Description is too broad | Description boundary |
| Arguments have the wrong format | Parameter has no format hint or enum | Schema, parameter descriptions |
| Model invents an ID or value | Required value is not obtainable and nothing says to ask | Parameter description |
| Model repeats the same failed call | Error message gives no way forward | Error messages |
Most of these are fixed by editing text, not code. That is the main idea of this tutorial: the definition is an interface for a reader that happens to be a model.
Schemas guide the model but do not guarantee correctness
A schema constrains what the model is likely to produce. It does not make bad arguments impossible. Depending on the provider and settings, the model may emit a value that breaks a constraint, omit a required field, or send a plausible but wrong value that is still valid, such as an ID that does not exist.
So your tool code must treat arguments like any other untrusted input. This tool checks its argument and returns an error that tells the model what to do next:
ORDERS = {
"ord_1001": {"id": "ord_1001", "status": "shipped", "total": 42.5},
}
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."
),
}
order = ORDERS.get(order_id)
if order is None:
return {
"is_error": True,
"message": f"No order found with id {order_id!r}. Check the ID with the user or use search_orders.",
}
return {"is_error": False, "order": order}Notice the error text. It states what was wrong, shows the expected format, and names the next tool to try. The model reads this as the tool result and can recover on the next turn. Errors and validation get their own chapters.
Measuring instead of guessing
Tool selection is probabilistic. A definition that works for one prompt may fail for another. To see whether a change helps, run the same set of prompts before and after and compare. This minimal harness does that. You supply choose_tool, which wraps your own model call and returns the name of the tool the model called, or None if it answered without one.
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 failuresThe third case matters. A good test set includes prompts where no tool should be called, because over-eager tool use is a real failure. The final chapter covers building and growing such a set.
How the rest of this tutorial maps to the loop
Each later topic improves one point in the loop:
- Choosing a tool (step 2): names, descriptions, granularity, overlap.
- Filling arguments (step 3): schemas, parameter descriptions, enums, required fields.
- Running safely (step 4): server-side validation.
- Reading results (steps 5 and 6): result shape, error messages, context cost.
- Checking it all: provider differences and evaluation.
Exercise
A user asks "Where is order ord1001?" and the model calls searchorders with only a customer_id, then reports it cannot find the order. Which parts of the definitions would you inspect first, and what would you change?
Show answer
Inspect the descriptions of getorder and searchorders. The searchorders description should say to use it only when the user gives no order ID and to use getorder when an ID is present, and getorder should say it is the tool to use when an ID is given. Also check that the names are distinct and that the orderid parameter in getorder describes the 'ord1001' format, so the model can match the ID in the user's message to that parameter. Then add this prompt to a test set and confirm the model now picks get_order.
Exercise
The model sends status="Shipped" (capitalized) and your tool returns no results. Name two changes, one in the definition and one in your code.
Show answer
In the definition, declare status as an enum of the exact lowercase values so the model is steered to valid options. In your code, validate the argument on the server and return an error that lists the allowed values, or normalize the case, so the model can correct itself instead of seeing an empty result.