Skip to main content
Open In ColabOpen on GitHub

如何将临时工具调用功能添加到 LLM 和聊天模型中

注意

一些模型已经针对工具调用进行了微调,并提供了专门用于工具调用的 API。通常,这类模型在工具调用方面比未微调的模型表现更好,推荐用于需要工具调用的场景。有关更多信息,请参阅如何使用聊天模型调用工具指南。

前置条件

本指南假设您熟悉以下概念:

在本指南中,我们将了解如何为聊天模型添加 即席 工具调用支持。如果您使用的模型不原生支持 工具调用,这是一种替代的调用工具的方法。

我们将通过简单地编写一个提示词来实现这一点,该提示词将促使模型调用相应的工具。以下是逻辑的图示:

chain

设置

我们需要安装以下软件包:

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

如果您想使用 LangSmith,请取消下面的注释:

import getpass
import os
# os.environ["LANGSMITH_TRACING"] = "true"
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass()

您可以从以下模型中任选其一进行本指南的操作。请注意,这些模型中的大多数已经支持原生工具调用,因此使用此处展示的提示策略对这些模型而言并无意义;相反,您应遵循如何使用聊天模型调用工具的指南。

pip install -qU "langchain[openai]"
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain.chat_models import init_chat_model

model = init_chat_model("gpt-4", model_provider="openai")

为了说明这个概念,我们将使用 phi3 通过 Ollama,它原生支持工具调用。如果您也想使用 Ollama,请遵循 这些说明

from langchain_community.llms import Ollama

model = Ollama(model="phi3")
API 参考:Ollama

创建一个工具

首先,让我们创建 addmultiply 工具。有关创建自定义工具的更多信息,请参阅 此指南

from langchain_core.tools import tool


@tool
def multiply(x: float, y: float) -> float:
"""Multiply two numbers together."""
return x * y


@tool
def add(x: int, y: int) -> int:
"Add two numbers."
return x + y


tools = [multiply, add]

# Let's inspect the tools
for t in tools:
print("--")
print(t.name)
print(t.description)
print(t.args)
API 参考:工具
--
multiply
Multiply two numbers together.
{'x': {'title': 'X', 'type': 'number'}, 'y': {'title': 'Y', 'type': 'number'}}
--
add
Add two numbers.
{'x': {'title': 'X', 'type': 'integer'}, 'y': {'title': 'Y', 'type': 'integer'}}
multiply.invoke({"x": 4, "y": 5})
20.0

创建我们的提示

我们将编写一个提示,指定模型可访问的工具、这些工具的参数以及模型的期望输出格式。在这种情况下,我们将指示它输出如下形式的 JSON 数据块 {"name": "...", "arguments": {...}}

from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import render_text_description

rendered_tools = render_text_description(tools)
print(rendered_tools)
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 | model
message = 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
}
}

添加输出解析器

我们将使用 JsonOutputParser 来将模型的输出解析为 JSON。

from langchain_core.output_parsers import JsonOutputParser

chain = prompt | model | JsonOutputParser()
chain.invoke({"input": "what's thirteen times 4"})
API 参考:JsonOutputParser
{'name': 'multiply', 'arguments': {'x': 13.0, 'y': 4.0}}
重要

🎉 太棒了!🎉 我们现在已指导我们的模型如何请求调用一个工具。

现在,让我们创建一些逻辑来实际运行工具!

调用工具 🏃

既然模型现在可以请求调用某个工具,我们需要编写一个函数来实际执行该工具的调用。

该函数将根据名称选择合适的工具,并将模型选择的参数传递给它。

from typing import Any, Dict, Optional, TypedDict

from langchain_core.runnables import RunnableConfig


class 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 参考:可运行配置

让我们测试一下 🧪!

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

让我们把它组合起来

让我们将其组合成一个链,创建一个具有加法和乘法功能的计算器。

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

返回工具输入

返回工具输入不仅有助于理解工具输出。我们可以轻松地在 LCEL 中通过 RunnablePassthrough.assign-ing 工具输出来实现这一点。这将把传递给 RunnablePassrthrough 组件的任意输入(假定为字典)添加一个键,同时仍传递当前输入中的所有所有内容:

from langchain_core.runnables import RunnablePassthrough

chain = (
prompt | model | JsonOutputParser() | RunnablePassthrough.assign(output=invoke_tool)
)
chain.invoke({"input": "what's thirteen times 4.14137281"})
{'name': 'multiply',
'arguments': {'x': 13, 'y': 4.14137281},
'output': 53.83784653}

下一步?

本操操作指南展示了当模型正确输出所有必需的工具信息时的“理想路径”。

实际上,如果您使用更复杂的工具,您将开始遇到来自模型的错误,特别是对于未经过工具调用微调的模型以及能力较弱的模型。

您需要准备好添加策略以提高模型的输出;例如,

  1. 提供少样本示例。
  2. 添加错误处理(例如,捕获异常并将其反馈给大语言模型,要求其纠正之前的输出)。