如何使用聊天模型调用工具
工具调用允许聊天模型通过“调用工具”来响应给定的提示。
请记住,虽然名称“工具调用”意味着模型正在直接执行某些作,但实际上并非如此!该模型仅生成工具的参数,实际运行(或不运行)取决于用户。
工具调用是一种从模型生成结构化输出的通用技术,即使您不打算调用任何工具,也可以使用它。一个示例用例是从非结构化文本中提取。

如果您想了解如何使用模型生成的工具调用来实际运行工具,请查看本指南。
工具调用不是通用的,但许多流行的 LLM 提供程序都支持它。您可以在此处找到支持工具调用的所有型号的列表。
LangChain 实现了用于定义工具、将其传递给 LLM 和表示工具调用的标准接口。 本指南将介绍如何将工具绑定到 LLM,然后调用 LLM 来生成这些参数。
定义工具方案
为了使模型能够调用工具,我们需要传入描述工具功能及其参数的工具架构。支持工具调用功能的聊天模型实现了.bind_tools()将工具架构传递给模型的方法。工具架构可以作为 Python 函数(带有类型提示和文档字符串)、Pydantic 模型、TypedDict 类或 LangChain Tool 对象传入。模型的后续调用将与提示符一起传入这些工具方案。
Python 函数
我们的工具架构可以是 Python 函数:
# The function name, type hints, and docstring are all part of the tool
# schema that's passed to the model. Defining good, descriptive schemas
# is an extension of prompt engineering and is an important part of
# getting models to perform well.
def add(a: int, b: int) -> int:
"""Add two integers.
Args:
a: First integer
b: Second integer
"""
return a + b
def multiply(a: int, b: int) -> int:
"""Multiply two integers.
Args:
a: First integer
b: Second integer
"""
return a * b
LangChain 工具
LangChain 还实现了一个@tool修饰器,允许进一步控制工具架构,例如工具名称和参数描述。有关详细信息,请参阅此处的操作指南。
Pydantic 类
您可以使用 Pydantic 等效地定义架构,而无需附带的函数。
请注意,所有字段都是required除非提供默认值。
from pydantic import BaseModel, Field
class add(BaseModel):
"""Add two integers."""
a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")
class multiply(BaseModel):
"""Multiply two integers."""
a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")
TypedDict 类
langchain-core>=0.2.25或者使用 TypedDicts 和注解:
from typing_extensions import Annotated, TypedDict
class add(TypedDict):
"""Add two integers."""
# Annotations must have the type and can optionally include a default value and description (in that order).
a: Annotated[int, ..., "First integer"]
b: Annotated[int, ..., "Second integer"]
class multiply(TypedDict):
"""Multiply two integers."""
a: Annotated[int, ..., "First integer"]
b: Annotated[int, ..., "Second integer"]
tools = [add, multiply]
要实际将这些 schema 绑定到聊天模型,我们将使用.bind_tools()方法。这将处理转换
这add和multiplyschemas 设置为模型的正确格式。然后,每次调用模型时,都会传入工具方案。
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")
llm_with_tools = llm.bind_tools(tools)
query = "What is 3 * 12?"
llm_with_tools.invoke(query)
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_iXj4DiW1p7WLjTAQMRO0jxMs', 'function': {'arguments': '{"a":3,"b":12}', 'name': 'multiply'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 80, 'total_tokens': 97}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_483d39d857', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-0b620986-3f62-4df7-9ba3-4595089f9ad4-0', tool_calls=[{'name': 'multiply', 'args': {'a': 3, 'b': 12}, 'id': 'call_iXj4DiW1p7WLjTAQMRO0jxMs', 'type': 'tool_call'}], usage_metadata={'input_tokens': 80, 'output_tokens': 17, 'total_tokens': 97})
正如我们所看到的,我们的 LLM 生成的工具参数!您可以查看 bind_tools() 的文档,了解自定义 LLM 选择工具的所有方法,以及有关如何强制 LLM 调用工具而不是让它决定的指南。
工具调用
如果 LLM 响应中包含工具调用,则它们将作为 .tool_calls属性。
请注意,聊天模型可以一次调用多个工具。
一个ToolCall是一个类型化的 dict,其中包含
工具名称、参数值字典和(可选)标识符。没有
tool 调用默认为此属性的空列表。
query = "What is 3 * 12? Also, what is 11 + 49?"
llm_with_tools.invoke(query).tool_calls
[{'name': 'multiply',
'args': {'a': 3, 'b': 12},
'id': 'call_1fyhJAbJHuKQe6n0PacubGsL',
'type': 'tool_call'},
{'name': 'add',
'args': {'a': 11, 'b': 49},
'id': 'call_fc2jVkKzwuPWyU7kS9qn1hyG',
'type': 'tool_call'}]
这.tool_calls属性应包含有效的工具调用。请注意,有时,
模型提供程序可能会输出格式错误的工具调用(例如,不是
有效的 JSON)。在这些情况下解析失败时,实例
的 InvalidToolCall 填充到.invalid_tool_calls属性。一InvalidToolCall可以有
名称、字符串参数、标识符和错误消息。
解析
如果需要,输出解析器可以进一步处理输出。例如,我们可以转换在.tool_calls使用 PydanticToolsParser 到 Pydantic 对象:
from langchain_core.output_parsers import PydanticToolsParser
from pydantic import BaseModel, Field
class add(BaseModel):
"""Add two integers."""
a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")
class multiply(BaseModel):
"""Multiply two integers."""
a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")
chain = llm_with_tools | PydanticToolsParser(tools=[add, multiply])
chain.invoke(query)
[multiply(a=3, b=12), add(a=11, b=49)]
后续步骤
现在,您已经学习了如何将工具架构绑定到聊天模型并让模型调用该工具。
接下来,查看本指南,了解如何通过调用函数并将结果传回模型来实际使用该工具:
您还可以查看工具调用的一些更具体的用途: