Availit World How AI really works, in your language

Lesson 31 of 4632 minFacts checked October 21, 2026

Tool calling: giving a model hands

A language model can only write text. It cannot read a clock, do exact arithmetic, look something up or press a button. Tool calling changes that with a simple agreement: the model writes a short, structured request, and the program around it does the work and hands back the result. This lesson follows one tool call through the API, down to the tokens the model reads, shows how to write tools that models use correctly, traces how labs in the United States and China taught models to use tools, and ends with the rule that keeps tool use safe.

In this lesson you will

  • Explain what a tool call is, and who actually runs the tool
  • Read the requests and replies of a tool call, field by field
  • Know how tools look inside the tokens, and why a server needs the right parser
  • Write tool names, descriptions and schemas that models use well
  • Describe how models were trained to call tools, from Toolformer to thousands of simulated environments
  • Treat tool output as untrusted data, and name the defences that work
On this page
  1. What a model cannot do alone
  2. One tool call is two requests
  3. The messages, field by field
  4. What the model really reads
  5. Writing tools a model uses well
  6. How models learned to use tools
  7. Tool output is data, not orders
  8. Remember
  9. Check yourself

What a model cannot do alone

Everything a model does is predict the next token (the tokens lesson), using weights that stopped changing when training ended (the pretraining lesson). That is enough to write, explain and reason, but four kinds of job stay out of reach:

  • Exact work. Multiplying long numbers digit by digit inside a model goes wrong easily, and counting letters is hard because the model sees tokens, not letters: “strawberry” reaches it as two or three pieces, not ten letters.
  • Fresh facts. Today’s date, this morning’s exchange rate or last night’s match result came after the training data was collected.
  • Private facts. Your files, your school’s timetable or your shop’s stock list were never in the training data.
  • Actions. Writing “I have saved the file” saves nothing. Some program has to do it.

This lesson opens the agents part of the course. An agent is a model that calls tools again and again until a job is done. Before building that loop in the next lesson, we take one single tool call completely apart.

One tool call is two requests

The most important fact about tool calling is that the model never runs anything. A tool call is text: a tool name and its arguments, written in a format the model was trained on. The program that sent the request, called the harness (from the stack lesson), reads that text, decides whether to allow it, runs the real function and sends the result back. Only then does the model write its answer.

One tool call, start to finish
  1. Request 1The harness sends the conversation and a list of tools: name, description and allowed arguments
  2. The model asksInstead of answering, it writes a tool call and stops
  3. The harness actsChecks the call, runs the real function, catches any error
  4. Request 2The whole conversation again, now with the tool’s result added
  5. The model answersOr asks for another tool, which is how an agent loop begins
Try itBe the harness

Choose a question and press “Next step” to move through it. “The API messages” shows what your program sends and receives. “What the model reads” shows the same exchange as the one long text Qwen3 actually sees, with the model’s own writing highlighted. Try the unit conversion: the model asks for two tools in one reply. The Karachi question really reads your device’s clock.

This interactive part needs JavaScript.

Quick check

When a chat assistant “uses a calculator”, where is the arithmetic done?

Show the answer

Answer: Outside the model: a program reads the model’s request and runs the calculator The model only writes the request. The harness runs the function and pastes the result into the conversation. That is also why a call can be checked, refused or logged before anything happens.

The messages, field by field

Here is the real exchange behind the 1969 question, in the OpenAI-style format that DeepSeek, Qwen’s cloud, vLLM, llama.cpp and most other servers accept (the APIs lesson). First, the request with one tool attached:

Request 1: the question and the tool listjson
{
  "model": "deepseek-flash",
  "messages": [
    {"role": "user", "content": "What day of the week was 20 July 1969?"}
  ],
  "tools": [{
    "type": "function",
    "function": {
      "name": "weekday",
      "description": "Give the day of the week for a date. Use it for any question about which weekday a date fell on or will fall on. Works for years 1 to 9999.",
      "parameters": {
        "type": "object",
        "properties": {
          "date": {"type": "string", "description": "The date as YYYY-MM-DD, e.g. 1969-07-20"}
        },
        "required": ["date"]
      }
    }
  }],
  "thinking": {"type": "disabled"}
}
  • A tool is a name, a description written for the model, and parameters written as JSON Schema: which arguments exist, their types and which are required.
  • The tool list is sent with every request. Its tokens are billed as input each time, so long tool lists cost money on every turn.
Reply 1: a tool call instead of an answerjson
{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "",
      "tool_calls": [{
        "id": "call_0_7f3a",
        "type": "function",
        "function": {"name": "weekday", "arguments": "{\"date\": \"1969-07-20\"}"}
      }]
    },
    "finish_reason": "tool_calls"
  }]
}
  • finish_reason is “tool_calls”, not “stop”. This is your program’s signal to run something.
  • arguments is a JSON string that the model wrote token by token. Parse it and check it before use: it can be malformed, or well formed with wrong values.
  • The id lets you match each result to its call, which matters when there are several.
Request 2: the same chat, plus the resultjson
"messages": [
  {"role": "user", "content": "What day of the week was 20 July 1969?"},
  {"role": "assistant", "content": "", "tool_calls": [{
    "id": "call_0_7f3a", "type": "function",
    "function": {"name": "weekday", "arguments": "{\"date\": \"1969-07-20\"}"}
  }]},
  {"role": "tool", "tool_call_id": "call_0_7f3a", "content": "Sunday"}
]
  • The API remembers nothing (the APIs lesson), so the harness resends the question, the model’s own tool call and a new message with role tool holding the result.
  • The tools are sent again too. The reply now has finish_reason “stop” and the text: “20 July 1969 was a Sunday.”

When a question needs several independent facts, such as the weather in two cities, a model can write several calls in one reply: parallel tool calls. The harness may run them at the same time, then sends one tool message per call, each with its own tool_call_id.

Telling the model whether to call a tool
OpenAI formatClaude
The model decides (the default)"tool_choice": "auto"{"type": "auto"}
Must call some tool"tool_choice": "required"{"type": "any"}
Must call one named tool{"type": "function", "function": {"name": "weekday"}}{"type": "tool", "name": "weekday"}
Must not call a tool"tool_choice": "none"{"type": "none"}
At most one call per reply"parallel_tool_calls": false"disable_parallel_tool_use": true

Forcing is not always allowed. Claude’s newest models return error 400 for “any” or a named tool, and so does any Claude model with thinking switched on manually; use “auto” and say in the prompt which tool you want.

What the model really reads

Nothing about the model changed to make tools possible. Before the request reaches the model, the server’s chat template (the APIs lesson) turns the messages and the tool list into one long piece of text with special tokens, and the model was fine-tuned on many examples in exactly that layout. The demo’s second view shows Qwen3’s version. Each model family has its own:

Same idea, four layouts
The tool listThe model’s callThe result
Qwen3JSON, one tool per line, between <tools> tags in the system turnJSON between <tool_call> tags; <tool_call> is a single tokenA turn marked user, between <tool_response> tags
gpt-oss (OpenAI’s open models)TypeScript-style types in a “functions” namespace, in the developer messageA message on the “commentary” channel addressed to=functions.weekday, ending with the <|call|> tokenA message whose author is the tool itself
DeepSeek V4.1JSON schemas under “## Tools” in the system promptXML-like DSML tags: one “invoke” per call and one “parameter” per argument; text arguments are written plainly, without JSON quotingA turn marked user, between <tool_result> tags
ClaudeBuilt into a system prompt by the API, which adds 286 tokens of instructions on the newest modelstool_use blocks in the reply; the raw layout is not publishedtool_result blocks in your next message

Two things follow. First, tool results arrive in a turn marked user or tool, and the model tells them apart from your words only through the tags around them, a habit it learned in training. Second, when you serve an open model yourself, the engine must recognise that model’s layout to turn the text back into tool_calls. vLLM needs --enable-auto-tool-choice and the right --tool-call-parser (for Qwen3, hermes); llama.cpp’s llama-server needs --jinja so it applies the model’s own template. With the wrong setting, the call comes back as ordinary words inside the answer and nothing runs.

Quick check

You serve Qwen3 with vLLM, and tool calls come back as text such as <tool_call>{…}</tool_call> inside the answer. What is most likely wrong?

Show the answer

Answer: The server was started without tool parsing, so it never turned the tags into tool_calls The model did its part: it wrote a call in its trained layout. Starting vLLM with --enable-auto-tool-choice --tool-call-parser hermes lets the engine cut the call out of the text and return it as structured tool_calls with finish_reason “tool_calls”.

Writing tools a model uses well

A model chooses a tool by reading its name, description and schema, much as you might choose from a menu in a language you half know. Anthropic’s documentation calls detailed descriptions “by far the most important factor” in how well tools work. What helps most:

  • Write the description for a new colleague. What the tool does, when to use it and when not to, what each argument means, what comes back, and its limits. Three or four sentences is normal.
  • Make wrong calls impossible. Use enum for fixed choices, exact types and required fields. Avoid arguments that can contradict each other: one state of “on” or “off” is safer than two yes-or-no switches that could both be yes.
  • Prefer fewer, more complete tools. One tool that finds a free time and books it beats three tools the model must chain in the right order.
  • Group names by service. With many tools, prefixes such as calendar_find_slot and email_send show which system each belongs to.
  • Return only what matters. Results go into the context and are paid for on every later turn. Send back the few fields the model needs, with readable identifiers, not a page of raw HTML.
  • Write errors the model can act on. “Unknown currency ‘rupee’. Use a code such as PKR, INR, LKR or NPR” teaches the model to fix its call on the next try.
  • Keep the list short. Every definition is sent on every turn and competes for attention. When there are hundreds, providers offer tool search: the model first searches the catalogue, and only matching definitions are loaded.

A tool that invites mistakes

  • Name: convert, arguments amount, from, to, all plain text.
  • Description: “Converts money.”
  • Which rupee: Pakistan’s, India’s, Sri Lanka’s or Nepal’s? Today’s rate or last year’s? The model has to guess, and it will not always guess the same way.

A tool that guides the model

  • Name: currency_convert; amount is a number, from and to are three-letter ISO codes such as PKR or NGN.
  • Description: “Convert an amount between two currencies at today’s rate. Use ISO codes; if the user names a currency ambiguously, ask which country they mean. Returns the converted amount, the rate and its date. Not for past rates.”
  • Every question the first version left open now has an answer.

Does each one help the model call tools correctly, or confuse it?

0 of 8 sorted
  • An enum listing the five allowed values

    Answer: Helps

  • Two tools called search and find that do nearly the same thing

    Answer: Confuses

  • A description that says when not to use the tool

    Answer: Helps

  • A tool that returns a whole web page of HTML

    Answer: Confuses

  • An error message that says how to fix the call

    Answer: Helps

  • Forty tools sent on every turn, most of them never used

    Answer: Confuses

  • Arguments named a, b and c

    Answer: Confuses

  • One example call included in the description

    Answer: Helps

How models learned to use tools

The first chat models could not call tools at all. The skill was built up in steps, and each step is a paper worth reading once you finish this course.

From one calculator to thousands of environments
What it didWhy it mattered
Toolformer (Meta, 2023)The model tried inserting API calls into ordinary text and kept only the calls whose results made the following words easier to predict. Tools: a calculator, a question-answering system, two search engines, a translator and a calendar.A model can teach itself when a tool helps, without people labelling examples.
Gorilla (UC Berkeley and Microsoft, 2023)Fine-tuned a 7B LLaMA model to write calls to machine-learning APIs from Hugging Face, TorchHub and TensorFlow Hub, reading the documentation as it goes.It wrote correct calls more often than GPT-4 and invented fewer. The same team later built the Berkeley Function Calling Leaderboard.
ToolLLM (Tsinghua University and others, 2023)Collected 16,464 real web APIs in 49 categories, generated tasks and solutions, and searched solutions as a tree so dead ends could be undone.Open models learned tasks that need several tools in a row.
ToolACE (Huawei Noah’s Ark Lab, USTC and others, 2024)Invented 26,507 synthetic APIs, generated conversations between simulated users, assistants and tools, and checked every example with rules and a model.An 8B model fine-tuned on this data ranked third on the Berkeley leaderboard, just behind two GPT-4 models.
Kimi K2 (Moonshot AI, 2025)Tool definitions from real MCP servers plus synthetic ones, then agents and tasks, then whole conversations with a simulated user and a simulated tool, graded against rubrics by a judge model.Agent data at scale became a standard part of training an open frontier model.
DeepSeek-V3.2 (DeepSeek, 2025)Built over 1,800 environments and 85,000 complex prompts for reinforcement learning on code, search and general tool use.Tool use learned by trying and being scored (the reasoning lesson), not only by copying examples.
How tool use is measured
What it tests
BFCL, the Berkeley Function Calling Leaderboard (version 4)Whether calls are right: the right function, the right arguments, and declining when no tool fits. Later versions add conversations of several turns and agent tasks such as web search.
τ²-bench (Sierra, 2025)A simulated customer talks to the agent, which must solve the problem with tools while following a company’s rules, in airline, retail and telecom settings. In telecom the customer has tools too, and the agent must guide them. It reports pass^k: the share of tasks solved in every one of k tries.
ACEBench (2025)Ordinary cases, special cases such as missing or wrong information in the request, and agent tasks over many turns.

Quick check

Why did labs move from real APIs towards simulated tools and environments for training?

Show the answer

Answer: They can be made by the thousand, answer instantly, cost nothing per call and are safe to get wrong Training needs huge numbers of attempts, many of them mistakes. Simulated tools make that cheap and safe; real sandboxes are added where results must be exact.

Tool output is data, not orders

A tool result enters the context as ordinary tokens, right next to your instructions. When it comes from outside, such as a web page, an email, a shared document or a reply from another program, then whoever wrote that text has a channel into the model. The model cannot see who wrote which words; it can only judge them. A 2023 paper by Greshake and colleagues named the risk indirect prompt injection: text left where a model will read it, written to steer the model away from what its user asked.

Models are trained to resist this and improve every year, but none resists every attempt. So the sound design rule is: assume a model that has read untrusted text may follow it, and limit what that could cost. The security researcher Simon Willison describes the dangerous combination as the lethal trifecta (2025): an agent that has access to private data, reads untrusted content and can send data out. With all three, private data can leak. Remove any one of the three and that path is closed.

  • Give the least access that works. Read-only where possible; one folder, not the whole disk; one mailbox label, not the whole account.
  • Ask a person before anything that matters. Sending, paying, deleting and publishing wait for a human “yes”. Most coding agents ask before running a command they have not been allowed to run.
  • Check in code, not in words. Your program validates every argument: the path is inside the allowed folder, the amount is under the limit, the address is on the approved list.
  • Close the way out. An agent that reads untrusted text should not also be able to contact new addresses freely. Limit which sites, people and links it can reach.
  • Keep a record. Log every call and result, so a person can see afterwards what happened and why.

Quick check

An email assistant can read your inbox, browse the web and send emails. Which change best protects you from a harmful instruction hidden in an incoming message?

Show the answer

Answer: Requiring your approval before any email is sent Sending is the way out. With a person checking every outgoing email, an instruction hidden in a message cannot quietly move your data anywhere. A prompt helps a little, and a better model helps a little, but neither is a guarantee.

Remember

  • A model only writes text. A tool call is text in an agreed format; the harness runs the function and returns the result.
  • One tool call is two requests: the model asks (finish_reason “tool_calls”), the harness runs the tool, and the model answers with the result in its context.
  • A tool is a name, a description and a JSON Schema. Arguments arrive as a string to check; parallel calls each get a result with a matching tool_call_id.
  • Inside, tools are just tokens: definitions in the system prompt, calls and results in special tags. Each family has its own layout, and a self-hosted server needs the matching parser.
  • Detailed descriptions, enums, few well-named tools and short, useful results matter more than anything else for accuracy.
  • Models learned tools from self-teaching (Toolformer), real API collections (Gorilla, ToolLLM), synthetic APIs (ToolACE) and now thousands of simulated and real environments with reinforcement learning (Kimi K2, DeepSeek-V3.2).
  • Tool output is untrusted data. Private data, untrusted content and a way out together form the lethal trifecta; real protection lives in the harness, not the prompt.

Words to know

tool
A function outside the model that it can ask to run, such as a calculator, a search or a database lookup.
tool call
A structured request written by the model: a tool name and its arguments. Also called a function call.
harness
The program around a model that sends it requests, runs its tool calls and returns the results.
JSON Schema
A standard way to describe the shape of JSON: which fields exist, their types and which are required.
parallel tool calls
Several tool calls in one reply, which the harness can run at the same time.
tool_call_id
The label that links each tool result to the call it answers.
tool_choice
The request setting that lets the model decide, forces a tool, or forbids tools.
strict mode
Constrained decoding for tool calls, so the arguments always match the schema.
tool-call parser
The part of a serving engine that finds tool calls in the model’s text and returns them as structured data.
client tool, server tool
A tool your own program runs, or one the provider runs for you.
simulated environment
A pretend tool, user or world, played by a program or another model, used to train agents safely.
indirect prompt injection
Instructions hidden in something a model reads, such as a web page or an email, that try to steer it away from its user’s request.
lethal trifecta
Access to private data, exposure to untrusted content and a way to send data out, all in one agent.
least privilege
Giving each tool only the access it needs, and nothing more.
BFCL
The Berkeley Function Calling Leaderboard, a public test of how accurately models call tools.

Go to the source

This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.

Check yourself

5 questions. Tap the answer you think is right.

0 of 5 answered

Your program receives a reply with finish_reason “tool_calls”. What should it do next?

Show the answer

Answer: Run the requested tools, add the results to the conversation and call the model again The model has asked for work to be done. Your program does it, adds a tool message for each call, and sends the conversation back so the model can answer.

Why can a model count the letters in a word reliably with a tool, but not always without one?

Show the answer

Answer: The model sees tokens, not letters, while the tool counts letters directly in code “strawberry” reaches the model as a few tokens. Code sees every character.

Where does a tool’s description go?

Show the answer

Answer: Into the model’s context on every request, where the model reads it to decide what to call Definitions are part of the prompt each time. That is why clear descriptions matter so much, and why long tool lists cost input tokens on every turn.

Which tool is easiest for a model to use correctly?

Show the answer

Answer: One with a detailed description, an enum for fixed choices and only the fields it needs The model can only act on what the definition tells it. Clear words and tight schemas leave nothing to guess.

Which agent has the lethal trifecta?

Show the answer

Answer: One that reads your email, browses the web and can send messages Private data (your email), untrusted content (web pages and incoming mail) and a way out (sending messages) are all present. Removing any one closes the path.

Lesson complete

Answer every question above to complete this lesson.

Your progress is saved on this device only.

Next lessonThe agent loop: think, act, look, repeat
Previous lesson All lessons

Choose your language