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

如果您想了解如何使用模型生成的工具调用来实际运行工具,请查看本指南。
工具调用并非普遍支持,但许多流行的 LLM 提供商都支持。您可以在此处找到所有支持工具调用的模型列表。
LangChain 为定义工具、将它们传递给 LLM 以及表示工具调用实现了标准接口。 本指南将介绍如何将工具绑定到 LLM,然后调用 LLM 来生成这些参数。
定义工具模式(Schema)
要使模型能够调用工具,我们需要传入描述工具功能及其参数的工具模式。支持工具调用功能的聊天模型会实现 .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 等效地定义模式而无需配套函数。
请注意,除非提供了默认值,否则所有字段都是必需的。
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")
泛型字典类
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]
为了将这些模式实际绑定到聊天模型,我们将使用 .bind_tools() 方法。此方法负责将 add 和 multiply 模式转换为适合模型的正确格式。然后,每 次调用模型时都会将工具模式传递给它。
pip install -qU "langchain[google-genai]"
import getpass
import os
if not os.environ.get("GOOGLE_API_KEY"):
os.environ["GOOGLE_API_KEY"] = getpass.getpass("Enter API key for Google Gemini: ")
from langchain.chat_models import init_chat_model
llm = init_chat_model("gemini-2.0-flash", model_provider="google_genai")
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() 的文档 https://python.langchain.com/api_reference/openai/chat_models/langchain_openai.chat_models.base.BaseChatOpenAI.html#langchain_openai.chat_models.base.BaseChatOpenAI.bind_tools 来了解自定义 LLM 如何选择工具的所有方式,以及 此指南,了解如何强制 LLM 调用工具 而不是让它自行决定。
工具调用
如果大语言模型响应中包含工具调用,它们将作为一系列 tool call 对象附加到相应的 message 或 message chunk 的 .tool_calls 属性中。
请注意,聊天模型可以一次调用多个工具。
ToolCall 是一个类型化字典,包含一个工具名称、一个参数值字典以及(可选)一个标识符。没有工具调用的消息默认将此属性设置为空列表。
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 参数)。在这些情况下,解析失败时,.invalid_tool_calls 属性中会填充 InvalidToolCall 的实例。InvalidToolCall 可以包含名称、字符串参数、标识符和错误消息。
解析
如果需要,输出解析器 可以进一步处理输出。例如,我们可以使用
PydanticToolsParser 将 .tool_calls 上已有的值转换为 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)]
后续步骤
现在您已经学会了如何将工具模式(tool schemas)绑定到聊天模型(chat model)并让模型调用工具。
接下来,请查看这篇关于通过调用函数并将结果传回模型来实际使用工具的指南:
您还可以查看一些更具体的工具调用用法: