Tool Use in Language Model Agents
Tool Use in Language-Model Agents
What makes a tool-using system an agent?
A language model generates text by predicting tokens from the input it receives. On its own, it cannot directly check a live website, run a calculator, read a private database, or make a change to an external service. Its knowledge and actions are limited to what its model and surrounding system make available.
A tool is an interface that lets a language model request that an external program perform an operation. The model might ask a search tool to find current information, a calculator to compute a result, or an API to create a shopping cart. The surrounding software interprets the request, runs the program, and returns the result to the model.
This creates an iterative process: the model decides what to do, a tool performs the requested operation, and the model uses the result to decide what to do next or what answer to give. A system that can make such repeated tool calls is an agent, rather than merely a system that produces a single text response.
A tool connects a language model to an external capability; the agentic behavior comes from choosing, using, and responding to tools over a sequence of steps.
Tools are useful for two related but different reasons.
- Extending the model’s abilities: A tool gives the model access to information or actions that are outside the model’s own capabilities. For example, a model whose training information is several months out of date cannot know today’s weather from its stored knowledge alone. A weather or search tool can provide fresh information.
- Facilitating work the model could do itself: A tool can perform a task more quickly or reliably than generating an answer through language-model reasoning. A model may be able to multiply large numbers, for example, but a calculator can do so faster and with less risk of arithmetic error.
Think About It
If a model can explain how to calculate a result but cannot reliably produce the exact result, is a calculator extending its ability or facilitating it? The answer depends on which part of the task is considered: arithmetic is something the model may be able to attempt, while the calculator makes exact computation faster and more dependable.
What tools make possible
Tools can give an agent access to several broad kinds of capability.
- Current information: Search and browsing tools retrieve information that may not have been available when the model was trained. Retrieved evidence can help ground the model’s answer in up-to-date information.
- Exact computation: Calculators and code execution can perform arithmetic, data processing, and other calculations more quickly and reliably than relying on generated text alone.
- Private or user-specific information: A tool can provide information about a user or their account, allowing an answer to reflect the user’s actual situation.
- Changes to an external environment: An agent can call an API to perform an action, such as creating a grocery order or making another change in an external service.
- Generated media: An image-generation tool can turn a text request into an image. This differs from ordinary text tools because the result is an image rather than text.
A request to generate an image often requires more than passing the user’s original words directly to the image tool. The language model may expand or refine the request into a more detailed prompt. Thus, deciding what to send to the tool is itself part of using the tool effectively.
Common tool patterns
A system may offer a range of tools, but many fit into a few familiar patterns:
- Text responses: The agent returns an answer to the user. In an agent loop, this can be represented by a special “finish” action, or the loop can end when the model chooses not to call another tool.
- Web search and retrieval: The agent searches for relevant information and then generates an answer based on what it retrieved. This is the basic idea of retrieval-augmented generation (RAG). Because search-and-answer behavior is common in modern assistants, retrieval can feel like an ordinary part of interacting with them.
- Code execution: The agent provides code to perform calculations or other operations.
- Image generation: The agent sends a prompt to a system that produces an image.
- Custom functions and APIs: The agent uses a purpose-built function to perform an action, such as adding specified items to a grocery cart.
These examples illustrate why tools are flexible: a tool call may simply gather information, or it may cause a real change in another system.
Direct tools and code as a meta-tool
One design is to provide an agent with a set of individual API functions. The model chooses a function, supplies its arguments, and the system runs it. A task that involves several steps may therefore require several separate tool calls.
Code offers a more expressive alternative. A program can combine many operations into a single sequence, use variables to store intermediate results, and use loops or other control flow. In that sense, code can act as a meta-tool: it allows the model to organize and invoke other operations in flexible combinations.
For example, suppose an agent must compare the cost of buying a phone in several countries. With separate tools, it may need to look up an exchange rate, look up a local phone price, convert the price, account for tax, and repeat those steps for each country. A program can express the repeated procedure once and apply it to all the countries. This can reduce the number of back-and-forth interactions and make the task more efficient.
Research on CodeAct, an approach that uses generated programs for tool interaction, reports that code-based tool use can improve task success rates while reducing the average number of interaction turns. The benefit is not limited to tasks traditionally described as coding tasks; code can also be an effective way to coordinate ordinary tools.
The trade-offs of programmatic tool use
Code is powerful, but that power creates risks and management challenges.
- Unbounded execution: A generated program could enter an infinite loop, so the system needs limits and ways to stop execution.
- Security risks: A program may use an unsafe or compromised library. If that library is malicious, the agent’s environment or the broader system could be put at risk.
- Harder constraints and validation: A broad programming environment gives an agent many possible actions, which can make behavior less predictable and harder to check in advance.
- Resource use: A program can consume excessive memory, disk space, or processing time.
For these reasons, code execution often needs a sandbox: a restricted environment that limits the program’s access and contains the effects of mistakes or misuse. A sandbox does not make code harmless, but it can reduce the consequences of giving an agent a powerful execution tool.
Think About It
Why might one tightly defined function be safer than giving an agent access to a general-purpose programming environment? A narrow function limits what the agent can ask the system to do; a programming environment offers much greater flexibility, but also a broader space of possible actions and failures.
How tool calls fit into a conversation
Tool calls are represented as structured outputs, not merely as ordinary prose mentioning a tool. A model may produce a user-facing message and a tool request as parts of the same response. For example, a system may allow the assistant to produce visible text, make a request to a weather tool, and later use the returned observation to continue.
Some systems also include an internal reasoning portion that is not shown to the user. In such a format, the output may distinguish among:
- internal reasoning or planning,
- a user-facing message, and
- the actual tool call.
The important idea is that a tool call is a specific kind of model output that the surrounding software can recognize and execute. The agent loop can therefore be represented through structured conversation messages rather than only through separate, hand-written control code.
Chat formats and training
Chat messages commonly have roles such as system, user, and assistant. Although an application may represent these messages using a data structure such as JSON, the model typically receives them in a particular serialized format with special markers separating messages and indicating their roles.
Tool calls add further structure. A tool definition can specify:
- the tool’s name,
- its parameters,
- the expected type of each parameter, and
- which parameters are required.
For example, a weather function might be described as taking a city name as a required string and a temperature unit as an optional or constrained value. This description can be included in the request to the model so that the model knows what it is allowed to call and what arguments are expected.
Tool-call markers do not necessarily need to be present in a model’s vocabulary from the beginning of pretraining. They may instead be introduced during mid-training, a later stage in which the model is trained on substantial data in formats closer to the formats it will use. Training and fine-tuning then teach the model to produce tool calls in a particular style.
Different model families can use different tool-call formats. One model might use one set of special markers, while another uses a different format or labels calls as “functions” rather than “tools.” These differences matter: software that parses one model’s format may not correctly parse another’s.
When adapting an already-trained model, the conversation format should match the format the model was trained to use. Chat-template functions in model libraries help produce the appropriate format. Correct templating is not just cosmetic; a mismatch can cause the model’s tool calls to be misunderstood or rejected.
From a generated call to a tool result
A tool-using system must do more than ask the model for a tool call. It needs to turn the model’s structured output into an actual operation and return the result.
A typical process is:
- Parse the output: Extract the tool name and arguments from the model’s response.
- Resolve the tool: Find the registered implementation associated with the tool name.
- Validate the arguments: Check that the arguments meet the tool’s requirements.
- Execute the tool: Run the relevant function or send the request to the appropriate service.
- Return an observation: Send the result back into the conversation so the model can use it.
Tools are generally registered when the agent is initialized. Each registered tool has a name and an implementation, such as a Python or TypeScript function. When the model requests a tool by name, the agent looks up the matching implementation and passes it the supplied arguments.
Failures can happen at different stages. A model may name a tool incorrectly or provide arguments that fail validation. Even if the arguments pass validation, execution may still fail. For example, an execution tool may accept a string as Python code, but the code itself may produce an error when run. The agent should therefore distinguish between an invalid request and an execution failure.
Tool calls and their results also need matching identifiers. Each call can be assigned an ID, and its result carries the corresponding ID. This becomes particularly important when several tools run at the same time: the IDs show which result belongs to which request. Some model interfaces require every tool call in the conversation history to have a matching result. If a program crashes after recording the call but before saving the result, resuming from that incomplete history may cause the interface to reject it.
Making tool calls well-formed
A model can produce an invalid tool call. For example, it might generate JSON with a missing closing bracket. If a program tries to parse that as ordinary JSON, parsing can fail, preventing the agent from retrieving the intended arguments.
Tool calls can be checked at several levels:
- Syntax: Is the output valid JSON or another required format?
- Shape: Are the expected fields present?
- Types and permitted values: Does each field have the right type, and are its values allowed?
A JSON schema can describe these requirements in a machine-readable way. For instance, it can require a city field to be a string, limit a unit field to a set of permitted options, and mark the city as required. A program can use the schema to check whether a call follows the tool’s specification.
Grammar-constrained decoding
Validation after generation can identify a bad call, but another approach is to stop invalid output from being generated in the first place. This is called constrained decoding.
A schema can be used to define a grammar describing valid outputs. A grammar specifies which sequences of symbols are allowed. For structured data such as JSON, the grammar needs to account not only for which values are permitted but also for how those values are arranged.
A regular expression describes a form of regular grammar, which can be recognized by a finite-state automaton. Such an automaton changes state as it reads each token. More deeply structured formats such as nested JSON are not generally handled by a regular grammar alone. A context-free grammar can describe nested structures, and a pushdown automaton can process them using a stack: it pushes information as nested structures begin and removes it as they close.
During constrained decoding, the system checks which next tokens are allowed by the grammar at the current point in generation. Tokens that would make the output invalid are masked out by assigning them a logit of negative infinity. The remaining token scores are then renormalized, so the model selects among permitted next tokens only. Systems such as XGrammar use techniques to determine which tokens are always valid, always invalid, or valid only in a particular context.
This approach can make it very likely that a generated call has valid structure and meets the schema. However, it does not guarantee that the call is sensible or that the requested operation will succeed. A Python program can be syntactically valid but still contain a logical error. Likewise, a call can satisfy a schema but request something inappropriate or produce an unwanted effect.
There is also a limit that grammar constraints cannot eliminate: generation can stop before the output is complete. If the model reaches its output-token limit while still on a valid path through the grammar, the result may be a partial JSON object that has not reached a valid final state.
Think About It
What does a schema guarantee, and what does it leave uncertain? A schema can help ensure that a call has the required structure and permitted types; it cannot establish that the call expresses the correct plan or that the action will succeed.
Calling services with REST APIs
A REST API is a common way for software to interact with a web service. An agent can use an API by sending a request to a server, which performs an operation and returns a result. A coding agent with access to a command-line tool such as curl can also make these requests from code or a shell command.
Frameworks such as FastAPI make it relatively straightforward to create a Python web service. A developer can define functions that become API endpoints, specify how requests should be validated, and require an API key for access. FastAPI can also derive a JSON schema from an API’s definitions. That schema can be used to describe the available operations and acceptable arguments to a language model.
API keys are a way to control who can access a service. For example, requiring an appropriate key can prevent an unauthorized caller from using an API. But the way credentials are given to an agent matters: directly exposing a powerful personal or account credential can be dangerous if the agent leaks it or uses it inappropriately.
MCP: an additional interface layer
The Model Context Protocol (MCP) is a standard for connecting AI applications to external tools and related context. An MCP setup includes an AI application, an MCP client, and an MCP server that exposes capabilities such as tools. Frameworks such as FastMCP make it easier to create MCP servers, much as FastAPI makes it easier to create REST API servers. In some cases, an existing REST API specification can also be adapted into an MCP interface.
MCP and direct REST calls can both make APIs available to an agent, but they differ in how tools are discovered, invoked, and connected. A REST-based system may fetch an OpenAPI document to learn about the API. An MCP server provides a protocol method for listing its available tools. REST requests use HTTP API endpoints, while MCP can communicate through transports such as standard input and output or sockets. MCP can also support resources, prompts, and extensions in addition to tools.
One important reason to put an MCP server between the agent and an external service is credential separation. Consider an agent that needs to work with a GitHub account:
- The upstream credential, such as a GitHub token, is held by the MCP server.
- The agent receives an MCP credential that lets it access the MCP server.
The agent can request permitted GitHub operations without receiving the GitHub token itself. If the agent leaks its MCP credential, the upstream token can remain protected. This arrangement adds a layer between the agent and the more powerful account credential; it does not remove the need to limit permissions and manage security carefully.
MCP tool registries can help developers discover servers that provide particular capabilities. The protocol is useful to understand as an additional way of organizing access to tools, rather than as the only way to connect an agent to an API.
Parallel tool calling
A tool-using agent does not always need to make one request, wait for its result, and then make another request. If several requests are independent, the agent can issue them together. For example, it might check the weather, read the day’s calendar, and look up a flight status at the same time.
This is parallel tool calling. The model can include multiple tool calls in a single response, and the agent system can execute them concurrently. In Python, asynchronous programming tools such as asyncio.gather can run multiple operations and collect their results.
Parallel execution is appropriate only when the calls do not depend on one another. If a later call needs a value returned by an earlier call, they must be sequenced. For example, an agent cannot fetch orders using a customer ID it has not yet found. Nor can it refund an order before it has identified which order was selected.
Parallelism can greatly reduce waiting time for tasks made up of independent operations. Recent models have become better at using this strategy, partly because reinforcement learning can reward completing tasks in fewer steps. A model encouraged to reduce task-execution time has a reason to make compatible tool calls together rather than serially.
Efficiency is not determined only by the price of a model per generated token. A more capable model may finish a task in fewer calls, while a less capable model may need more interactions or make errors that require recovery. As a result, a more expensive model can sometimes cost less for a completed task.
Think About It
Which parts of a task can run at the same time, and which require earlier results? Identifying those dependencies is essential: it determines whether parallel calling speeds up the work or produces invalid requests.
Evaluating tool use
Tool use can be evaluated on its own, separately from the quality of a complete agent system. This matters because selecting and calling tools successfully is a prerequisite for many larger agent tasks.
The Berkeley Function Calling Leaderboard is an example of a benchmark for tool use. Its versions have expanded from single-turn calls to cover multi-turn tool use, robustness, and other aspects of tool-calling behavior. Evaluations can examine whether a model:
- selects a suitable tool for the task,
- supplies the correct argument values,
- uses tools in the right order when order matters,
- completes the task successfully from beginning to end,
- follows the required output format, and
- avoids hallucinating arguments or other call details.
Evaluation can also measure properties beyond basic correctness:
- Efficiency: How many tokens, interactions, or dollars does a task require, and how long does it take?
- Reliability: Does the system respond appropriately to timeouts or failed tools? Can it recover or choose an alternative when needed?
- Safety: Does it resist requests to use tools in inappropriate or harmful ways?
A tool-call benchmark may measure only the model’s ability to make tool calls, rather than the full performance of a complex coding agent. The distinction matters because success on a narrow function-calling task does not automatically show that every part of a long, end-to-end agent workflow will work well.
Why providers can get different results from the same model
The same named model can have notably different tool-call error rates depending on how it is served. A reported comparison has shown a tool-call error rate around 15% for one serving setup and around 0.01% to 0.05% for others. That difference suggests that “the model” is not the only factor in the outcome.
Possible causes include:
- Quantization: Compressing model values can reduce the cost of running the model, but aggressive quantization may reduce quality. For example, heavily compressed FP4 models may make more mistakes than FP8 models, though the result depends on the particular model and implementation.
- Speculative decoding: A cheaper model can predict likely outputs to speed up a larger model’s generation. Lossless speculative decoding should preserve the underlying result, but lossy variants may affect outputs.
- Constrained decoding: One provider may enforce a grammar that limits output to valid tool-call formats, while another may rely on the model to produce well-formed calls by itself.
- Serving reliability: The inference service may fail or become unavailable, causing a call to fail even if the model could have produced a correct request.
Consequently, evaluating tool use requires attention not only to the model’s name but also to the inference and serving system around it.
Comprehensive review
Tool use connects language models to external programs. It can extend a model’s abilities by giving it access to current information, private state, or external actions, and it can facilitate tasks—such as exact computation—that the model might attempt but perform less quickly or reliably by itself.
A tool call is a structured request: the model selects a tool and provides arguments, and the agent parses, validates, dispatches, and executes the request. The result is returned as an observation, matched to the call by an identifier, and used in the next step. Schemas and grammar-constrained decoding can help ensure that calls are structurally valid, but structural validity does not ensure correct reasoning or safe execution.
Individual tools provide focused capabilities; code can coordinate tools more flexibly, but it introduces risks that call for constraints and sandboxing. REST APIs offer a common way to access web services, while MCP provides another layer for discovering and connecting tools and can help keep powerful upstream credentials away from the agent. Independent calls can run in parallel, whereas dependent calls must be sequenced. Finally, tool-use quality depends on the whole serving stack—including formatting, validation, decoding, execution, reliability, and evaluation—not on the model alone.

Ask anything
We've read this whole study set, so questions about it get the best answers.