*   [](/v0.2/)
*   [How-to guides](/v0.2/docs/how_to/)
*   How to use a model to call tools

On this page

How to use a model to call tools
================================

Prerequisites

This guide assumes familiarity with the following concepts:

*   [Chat models](/v0.2/docs/concepts/#chat-models)
*   [LangChain Tools](/v0.2/docs/concepts/#tools)

Tool calling vs function calling

We use the term tool calling interchangeably with function calling. Although function calling is sometimes meant to refer to invocations of a single function, we treat all models as though they can return multiple tool or function calls in each message.

Supported models

You can find a [list of all models that support tool calling](/v0.2/docs/integrations/chat/).

Tool calling allows a chat model to respond to a given prompt by "calling a tool". While the name implies that the model is performing some action, this is actually not the case! The model generates the arguments to a tool, and actually running the tool (or not) is up to the user. For example, if you want to [extract output matching some schema](/v0.2/docs/how_to/structured_output/) from unstructured text, you could give the model an "extraction" tool that takes parameters matching the desired schema, then treat the generated output as your final result.

However, tool calling goes beyond [structured output](/v0.2/docs/how_to/structured_output/) since you can pass responses from called tools back to the model to create longer interactions. For instance, given a search engine tool, an LLM might handle a query by first issuing a call to the search engine with arguments. The system calling the LLM can receive the tool call, execute it, and return the output to the LLM to inform its response. LangChain includes a suite of [built-in tools](/v0.2/docs/integrations/tools/) and supports several methods for defining your own [custom tools](/v0.2/docs/how_to/custom_tools/).

Tool calling is not universal, but many popular LLM providers, including [Anthropic](https://www.anthropic.com/), [Cohere](https://cohere.com/), [Google](https://cloud.google.com/vertex-ai), [Mistral](https://mistral.ai/), [OpenAI](https://openai.com/), and others, support variants of a tool calling feature.

LangChain implements standard interfaces for defining tools, passing them to LLMs, and representing tool calls. This guide and the other How-to pages in the Tool section will show you how to use tools with LangChain.

Passing tools to chat models[​](#passing-tools-to-chat-models "Direct link to Passing tools to chat models")
------------------------------------------------------------------------------------------------------------

Chat models that support tool calling features implement a `.bind_tools` method, which receives a list of LangChain [tool objects](https://api.python.langchain.com/en/latest/tools/langchain_core.tools.BaseTool.html#langchain_core.tools.BaseTool) and binds them to the chat model in its expected format. Subsequent invocations of the chat model will include tool schemas in its calls to the LLM.

For example, we can define the schema for custom tools using the `@tool` decorator on Python functions:

    from langchain_core.tools import tool@tooldef add(a: int, b: int) -> int:    """Adds a and b."""    return a + b@tooldef multiply(a: int, b: int) -> int:    """Multiplies a and b."""    return a * btools = [add, multiply]

**API Reference:**[tool](https://api.python.langchain.com/en/latest/tools/langchain_core.tools.tool.html)

Or below, we define the schema using [Pydantic](https://docs.pydantic.dev):

    from langchain_core.pydantic_v1 import BaseModel, Field# Note that the docstrings here are crucial, as they will be passed along# to the model along with the class name.class Add(BaseModel):    """Add two integers together."""    a: int = Field(..., description="First integer")    b: int = Field(..., description="Second integer")class Multiply(BaseModel):    """Multiply two integers together."""    a: int = Field(..., description="First integer")    b: int = Field(..., description="Second integer")tools = [Add, Multiply]

We can bind them to chat models as follows:

*   OpenAI
*   Anthropic
*   Azure
*   Google
*   Cohere
*   FireworksAI
*   Groq
*   MistralAI
*   TogetherAI

    pip install -qU langchain-openai

    import getpassimport osos.environ["OPENAI_API_KEY"] = getpass.getpass()from langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-3.5-turbo-0125")

    pip install -qU langchain-anthropic

    import getpassimport osos.environ["ANTHROPIC_API_KEY"] = getpass.getpass()from langchain_anthropic import ChatAnthropicllm = ChatAnthropic(model="claude-3-sonnet-20240229")

    pip install -qU langchain-openai

    import getpassimport osos.environ["AZURE_OPENAI_API_KEY"] = getpass.getpass()from langchain_openai import AzureChatOpenAIllm = AzureChatOpenAI(    azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],    azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],    openai_api_version=os.environ["AZURE_OPENAI_API_VERSION"],)

    pip install -qU langchain-google-vertexai

    import getpassimport osos.environ["GOOGLE_API_KEY"] = getpass.getpass()from langchain_google_vertexai import ChatVertexAIllm = ChatVertexAI(model="gemini-pro")

    pip install -qU langchain-cohere

    import getpassimport osos.environ["COHERE_API_KEY"] = getpass.getpass()from langchain_cohere import ChatCoherellm = ChatCohere(model="command-r")

    pip install -qU langchain-fireworks

    import getpassimport osos.environ["FIREWORKS_API_KEY"] = getpass.getpass()from langchain_fireworks import ChatFireworksllm = ChatFireworks(model="accounts/fireworks/models/firefunction-v1", temperature=0)

    pip install -qU langchain-groq

    import getpassimport osos.environ["GROQ_API_KEY"] = getpass.getpass()from langchain_groq import ChatGroqllm = ChatGroq(model="llama3-8b-8192")

    pip install -qU langchain-mistralai

    import getpassimport osos.environ["MISTRAL_API_KEY"] = getpass.getpass()from langchain_mistralai import ChatMistralAIllm = ChatMistralAI(model="mistral-large-latest")

    pip install -qU langchain-openai

    import getpassimport osos.environ["TOGETHER_API_KEY"] = getpass.getpass()from langchain_openai import ChatOpenAIllm = ChatOpenAI(    base_url="https://api.together.xyz/v1",    api_key=os.environ["TOGETHER_API_KEY"],    model="mistralai/Mixtral-8x7B-Instruct-v0.1",)

We'll use the `.bind_tools()` method to handle converting `Multiply` to the proper format for the model, then and bind it (i.e., passing it in each time the model is invoked).

    llm_with_tools = llm.bind_tools(tools)

As we can see, even though the prompt didn't really suggest a tool call, our LLM made one since it was forced to do so. You can look at the docs for [`bind_tool`](https://api.python.langchain.com/en/latest/chat_models/langchain_openai.chat_models.base.BaseChatOpenAI.html#langchain_openai.chat_models.base.BaseChatOpenAI.bind_tools) to learn about all the ways to customize how your LLM selects tools.

Tool calls[​](#tool-calls "Direct link to Tool calls")
------------------------------------------------------

If tool calls are included in a LLM response, they are attached to the corresponding [message](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.ai.AIMessage.html#langchain_core.messages.ai.AIMessage) or [message chunk](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.ai.AIMessageChunk.html#langchain_core.messages.ai.AIMessageChunk) as a list of [tool call](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.tool.ToolCall.html#langchain_core.messages.tool.ToolCall) objects in the `.tool_calls` attribute.

Note that chat models can call multiple tools at once.

A `ToolCall` is a typed dict that includes a tool name, dict of argument values, and (optionally) an identifier. Messages with no tool calls default to an empty list for this attribute.

    query = "What is 3 * 12? Also, what is 11 + 49?"llm_with_tools.invoke(query).tool_calls

    [{'name': 'Multiply',  'args': {'a': 3, 'b': 12},  'id': 'call_KquHA7mSbgtAkpkmRPaFnJKa'}, {'name': 'Add',  'args': {'a': 11, 'b': 49},  'id': 'call_Fl0hQi4IBTzlpaJYlM5kPQhE'}]

The `.tool_calls` attribute should contain valid tool calls. Note that on occasion, model providers may output malformed tool calls (e.g., arguments that are not valid JSON). When parsing fails in these cases, instances of [InvalidToolCall](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.tool.InvalidToolCall.html#langchain_core.messages.tool.InvalidToolCall) are populated in the `.invalid_tool_calls` attribute. An `InvalidToolCall` can have a name, string arguments, identifier, and error message.

If desired, [output parsers](/v0.2/docs/how_to/#output-parsers) can further process the output. For example, we can convert back to the original Pydantic class:

    from langchain_core.output_parsers.openai_tools import PydanticToolsParserchain = llm_with_tools | PydanticToolsParser(tools=[Multiply, Add])chain.invoke(query)

**API Reference:**[PydanticToolsParser](https://api.python.langchain.com/en/latest/output_parsers/langchain_core.output_parsers.openai_tools.PydanticToolsParser.html)

    [Multiply(a=3, b=12), Add(a=11, b=49)]

Next steps[​](#next-steps "Direct link to Next steps")
------------------------------------------------------

Now you've learned how to bind tool schemas to a chat model and to call those tools. Next, you can learn more about how to use tools:

*   Few shot promting [with tools](/v0.2/docs/how_to/tools_few_shot/)
*   Stream [tool calls](/v0.2/docs/how_to/tool_streaming/)
*   Bind [model-specific tools](/v0.2/docs/how_to/tools_model_specific/)
*   Pass [runtime values to tools](/v0.2/docs/how_to/tool_runtime/)
*   Pass [tool results back to model](/v0.2/docs/how_to/tool_results_pass_to_model/)

You can also check out some more specific uses of tool calling:

*   Building [tool-using chains and agents](/v0.2/docs/how_to/#tools)
*   Getting [structured outputs](/v0.2/docs/how_to/structured_output/) from models

[Edit this page](https://github.com/langchain-ai/langchain/edit/master/docs/docs/how_to/tool_calling.ipynb)

* * *

#### Was this page helpful?

  

#### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchain/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E).

[

Previous

How to use a time-weighted vector store retriever

](/v0.2/docs/how_to/time_weighted_vectorstore/)[

Next

tool\_calling\_parallel

](/v0.2/docs/how_to/tool_calling_parallel/)

*   [Passing tools to chat models](#passing-tools-to-chat-models)
*   [Tool calls](#tool-calls)
*   [Next steps](#next-steps)