1. Home
  2. Explore
  3. Computer Science
  4. Tool Use in Language Model Agents

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Tool Use in Language Model Agents

Speaker 1Speaker 2

Tool Use in Language Model Agents

15:04
0:00-15:04
  1. Corey

    Welcome back. Today we’re looking at tool use for language-model agents—the fundamental feature that lets an agent do more than a language model operating by itself. A tool is an interface through which a model can invoke an external computer program. The model alone predicts tokens; a tool gives it a way to reach beyond those tokens and do something in the outside world.

  2. Simon

    So a tool might search the web, call a calculator, run Python, open a browser, or access an API. The way a model expresses a tool call is structured, but what happens after that call can vary enormously depending on the tool.

  3. Corey

    Right. Tools have two broad benefits. The first is extending the model’s abilities: giving it access to information or actions outside its own abilities. The second is facilitating something the model could, in principle, do, but that a tool can do more conveniently or reliably.

  4. Simon

    A good example of extending ability is getting current information. If a model’s knowledge is frozen at a point months ago, it can’t know today’s weather just by reasoning harder. It needs to call an external source. A web search can bring in fresh evidence and help ground the answer.

  5. Corey

    And a calculator is a good example of facilitation. A language model may be capable of doing arithmetic, but multiplying two seven-digit numbers through reasoning takes time and could go wrong. A calculator can return an exact result very quickly.

  6. Simon

    There are other kinds of tools, too. A model might access private state, such as information about a user, so it can tailor a response. Or it might change the external environment by browsing or calling an API. Those are different forms of reaching beyond a plain text response.

  7. Corey

    That’s why chat applications have changed so much. They began as text-in, text-out systems. Now an application can search, execute code, generate images, or interact with services. When it iteratively makes tool calls to answer a request, it’s acting as an agent, not merely a chat box.

  8. Simon

    Let’s walk through some common tool categories. The simplest is a textual response: the agent decides it has finished and gives the user an answer. In an agent loop, that can be represented with a special finish tool, or the loop can end when the agent chooses not to call another tool.

  9. Corey

    Searching the web is another common category, and it connects closely to retrieval-augmented generation, or RAG. The pattern is to retrieve relevant information and then generate an answer based on it. That approach has become so normal in applications that people may use it without thinking of it as a distinct technique.

  10. Simon

    Code execution is useful for calculations and other tasks where executing a program is more reliable or efficient than asking the model to work everything out in its own text. Image generation is another category, but it differs because the tool takes a prompt and returns an image rather than simply exchanging text.

  11. Corey

    And the prompt sent to an image generator may not be exactly the words the user typed. The language model can expand or refine the request before calling the image-generation tool. So part of using that tool well is choosing a useful query.

  12. Simon

    Then there are custom functions: for example, a request to buy bananas, milk, and coffee might lead to a function that creates a grocery cart through a service’s API. The set of possible tools is open-ended; you can add functions suited to the application.

  13. Corey

    One way to organize tools is to offer the model a collection of separate APIs—say, dozens of functions—and let it choose among them. Each step might call one tool, or several independent tools at once. But code is a special case because it can act as a meta-tool.

  14. Simon

    What makes code a meta-tool? A program can combine calls, use variables, and include loops and other control flow. You can also bring in libraries, such as pandas, or write utility functions of your own. That makes code a much richer way to orchestrate tools than selecting a single API at a time.

  15. Corey

    Imagine a task that asks which of several countries is the most cost-effective place to buy a phone. With separate tools, the agent might repeatedly look up exchange rates and phone prices, convert amounts, and check taxes. With code, it can write one program to perform the whole set of steps.

  16. Simon

    Research on a method called CodeAct found that this kind of approach can raise task success and reduce the average number of interaction turns. That benefit can apply even to tasks that were traditionally treated as ordinary tool-use tasks, not tasks that obviously required writing code.

  17. Corey

    But more expressive power comes with trade-offs. A program can get stuck in an infinite loop, so the surrounding system needs a way to deal with that. And code that can load libraries raises security concerns: a compromised library could compromise the agent’s system.

  18. Simon

    Code is also harder to constrain and validate predictably because it gives the agent a broad action space. It can consume memory, disk, or CPU. So programmatic tool use calls for careful containment, such as running the agent in a sandbox.

  19. Corey

    Now let’s look at how calls are represented. A model’s output can contain ordinary text and a structured tool call. In a ReAct-style pattern, the model may produce a user-facing message, then a tool call, and later a response based on the tool’s result. Reasoning models may also have a separate, verbose thinking section that isn’t shown to the user.

  20. Simon

    Tool calls are represented using tokens and message formats, not by some ability the model magically has to run a function. One question is whether those special tokens must already be in the vocabulary during pretraining. Often they’re introduced later, during mid-training on data in the desired format, rather than being present when the model first learns from the internet.

  21. Corey

    A chat API also has a message structure: system, user, and assistant messages, for example. A tool definition adds more structure. It can specify a function name, its parameters, their types, and which parameters are required. That schema is included in the request, and the model can produce a call with arguments, such as a weather request for Pittsburgh.

  22. Simon

    Different models can use different formats for the same basic idea. One may use one set of special tokens, another may use a different function-call format, and another may call the operation something else. The details matter: parsing code written for one model’s format won’t necessarily work for another’s.

  23. Corey

    That matters especially when fine-tuning. If a model has already been trained to use a particular tool-call format, you generally want your fine-tuning data to match it rather than asking it to use an unfamiliar format. Libraries such as Hugging Face provide chat-template functions to apply the format expected by a given model.

  24. Simon

    Once a call is generated, the agent has to parse it, find the registered tool by name, validate the arguments, and dispatch the call to the corresponding function. Frameworks commonly let you register tools implemented in languages such as Python or TypeScript.

  25. Corey

    A failure can happen during validation—for example, if the model supplies an invalid tool name or arguments. It can also happen during execution. A string might be accepted as Python code, for instance, but then fail when the system actually tries to run it. Either way, the agent needs to handle the result and produce an observation for the model.

  26. Simon

    Tool-call IDs are another practical detail. A call gets an identifier, and its result carries the matching ID. That’s especially useful when several calls happen in parallel, because it tells the system which result belongs to which call.

  27. Corey

    And some providers require the conversation history to contain a matching result for every tool call. If a program crashes after the assistant’s call but before it writes the result, resuming with that incomplete history can fail. So reliable systems need to preserve the call-and-result relationship.

  28. Simon

    Even if all that plumbing is correct, a model can generate malformed output. For example, it might produce JSON with a missing closing bracket. A normal JSON parser will reject it, which is why trying to patch malformed outputs after the fact can become frustrating.

  29. Corey

    A tool call can be checked at several levels. Syntax asks whether the output is valid JSON. Shape asks whether required fields are present. Types ask whether values have the right kinds—for example, whether a city is a string—and whether values such as units belong to the allowed set. These rules can be expressed using JSON Schema or another schema system.

  30. Simon

    Schemas can also be used to constrain generation. Regular expressions are one familiar kind of grammar, and finite-state automata can recognize regular grammars. But JSON schemas generally need the greater expressive power of a context-free grammar, which can describe nested structures such as JSON objects and arrays.

  31. Corey

    A pushdown automaton handles that kind of grammar by adding a stack. During generation, the system can track whether the next token is permitted in the current context. If it isn’t, it can mask that token’s logit—effectively assigning it negative infinity—then renormalize over the valid choices.

  32. Simon

    That’s the basic idea behind grammar-constrained decoding used in systems such as XGrammar. Some token-validity checks can be precomputed; others depend on the current context and are worked out as generation proceeds. When it’s configured properly, this can make well-formed calls much more reliable.

  33. Corey

    There’s an important limit, though: constrained decoding can keep generation on a valid path without guaranteeing that it reaches the end of a valid call. If the model runs out of its allotted output tokens halfway through the JSON, the result can still be incomplete.

  34. Simon

    And even a well-formed call can be wrong in meaning. A valid Python program may still do the wrong thing, and valid JSON may contain an inappropriate choice. Grammar constraints help with structure; they don’t guarantee semantic correctness.

  35. Corey

    Tools can be exposed in different ways. A traditional option is a REST API: a service offers endpoints that applications can call. FastAPI makes it relatively straightforward to create a Python backend, protect it with an API key, and describe its inputs in a machine-readable schema.

  36. Simon

    That schema can help describe which calls are allowed to a language model. A program can then send the model’s chosen call to the API server, where the actual work happens. A coding agent with access to a shell could also call a REST API using a command such as curl.

  37. Corey

    Another approach is the Model Context Protocol, or MCP. It provides a standard way for an AI application to connect with tool servers. At first glance, it may seem like an unnecessary detour when an agent can already call a REST API directly.

  38. Simon

    One important reason to use MCP is that it can add a layer between the agent and sensitive credentials. For example, the MCP server can hold a GitHub token while the agent receives only a separate MCP key. If the agent leaks its key, that’s less dangerous than exposing the actual upstream credential.

  39. Corey

    MCP also has its own ways to discover tools and invoke them, using MCP transports such as standard input and output or sockets. It can offer other conveniences, including resources, prompts, and extensions. FastMCP is a way to build MCP servers with an approach similar to FastAPI, and REST API specifications can also be adapted for MCP use.

  40. Simon

    So both direct APIs and MCP can provide tools, but they differ in discovery, invocation, and authentication. MCP registries can also help people find servers that provide capabilities they want.

  41. Corey

    Next up: parallel tool calling. If an agent needs the weather, today’s calendar, and a flight status, those requests may be independent, so it can make them together rather than waiting for one result before starting the next.

  42. Simon

    The key condition is independence. If you need to find a customer ID before fetching that customer’s orders, and then choose an order before issuing a refund, those calls have dependencies and can’t all happen at once. The same is true if one result determines what the next call should be.

  43. Corey

    When calls are independent, a system can execute them concurrently—for instance, by using asynchronous programming tools such as Python’s asyncio.gather—and collect the results together. The IDs we mentioned earlier help match each result to its original call.

  44. Simon

    Parallel calling can also change how efficient an agent is. A more expensive model may sometimes cost less per completed task if it is smart enough to choose a good solution quickly and makes effective parallel calls instead of stretching the work over many turns.

  45. Corey

    Models have improved at parallel calls in part because reinforcement learning can reward finishing tasks quickly. If a training setup strongly penalizes long task execution, making independent calls together is one way for a model to complete the task faster.

  46. Simon

    Finally, how do we evaluate tool use? The Berkeley Function Calling Leaderboard is a prominent benchmark that has expanded from single-turn calling to include multi-turn tool calling, tool-calling agents, and robustness measures such as argument hallucination and sensitivity to formats.

  47. Corey

    When evaluating the whole tool-use stack, you can ask whether the model chose the right tool, supplied the right arguments, and—when it’s an agent—used the tools in the right order. You can also measure end-to-end task accuracy, along with efficiency, reliability, and safety.

  48. Simon

    Efficiency includes things like how long the task takes, how many tokens it uses, and what it costs. Reliability includes whether the system responds well to timeouts or unavailable tools. Safety asks whether it avoids using tools in inappropriate ways, including when faced with adversarial requests or outputs.

  49. Corey

    A benchmark comparing tool-call errors across providers shows why the serving stack matters: the same named model can have very different error rates depending on who serves it. Different quantization levels can affect performance; heavier compression, such as FP4, may produce more mistaken calls than FP8, though results depend on the particular setup.

  50. Simon

    Other possible differences include decoding and inference algorithms, speculative decoding, and whether the provider uses constrained decoding. A provider that doesn’t support grammar-based constraints may be relying more heavily on the model to produce a valid call. And, more simply, an unreliable provider can go down and cause a call to fail.

  51. Corey

    So the big picture is that tool use is a layered system. Tools add abilities such as retrieval, computation, image generation, or interaction with applications. The model emits a call; the system validates it, dispatches it, executes it, and returns the matching result.

  52. Simon

    You can make that system more expressive with code, more structured with schemas, and more reliable at the syntax level with constrained decoding. You can connect tools through direct APIs or MCP, coordinate independent calls in parallel, and evaluate accuracy, efficiency, reliability, and safety. But none of that makes an agent’s decisions automatically correct, so the surrounding system still matters.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent