Skip to main content
Open In ColabOpen on GitHub

如何在链中使用工具

在本指南中,我们将介绍创建调用 工具 的链(Chains)和智能体(Agents)的基本方法。工具几乎可以是任何事物——API、函数、数据库等。工具使我们能够扩展模型的能力,使其不仅仅输出文本或消息。使用带工具的模型的关键在于正确地对模型进行提示,并解析其响应,以便它选择合适的工具并提供正确的输入。

设置

我们需要为本指南安装以下包:

%pip install --upgrade --quiet langchain

如果您希望在使用 LangSmith 追踪您的运行,请取消注释并设置以下环境变量:

import getpass
import os

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

创建一个工具

首先,我们需要创建一个要调用的工具。在本示例中,我们将基于函数创建一个自定义工具。有关创建自定义工具的更多信息,请参阅 此指南

from langchain_core.tools import tool


@tool
def multiply(first_int: int, second_int: int) -> int:
"""Multiply two integers together."""
return first_int * second_int
API 参考:工具
print(multiply.name)
print(multiply.description)
print(multiply.args)
multiply
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

链式操作

如果我们知道只需要固定次数地使用一个工具,我们就可以创建一个用于此目的的链。让我们创建一个简单的链,仅将用户指定的数字相乘。

chain

工具/函数调用

使用 LLM 与工具交互最可靠的方法之一是使用 工具调用 API(有时也称为函数调用)。这仅适用于明确支持工具调用的模型。您可以在 此处 查看哪些模型支持工具调用,并在 本指南 中了解更多关于如何使用工具调用的内容。

首先,我们将定义我们的模型和工具。我们将从单个工具 multiply 开始。

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

llm = init_chat_model("gpt-4o-mini", model_provider="openai")

我们将使用 bind_tools 将我们的工具定义作为每次调用模型的一部分传入,以便模型在适当时能够调用该工具:

llm_with_tools = llm.bind_tools([multiply])

当模型调用工具时,这将显示在输出的 AIMessage.tool_calls 属性中:

msg = llm_with_tools.invoke("whats 5 times forty two")
msg.tool_calls
[{'name': 'multiply',
'args': {'first_int': 5, 'second_int': 42},
'id': 'call_8QIg4QVFVAEeC1orWAgB2036',
'type': 'tool_call'}]

查看 LangSmith 追踪记录

调用工具

太好了!我们已经能够生成工具调用。但如果我们想实际调用该工具呢?为此,我们需要将生成的工具参数传递给我们的工具。作为一个简单的例子,我们将提取第一个 tool_call 的参数:

from operator import itemgetter

chain = llm_with_tools | (lambda x: x.tool_calls[0]["args"]) | multiply
chain.invoke("What's four times 23")
92

查看 LangSmith 追踪记录

代理

当我们知道任何用户输入所需的具体工具使用序列时,Chains(链)非常有用。但对于某些用例,工具的使用次数取决于输入内容。在这些情况下,我们希望让模型自己决定使用工具的次数和顺序。Agents(智能体) 正是为此而设计的。

我们将使用 LangGraph agent 演示一个简单示例。有关更多详细信息,请查看 此教程

agent

!pip install -qU langgraph
from langgraph.prebuilt import create_react_agent

代理也非常棒,因为它们使得使用多个工具变得容易。

@tool
def add(first_int: int, second_int: int) -> int:
"Add two integers."
return first_int + second_int


@tool
def exponentiate(base: int, exponent: int) -> int:
"Exponentiate the base to the exponent power."
return base**exponent


tools = [multiply, add, exponentiate]
# Construct the tool calling agent
agent = create_react_agent(llm, tools)

通过智能体,我们可以提出需要任意多次使用工具的问题:

# Use the agent

query = (
"Take 3 to the fifth power and multiply that by the sum of twelve and "
"three, then square the whole result."
)
input_message = {"role": "user", "content": query}

for step in agent.stream({"messages": [input_message]}, stream_mode="values"):
step["messages"][-1].pretty_print()
================================ Human Message =================================

Take 3 to the fifth power and multiply that by the sum of twelve and three, then square the whole result.
================================== Ai Message ==================================
Tool Calls:
exponentiate (call_EHGS8gnEVNCJQ9rVOk11KCQH)
Call ID: call_EHGS8gnEVNCJQ9rVOk11KCQH
Args:
base: 3
exponent: 5
add (call_s2cxOrXEKqI6z7LWbMUG6s8c)
Call ID: call_s2cxOrXEKqI6z7LWbMUG6s8c
Args:
first_int: 12
second_int: 3
================================= Tool Message =================================
Name: add

15
================================== Ai Message ==================================
Tool Calls:
multiply (call_25v5JEfDWuKNgmVoGBan0d7J)
Call ID: call_25v5JEfDWuKNgmVoGBan0d7J
Args:
first_int: 243
second_int: 15
================================= Tool Message =================================
Name: multiply

3645
================================== Ai Message ==================================
Tool Calls:
exponentiate (call_x1yKEeBPrFYmCp2z5Kn8705r)
Call ID: call_x1yKEeBPrFYmCp2z5Kn8705r
Args:
base: 3645
exponent: 2
================================= Tool Message =================================
Name: exponentiate

13286025
================================== Ai Message ==================================

The final result of taking 3 to the fifth power, multiplying it by the sum of twelve and three, and then squaring the whole result is **13,286,025**.

查看 LangSmith 追踪记录