Tool Use in Language Model Agents
Tool Use in Language Model Agents
What a Tool Is and Why Agents Use Tools
A tool is an interface through which a language model can invoke an external computer program. A language model alone predicts tokens; it cannot directly search the web, run a calculator, access a live clock, or change an external system. A tool connects the model’s text-based decisions to those capabilities.
Tools make it possible for a language model to interact with systems such as:
Search engines and browsers
Calculators and Python interpreters
External APIs
Image-generation systems
Applications that manage user data or perform actions
The tool-calling method can follow a standard pattern, but the work performed by each tool can vary widely. A system that repeatedly decides whether to call a tool, calls it, receives its result, and then continues toward an answer is acting as an agent. In this sense, an agent is not merely a chat interface: it uses iterative interaction with tools to accomplish tasks.
Two fundamental benefits of tools
Extending the model’s abilities: A tool gives the model access to information or actions outside its own capabilities. For example, a model with outdated training information cannot reliably know the current time or today’s weather unless it consults an external source.
Facilitating tasks the model could perform itself: A tool can make a task faster or more reliable, even when the model could theoretically do it without assistance. For example, a language model may be able to multiply large numbers, but a calculator can do so more quickly and accurately.
Tools can also provide fresh evidence, perform exact computation, expose relevant user-specific information, and make changes to external systems. These abilities allow responses to be grounded in current information and can let an agent act on the user’s behalf.
Common Tool Categories
Textual responses
A textual response is the agent’s final answer to the user. An agentic system can implement this in either of two ways:
It can provide a dedicated “finish” action that signals that the agent is done and should return text.
It can treat the absence of another tool call as the signal to end the interaction and return the response.
Web search and retrieval
Web search retrieves information from external sources so that the model can use it when generating an answer. This is a common way to obtain current evidence that was not available in the model’s original training data.
This pattern is closely related to retrieval-augmented generation (RAG): the system retrieves relevant context and then generates an answer based on that context. As retrieval has become a routine feature of many conversational applications, users may encounter RAG without recognizing it as a distinct technique.
Code execution
A code-execution tool runs a program, often to perform calculations or other data-processing tasks. It can be more reliable and efficient than asking the model to carry out every operation through token generation alone. Code execution can also combine multiple operations into a single program.
Image generation
An image-generation tool sends a prompt to a system that creates an image. Unlike many tools that primarily take and return text, image-generation tools work with visual output.
The model may expand or transform the user’s request before sending it to the image generator. Therefore, the prompt that the image-generation system receives may be more detailed than the wording originally supplied by the user. Choosing and refining the image-generation prompt is itself an important part of tool use.
Custom functions and application actions
A system can expose custom tools for specific tasks, such as creating a grocery cart or interacting with a shopping service. The available functions depend on the tools and APIs integrated into the agent. This makes tool use adaptable to many applications, from retrieving information to carrying out transactions.
Tool Calling as Direct API Use or Program Execution
Direct function calls
One approach is to give the agent a defined set of API functions. The agent selects an appropriate function and supplies its arguments. A task may require one call, several sequential calls, or multiple independent calls made together.
Code as a meta-tool
Code is especially expressive because a program can combine many function calls with variables, loops, conditionals, and other control flow. Rather than requiring the agent to make every small operation as a separate interaction, the agent can write a program that coordinates those operations.
A program can also import libraries that expose many additional functions. For instance, making a data-analysis library available gives the agent access to that library’s capabilities; developers can also provide specialized utility functions.
Code therefore acts as a meta-tool: it does not merely perform one predefined operation but provides a flexible way to compose and coordinate other tools.
Why code-based tool use can be effective
Compared with calling APIs one at a time, a program can often complete a multi-step task with fewer interaction turns. For example, finding the most cost-effective option across several countries might require repeated calls to look up prices, exchange rates, and taxes if handled one API call at a time. A single program can perform the same sequence systematically.
Research on programmatic tool use has found that, for relevant tasks, this approach can improve success rates while reducing the average number of interaction turns. Its benefits can apply even when the task is not traditionally considered a programming task: code can simply be a convenient medium for coordinating tools.
Risks and trade-offs of programmatic tools
The flexibility of code also increases the power and risk of the agent:
Unbounded execution: A program can contain an infinite loop or otherwise run for too long. Systems need limits and mechanisms for stopping or containing execution.
Security risks: Code may load a compromised library. If an agent imports a malicious or vulnerable dependency, the effects can extend to the larger system.
Difficulty constraining behavior: A broad action space makes it harder to predict exactly what the agent will do and to validate its actions in advance.
Resource use: Programs can consume significant memory, storage, or computing time.
Need for isolation: Programmatic tool use often requires a sandbox or other containment mechanism to limit the damage that code could cause.
The choice between a narrow set of direct APIs and broad code execution is therefore a trade-off between expressiveness and control.
How Tool Calls Are Represented and Processed
Tool calls in model output
A tool call is represented in the model’s output using a structured format, often involving special tokens. The model may produce ordinary user-facing text, a tool call, or both as part of the same response.
Some formats also separate:
Private or internal reasoning
A user-facing message
The actual tool call
In such a format, the reasoning may be verbose and not intended for the user, while the message is the concise response shown to the user. The tool call specifies the action the system should perform.
Chat formats and model-specific conventions
Chat interfaces commonly represent messages with roles such as system, user, and assistant. Although an application may pass messages to a model in a convenient structure such as JSON, the model receives a model-specific representation using special tokens and formatting rules.
Tool calls also have model-specific formats. Different model families may use different special tokens or structures to indicate a function call and its arguments. Consequently:
A parser written for one model’s tool-call format may not work for another model.
A fine-tuned model should generally be trained using the tool-call format it was originally trained to follow.
Applications need to apply the correct chat template for the model being used.
Tool-call tokens do not necessarily have to be present during initial pre-training on broad internet data. They are often introduced during mid-training, a stage in which the model is trained on substantial data in more targeted formats. Later training stages may further reinforce tool use.
Tool registration, dispatch, and results
An agent framework typically registers each tool with a name and connects that name to an implementation, such as a Python or TypeScript function. When a model emits a tool call, the system can:
Parse the call and extract its tool name and arguments.
Find the implementation registered under that name.
Validate the arguments.
Execute the tool.
Return the tool’s result to the agent as an observation.
Errors can arise at different stages:
Parsing or validation errors: The call is malformed or does not match the expected arguments.
Execution errors: The call passes validation but fails when run. For example, a Python tool may accept a string as input, but that string may contain invalid Python.
External failures: The tool itself may be unavailable, time out, or return an error.
Tool-call IDs and history matching
Tool calls are commonly assigned unique IDs, and each result refers to the ID of the call that produced it. This matching is important when several tool calls are made at once, because it lets the system associate each result with the correct request.
Some model providers require every tool call in the conversation history to have a matching result. If a program crashes after recording a tool call but before recording its result, a resumed conversation may contain an incomplete history. A provider may reject that history rather than continue generating. Reliable systems therefore need to preserve the relationship between each call and its result.
Constrained Decoding for Valid Tool Calls
Language models are not guaranteed to produce correctly formatted tool calls. For example, a model may generate JSON that is missing a closing brace. A standard JSON parser would fail to process it.
Tool-call validity has several dimensions:
Syntax: The output must be parseable, such as valid JSON.
Shape: Required fields must be present, and fields must follow the expected structure.
Types and values: Values must have the correct types and satisfy restrictions. For example, a city may need to be a string, and a temperature unit may need to be one of the accepted options.
A JSON schema can describe machine-readable requirements for the structure, types, required fields, and allowed values of a tool call. A validator can then check whether a call conforms to those requirements.
Grammars and automata
Schemas can be connected to grammars that describe which sequences of tokens are valid. A regular grammar, such as one represented by a regular expression, can be processed with a finite-state automaton. However, nested structures such as JSON require more expressive parsing than a finite-state automaton provides. A context-free grammar can describe these nested structures, and a pushdown automaton can process them by using a stack.
A grammar-based decoding system can use these rules while the model generates output:
The model predicts scores, or logits, for possible next tokens.
The grammar determines which tokens are valid in the current context.
Scores for invalid tokens are suppressed, effectively preventing those tokens from being selected.
The remaining scores are normalized so generation proceeds only along valid paths.
This process can ensure that the generated output follows the required syntax and schema, provided the system supports the relevant constraints. Some decoding systems precompute which tokens are always valid or always invalid; other token-validity checks depend on the current parsing context and are calculated during generation.
What constrained decoding cannot guarantee
Constrained decoding guarantees structural validity only within its supported rules. It does not guarantee that the tool call is meaningful or that the requested action is correct. A syntactically valid Python program can still contain a logic error, and a schema-valid request can still be inappropriate for the task.
There is also a limit related to the model’s maximum output length. Generation may stop while the output is still on a valid path through the grammar but has not yet reached a complete final state. In that case, the result can still be incomplete, such as a partially generated JSON object.
Connecting Tools Through REST APIs and MCP
REST APIs and FastAPI
A REST API is a common way for applications to interact with web services. A local function can be exposed remotely as an API endpoint, allowing an agent or another application to call it over a network.
Frameworks such as FastAPI make this process easier by allowing a developer to define endpoints using Python functions and annotations. This can provide several benefits:
API-key checks can restrict access to authorized users or systems.
Authentication can protect personal or sensitive data.
API definitions can produce a JSON schema describing the API’s accepted inputs.
The schema can be supplied to a language model so it knows which calls and arguments are allowed.
A command-line utility such as curl can also invoke a REST API. A coding agent with access to a shell may use such a command to contact an API, although this is different from a structured tool call made through a model’s standard tool-calling interface.
Model Context Protocol
The Model Context Protocol (MCP) provides a standard way to expose capabilities and context to AI applications. Instead of having an agent call each upstream service directly, an application can connect to an MCP server that provides tools for services such as weather or source-code hosting.
MCP can be useful when it adds an intermediary layer between an agent and a sensitive service. For example:
The MCP server holds the upstream credential, such as a service-specific token.
The agent receives a separate credential that allows it to access the MCP server.
The agent does not receive the sensitive upstream credential itself.
This separation can reduce the consequences of credential leakage. If the agent exposes its own MCP credential, the more powerful credential held by the MCP server can remain protected.
MCP also standardizes tool discovery and communication. An MCP client can ask an MCP server which tools it provides, then invoke those tools using an MCP transport. Depending on the implementation, communication may use standard input and output, a socket, or another supported method.
Compared with directly calling a REST API:
A REST integration may discover capabilities through an OpenAPI document and invoke them through HTTP.
An MCP integration can use a protocol-specific method to list and invoke tools.
MCP can provide additional features, including resources, prompts, and extensions.
Frameworks such as FastMCP make it easier to create MCP servers, in a way that is conceptually similar to how FastAPI simplifies the creation of REST APIs.
Parallel Tool Calling
Parallel tool calling allows an agent to request multiple tool operations in one response rather than waiting for each operation to finish before requesting the next. A system can then execute the independent calls concurrently and collect their results.
For example, retrieving the weather, reading a calendar, and checking a flight status may be done in parallel if none of those results depends on another. By contrast, the following sequence must be ordered:
Find a customer ID.
Use that ID to retrieve orders.
Use the selected order to issue a refund.
The later calls depend on information produced by earlier calls, so they cannot all be performed at the same time.
A system can execute independent calls concurrently using asynchronous programming tools, such as Python’s asyncio.gather. Results are then matched to their original calls using call IDs.
Why parallel calling matters
Parallel calls can reduce the time required to complete a task. More capable models may also be cheaper on a per-task basis, even if they cost more per token, because they can:
Select an effective solution more quickly.
Recognize which tool calls are independent.
Issue multiple tool calls together rather than making them sequentially.
A factor that can encourage parallel tool use is reinforcement learning with a strong penalty for lengthy task execution. If a model is rewarded for finishing tasks with fewer steps or less elapsed time, it may learn to make independent calls concurrently.
Evaluating Tool Use
Tool-use evaluation can measure whether a language model can select, format, and sequence tool calls reliably. A tool-calling benchmark may cover several levels of difficulty, from a single tool call to multi-turn and agentic tool use.
Important evaluation dimensions include:
Tool selection: Did the model choose a tool that can help accomplish the task?
Argument correctness: Did it supply the correct values and use the required formats?
Call ordering: When calls have dependencies, did it use them in the right sequence?
End-to-end accuracy: Did the complete tool-assisted process solve the task?
Robustness: Can the model handle invalid or unavailable tools, or recover from errors?
Efficiency: How much time, how many tokens, and how much cost did the task require?
Reliability: Does the system retry appropriately after timeouts and choose alternatives when a tool is unavailable?
Safety: Does the system avoid inappropriate or adversarially prompted tool use?
Tool-call robustness can also include testing whether the model invents unsupported arguments or is sensitive to differences in formatting.
Provider-dependent error rates
The same named model can have very different tool-call error rates depending on who serves it. The model’s name alone does not fully determine the behavior of a deployed system. Differences may result from:
Quantization: Compressing model weights can reduce inference costs but may degrade performance. More aggressive quantization, such as four-bit rather than eight-bit representations, can lead to more incorrect tool calls, although the effect depends on the model and implementation.
Speculative decoding: A cheaper model may predict tokens for a more expensive model to speed up generation. Lossless speculative decoding should preserve the underlying output distribution, while lossy variants may change behavior and potentially affect tool-call reliability.
Constrained decoding: Providers may differ in whether they use grammar-based decoding to restrict outputs to valid tool-call formats.
Inference implementation: Providers may use different inference software and decoding settings, which can affect tool-call formatting and success.
Service reliability: The inference provider itself may experience outages or failures, causing a tool call to fail even if the model’s generated call was correct.
Tool-call evaluation therefore needs to account not only for the model, but also for the serving system and its decoding methods.
The Tool-Use Pipeline
Tool use is a layered process that connects model generation to external capabilities:
Define capabilities: Tools provide functions such as retrieval, computation, content generation, or application actions.
Describe tools: Schemas and chat templates tell the model what tools are available and how to express calls.
Generate a call: The model emits a structured request for a tool.
Validate and dispatch: The agent parses the request, checks its arguments, and sends it to the correct implementation.
Execute and record: The tool runs, and its result is saved with the corresponding call ID.
Continue or finish: The agent uses the result to make another call or returns a final answer.
Schemas and constrained decoding can help ensure that calls are well-formed, but they cannot ensure semantic correctness. A structurally valid request may still be misguided, unsafe, or unsuccessful when executed. Reliable agents therefore need appropriate tool design, validation, error handling, security controls, concurrency management, and evaluation.

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