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

On this page

How to use tools in a chain
===========================

In this guide, we will go over the basic ways to create Chains and Agents that call Tools. Tools can be just about anything — APIs, functions, databases, etc. Tools allow us to extend the capabilities of a model beyond just outputting text/messages. The key to using models with tools is correctly prompting a model and parsing its response so that it chooses the right tools and provides the right inputs for them.

Setup[​](#setup "Direct link to Setup")
---------------------------------------

We'll need to install the following packages for this guide:

    %pip install --upgrade --quiet langchain

If you'd like to trace your runs in [LangSmith](https://docs.smith.langchain.com/) uncomment and set the following environment variables:

    import getpassimport os# os.environ["LANGCHAIN_TRACING_V2"] = "true"# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()

Create a tool[​](#create-a-tool "Direct link to Create a tool")
---------------------------------------------------------------

First, we need to create a tool to call. For this example, we will create a custom tool from a function. For more information on creating custom tools, please see [this guide](/v0.2/docs/how_to/custom_tools/).

    from langchain_core.tools import tool@tooldef multiply(first_int: int, second_int: int) -> int:    """Multiply two integers together."""    return first_int * second_int

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

    print(multiply.name)print(multiply.description)print(multiply.args)

    multiplymultiply(first_int: int, second_int: int) -> int - Multiply two integers together.{'first_int': {'title': 'First Int', 'type': 'integer'}, 'second_int': {'title': 'Second Int', 'type': 'integer'}}

    multiply.invoke({"first_int": 4, "second_int": 5})

    20

Chains[​](#chains "Direct link to Chains")
------------------------------------------

If we know that we only need to use a tool a fixed number of times, we can create a chain for doing so. Let's create a simple chain that just multiplies user-specified numbers.

![chain](/v0.2/assets/images/tool_chain-3571e7fbc481d648aff93a2630f812ab.svg)

### Tool/function calling[​](#toolfunction-calling "Direct link to Tool/function calling")

One of the most reliable ways to use tools with LLMs is with tool calling APIs (also sometimes called function calling). This only works with models that explicitly support tool calling. You can see which models support tool calling [here](/v0.2/docs/integrations/chat/), and learn more about how to use tool calling in [this guide](/v0.2/docs/how_to/function_calling/).

First we'll define our model and tools. We'll start with just a single tool, `multiply`.

*   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/mixtral-8x7b-instruct")

    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 `bind_tools` to pass the definition of our tool in as part of each call to the model, so that the model can invoke the tool when appropriate:

    llm_with_tools = llm.bind_tools([multiply])

When the model invokes the tool, this will show up in the `AIMessage.tool_calls` attribute of the output:

    msg = llm_with_tools.invoke("whats 5 times forty two")msg.tool_calls

    [{'name': 'multiply',  'args': {'first_int': 5, 'second_int': 42},  'id': 'call_cCP9oA3tRz7HDrjFn1FdmDaG'}]

Check out the [LangSmith trace here](https://smith.langchain.com/public/81ff0cbd-e05b-4720-bf61-2c9807edb708/r).

### Invoking the tool[​](#invoking-the-tool "Direct link to Invoking the tool")

Great! We're able to generate tool invocations. But what if we want to actually call the tool? To do so we'll need to pass the generated tool args to our tool. As a simple example we'll just extract the arguments of the first tool\_call:

    from operator import itemgetterchain = llm_with_tools | (lambda x: x.tool_calls[0]["args"]) | multiplychain.invoke("What's four times 23")

    92

Check out the [LangSmith trace here](https://smith.langchain.com/public/16bbabb9-fc9b-41e5-a33d-487c42df4f85/r).

Agents[​](#agents "Direct link to Agents")
------------------------------------------

Chains are great when we know the specific sequence of tool usage needed for any user input. But for certain use cases, how many times we use tools depends on the input. In these cases, we want to let the model itself decide how many times to use tools and in what order. [Agents](/v0.2/docs/tutorials/agents/) let us do just this.

LangChain comes with a number of built-in agents that are optimized for different use cases. Read about all the [agent types here](/v0.2/docs/concepts/#agents).

We'll use the [tool calling agent](https://api.python.langchain.com/en/latest/agents/langchain.agents.tool_calling_agent.base.create_tool_calling_agent.html), which is generally the most reliable kind and the recommended one for most use cases.

![agent](/v0.2/assets/images/tool_agent-d25fafc271da3ee950ac1fba59cdf490.svg)

    from langchain import hubfrom langchain.agents import AgentExecutor, create_tool_calling_agent

**API Reference:**[AgentExecutor](https://api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html) | [create\_tool\_calling\_agent](https://api.python.langchain.com/en/latest/agents/langchain.agents.tool_calling_agent.base.create_tool_calling_agent.html)

    # Get the prompt to use - can be replaced with any prompt that includes variables "agent_scratchpad" and "input"!prompt = hub.pull("hwchase17/openai-tools-agent")prompt.pretty_print()

    ================================[1m System Message [0m================================You are a helpful assistant=============================[1m Messages Placeholder [0m=============================[33;1m[1;3m{chat_history}[0m================================[1m Human Message [0m=================================[33;1m[1;3m{input}[0m=============================[1m Messages Placeholder [0m=============================[33;1m[1;3m{agent_scratchpad}[0m

Agents are also great because they make it easy to use multiple tools.

    @tooldef add(first_int: int, second_int: int) -> int:    "Add two integers."    return first_int + second_int@tooldef exponentiate(base: int, exponent: int) -> int:    "Exponentiate the base to the exponent power."    return base**exponenttools = [multiply, add, exponentiate]

    # Construct the tool calling agentagent = create_tool_calling_agent(llm, tools, prompt)

    # Create an agent executor by passing in the agent and toolsagent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

With an agent, we can ask questions that require arbitrarily-many uses of our tools:

    agent_executor.invoke(    {        "input": "Take 3 to the fifth power and multiply that by the sum of twelve and three, then square the whole result"    })

    [1m> Entering new AgentExecutor chain...[0m[32;1m[1;3mInvoking: `exponentiate` with `{'base': 3, 'exponent': 5}`[0m[38;5;200m[1;3m243[0m[32;1m[1;3mInvoking: `add` with `{'first_int': 12, 'second_int': 3}`[0m[33;1m[1;3m15[0m[32;1m[1;3mInvoking: `multiply` with `{'first_int': 243, 'second_int': 15}`[0m[36;1m[1;3m3645[0m[32;1m[1;3mInvoking: `exponentiate` with `{'base': 405, 'exponent': 2}`[0m[38;5;200m[1;3m164025[0m[32;1m[1;3mThe result of taking 3 to the fifth power is 243. The sum of twelve and three is 15. Multiplying 243 by 15 gives 3645. Finally, squaring 3645 gives 164025.[0m[1m> Finished chain.[0m

    {'input': 'Take 3 to the fifth power and multiply that by the sum of twelve and three, then square the whole result', 'output': 'The result of taking 3 to the fifth power is 243. \n\nThe sum of twelve and three is 15. \n\nMultiplying 243 by 15 gives 3645. \n\nFinally, squaring 3645 gives 164025.'}

Check out the [LangSmith trace here](https://smith.langchain.com/public/eeeb27a4-a2f8-4f06-a3af-9c983f76146c/r).

[Edit this page](https://github.com/langchain-ai/langchain/edit/master/docs/docs/how_to/tools_chain.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 guides

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

Next

How to use a vectorstore as a retriever

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

*   [Setup](#setup)
*   [Create a tool](#create-a-tool)
*   [Chains](#chains)
    *   [Tool/function calling](#toolfunction-calling)
    *   [Invoking the tool](#invoking-the-tool)
*   [Agents](#agents)