*   [](/v0.2/)
*   [How-to guides](/v0.2/docs/how_to/)
*   How to add ad-hoc tool calling capability to LLMs and Chat Models

On this page

How to add ad-hoc tool calling capability to LLMs and Chat Models
=================================================================

caution

Some models have been fine-tuned for tool calling and provide a dedicated API for tool calling. Generally, such models are better at tool calling than non-fine-tuned models, and are recommended for use cases that require tool calling. Please see the [how to use a chat model to call tools](/v0.2/docs/how_to/tool_calling/) guide for more information.

Prerequisites

This guide assumes familiarity with the following concepts:

*   [LangChain Tools](/v0.2/docs/concepts/#tools)
*   [Function/tool calling](https://python.langchain.com/v0.2/docs/concepts/#functiontool-calling)
*   [Chat models](/v0.2/docs/concepts/#chat-models)
*   [LLMs](/v0.2/docs/concepts/#llms)

In this guide, we'll see how to add **ad-hoc** tool calling support to a chat model. This is an alternative method to invoke tools if you're using a model that does not natively support [tool calling](/v0.2/docs/how_to/tool_calling/).

We'll do this by simply writing a prompt that will get the model to invoke the appropriate tools. Here's a diagram of the logic:

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

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

We'll need to install the following packages:

    %pip install --upgrade --quiet langchain langchain-community

If you'd like to use LangSmith, uncomment the below:

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

You can select any of the given models for this how-to guide. Keep in mind that most of these models already [support native tool calling](/v0.2/docs/integrations/chat/), so using the prompting strategy shown here doesn't make sense for these models, and instead you should follow the [how to use a chat model to call tools](/v0.2/docs/how_to/tool_calling/) guide.

*   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 ChatOpenAImodel = ChatOpenAI(model="gpt-4")

    pip install -qU langchain-anthropic

    import getpassimport osos.environ["ANTHROPIC_API_KEY"] = getpass.getpass()from langchain_anthropic import ChatAnthropicmodel = 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 AzureChatOpenAImodel = 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 ChatVertexAImodel = ChatVertexAI(model="gemini-pro")

    pip install -qU langchain-cohere

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

    pip install -qU langchain-fireworks

    import getpassimport osos.environ["FIREWORKS_API_KEY"] = getpass.getpass()from langchain_fireworks import ChatFireworksmodel = 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 ChatGroqmodel = ChatGroq(model="llama3-8b-8192")

    pip install -qU langchain-mistralai

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

    pip install -qU langchain-openai

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

To illustrate the idea, we'll use `phi3` via Ollama, which does **NOT** have native support for tool calling. If you'd like to use `Ollama` as well follow [these instructions](/v0.2/docs/integrations/chat/ollama/).

    from langchain_community.llms import Ollamamodel = Ollama(model="phi3")

**API Reference:**[Ollama](https://api.python.langchain.com/en/latest/llms/langchain_community.llms.ollama.Ollama.html)

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

First, let's create an `add` and `multiply` tools. 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(x: float, y: float) -> float:    """Multiply two numbers together."""    return x * y@tooldef add(x: int, y: int) -> int:    "Add two numbers."    return x + ytools = [multiply, add]# Let's inspect the toolsfor t in tools:    print("--")    print(t.name)    print(t.description)    print(t.args)

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

    --multiplyMultiply two numbers together.{'x': {'title': 'X', 'type': 'number'}, 'y': {'title': 'Y', 'type': 'number'}}--addAdd two numbers.{'x': {'title': 'X', 'type': 'integer'}, 'y': {'title': 'Y', 'type': 'integer'}}

    multiply.invoke({"x": 4, "y": 5})

    20.0

Creating our prompt[​](#creating-our-prompt "Direct link to Creating our prompt")
---------------------------------------------------------------------------------

We'll want to write a prompt that specifies the tools the model has access to, the arguments to those tools, and the desired output format of the model. In this case we'll instruct it to output a JSON blob of the form `{"name": "...", "arguments": {...}}`.

    from langchain_core.output_parsers import JsonOutputParserfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.tools import render_text_descriptionrendered_tools = render_text_description(tools)print(rendered_tools)

**API Reference:**[JsonOutputParser](https://api.python.langchain.com/en/latest/output_parsers/langchain_core.output_parsers.json.JsonOutputParser.html) | [ChatPromptTemplate](https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.chat.ChatPromptTemplate.html) | [render\_text\_description](https://api.python.langchain.com/en/latest/tools/langchain_core.tools.render_text_description.html)

    multiply(x: float, y: float) -> float - Multiply two numbers together.add(x: int, y: int) -> int - Add two numbers.

    system_prompt = f"""\You are an assistant that has access to the following set of tools. Here are the names and descriptions for each tool:{rendered_tools}Given the user input, return the name and input of the tool to use. Return your response as a JSON blob with 'name' and 'arguments' keys.The `arguments` should be a dictionary, with keys corresponding to the argument names and the values corresponding to the requested values."""prompt = ChatPromptTemplate.from_messages(    [("system", system_prompt), ("user", "{input}")])

    chain = prompt | modelmessage = chain.invoke({"input": "what's 3 plus 1132"})# Let's take a look at the output from the model# if the model is an LLM (not a chat model), the output will be a string.if isinstance(message, str):    print(message)else:  # Otherwise it's a chat model    print(message.content)

    {    "name": "add",    "arguments": {        "x": 3,        "y": 1132    }}

Adding an output parser[​](#adding-an-output-parser "Direct link to Adding an output parser")
---------------------------------------------------------------------------------------------

We'll use the `JsonOutputParser` for parsing our models output to JSON.

    from langchain_core.output_parsers import JsonOutputParserchain = prompt | model | JsonOutputParser()chain.invoke({"input": "what's thirteen times 4"})

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

    {'name': 'multiply', 'arguments': {'x': 13.0, 'y': 4.0}}

info

🎉 Amazing! 🎉 We now instructed our model on how to **request** that a tool be invoked.

Now, let's create some logic to actually run the tool!

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

Now that the model can request that a tool be invoked, we need to write a function that can actually invoke the tool.

The function will select the appropriate tool by name, and pass to it the arguments chosen by the model.

    from typing import Any, Dict, Optional, TypedDictfrom langchain_core.runnables import RunnableConfigclass ToolCallRequest(TypedDict):    """A typed dict that shows the inputs into the invoke_tool function."""    name: str    arguments: Dict[str, Any]def invoke_tool(    tool_call_request: ToolCallRequest, config: Optional[RunnableConfig] = None):    """A function that we can use the perform a tool invocation.    Args:        tool_call_request: a dict that contains the keys name and arguments.            The name must match the name of a tool that exists.            The arguments are the arguments to that tool.        config: This is configuration information that LangChain uses that contains            things like callbacks, metadata, etc.See LCEL documentation about RunnableConfig.    Returns:        output from the requested tool    """    tool_name_to_tool = {tool.name: tool for tool in tools}    name = tool_call_request["name"]    requested_tool = tool_name_to_tool[name]    return requested_tool.invoke(tool_call_request["arguments"], config=config)

**API Reference:**[RunnableConfig](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.config.RunnableConfig.html)

Let's test this out 🧪!

    invoke_tool({"name": "multiply", "arguments": {"x": 3, "y": 5}})

    15.0

Let's put it together[​](#lets-put-it-together "Direct link to Let's put it together")
--------------------------------------------------------------------------------------

Let's put it together into a chain that creates a calculator with add and multiplication capabilities.

    chain = prompt | model | JsonOutputParser() | invoke_toolchain.invoke({"input": "what's thirteen times 4.14137281"})

    53.83784653

Returning tool inputs[​](#returning-tool-inputs "Direct link to Returning tool inputs")
---------------------------------------------------------------------------------------

It can be helpful to return not only tool outputs but also tool inputs. We can easily do this with LCEL by `RunnablePassthrough.assign`\-ing the tool output. This will take whatever the input is to the RunnablePassrthrough components (assumed to be a dictionary) and add a key to it while still passing through everything that's currently in the input:

    from langchain_core.runnables import RunnablePassthroughchain = (    prompt | model | JsonOutputParser() | RunnablePassthrough.assign(output=invoke_tool))chain.invoke({"input": "what's thirteen times 4.14137281"})

**API Reference:**[RunnablePassthrough](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.passthrough.RunnablePassthrough.html)

    {'name': 'multiply', 'arguments': {'x': 13, 'y': 4.14137281}, 'output': 53.83784653}

What's next?[​](#whats-next "Direct link to What's next?")
----------------------------------------------------------

This how-to guide shows the "happy path" when the model correctly outputs all the required tool information.

In reality, if you're using more complex tools, you will start encountering errors from the model, especially for models that have not been fine tuned for tool calling and for less capable models.

You will need to be prepared to add strategies to improve the output from the model; e.g.,

1.  Provide few shot examples.
2.  Add error handling (e.g., catch the exception and feed it back to the LLM to ask it to correct its previous output).

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

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

Next

Build an Agent with AgentExecutor (Legacy)

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

*   [Setup](#setup)
*   [Create a tool](#create-a-tool)
*   [Creating our prompt](#creating-our-prompt)
*   [Adding an output parser](#adding-an-output-parser)
*   [Invoking the tool 🏃](#invoking-the-tool-)
*   [Let's put it together](#lets-put-it-together)
*   [Returning tool inputs](#returning-tool-inputs)
*   [What's next?](#whats-next)