如何在链中使用工具
在本指南中,我们将介绍创建调用工具的链和代理的基本方法。工具几乎可以是任何东西——API、函数、数据库等等。工具使我们能够扩展模型的功能,使其不仅仅输出文本/消息。将模型与工具一起使用的关键是正确地提示模型并解析其响应,以便它选择正确的工具并为它们提供正确的输入。
设置
本指南需要安装以下软件包
%pip install --upgrade --quiet langchain
如果您想在 LangSmith 中跟踪您的运行,请取消注释并设置以下环境变量
import getpass
import os
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
# os.environ["LANGCHAIN_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
print(multiply.name)
print(multiply.description)
print(multiply.args)
multiply
multiply(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
链
如果我们知道只需要使用一个工具固定次数,我们可以创建一个链来执行此操作。让我们创建一个简单的链,它只乘以用户指定的数字。
工具/函数调用
使用 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_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
我们将使用 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_cCP9oA3tRz7HDrjFn1FdmDaG'}]
请查看此处的 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 跟踪。
代理
当我们知道任何用户输入所需的特定工具使用顺序时,链非常有用。但是对于某些用例,我们使用工具的次数取决于输入。在这些情况下,我们希望让模型本身决定使用工具的次数和顺序。代理可以让我们做到这一点。
LangChain 附带许多内置代理,这些代理针对不同的用例进行了优化。阅读有关所有代理类型的信息,请点击此处。
我们将使用工具调用代理,它通常是最可靠的类型,也是大多数用例的推荐类型。
from langchain import hub
from langchain.agents import AgentExecutor, create_tool_calling_agent
# 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
代理也很棒,因为它们可以轻松地使用多个工具。
@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_tool_calling_agent(llm, tools, prompt)
# Create an agent executor by passing in the agent and tools
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
使用代理,我们可以提出需要任意多次使用工具的问题
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;3m
Invoking: `exponentiate` with `{'base': 3, 'exponent': 5}`
[0m[38;5;200m[1;3m243[0m[32;1m[1;3m
Invoking: `add` with `{'first_int': 12, 'second_int': 3}`
[0m[33;1m[1;3m15[0m[32;1m[1;3m
Invoking: `multiply` with `{'first_int': 243, 'second_int': 15}`
[0m[36;1m[1;3m3645[0m[32;1m[1;3m
Invoking: `exponentiate` with `{'base': 405, 'exponent': 2}`
[0m[38;5;200m[1;3m13286025[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 13286025.[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 13286025.'}
请查看此处的 LangSmith 跟踪。