Langchain指南-关键特性:使用聊天模型调用工具
为了使模型能够调用工具,我们需要传递描述工具功能及其参数的工具模式。支持工具调用功能的聊天模型实现了一个.bind_tools()方法,用于将工具模式传递给模型。工具模式可以作为 Python 函数(带有类型提示和文档字符串)、Pydantic 模型、TypedDict 类或 LangChain 工具对象传递。后续对模型的调用将传递这些工具模式以及提示。
如何使用聊天模型调用工具
title: 先决条件
本指南假定您熟悉以下概念:
- 聊天模型
- 工具调用
- 工具
- 输出解析器
工具调用允许聊天模型通过“调用工具”来响应给定的提示。
记住,虽然“工具调用”这个名字暗示模型正在直接执行某些操作,但实际上并非如此!模型只生成工具的参数,而是否运行工具(或是否不运行)取决于用户。
工具调用是一种从模型生成结构化输出的通用技术,即使你不想调用任何工具,你也可以使用它。一个例子用例是从非结构化文本中提取。
如果您想了解如何使用模型生成的工具调用实际运行工具,请查看此指南。。
工具调用并非通用,但许多流行的 LLM 提供商支持。您可以在此处找到所有支持工具调用的模型列表。
LangChain 实现了定义工具、将它们传递给LLMs以及表示工具调用的标准接口。本指南将介绍如何将工具绑定到LLM,然后调用LLM来生成这些参数。
定义工具模式
为了使模型能够调用工具,我们需要传递描述工具功能及其参数的工具模式。支持工具调用功能的聊天模型实现了一个.bind_tools()方法,用于将工具模式传递给模型。工具模式可以作为 Python 函数(带有类型提示和文档字符串)、Pydantic 模型、TypedDict 类或 LangChain 工具对象传递。后续对模型的调用将传递这些工具模式以及提示。
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:
"""计算两个数字之和
Args:
a: 第一个数字
b: 第二个数字
"""
return a + b
def multiply(a: int, b: int) -> int:
"""计算两个数字之乘积.
Args:
a: 第一个数字
b: 第二个数字
"""
return a * b
LangChain 工具
LangChain 还实现了一个@tool
装饰器,允许进一步控制工具模式,例如工具名称和参数描述。请参阅此处的如何指南以获取详细信息。
Pydantic 类
您可以使用Pydantic等价地定义没有伴随函数的模式。
请注意,除非提供默认值,否则所有字段都是必需的。
from pydantic import BaseModel,Field
class sub(BaseModel):
"""计算两个数的差"""
a: int = Field(..., description="第一个数字")
b: int = Field(..., description="第二个数字")
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_dict(TypedDict):
"""计算两个数字的和"""
a: Annotated[int, ...,Field(description="第一个数字")]
b : Annotated[int ,...,Field(description="第二个数字")]
class multiply_dict(TypedDict):
"""计算两个数字的积"""
a: Annotated[int, ...,Field(description="第一个数字")]
b : Annotated[int ,...,Field(description="第二个数字")]
要将这些模式绑定到聊天模型,我们将使用 .bind_tools()
方法。这处理将 add 和 multiply 模式转换为模型正确的格式。每次调用模型时,工具模式都会传递给它。
from pykg import openai_scill_chat_model as model
tools = [add, multiply]
llm_with_tools = model.bind_tools(tools)
query = "What is 3 * 12?"
llm_with_tools.invoke(query)
additional_kwargs={'tool_calls': [{'id': '0198ff85db627fbc21f171e9c2d1d458', 'function': {'arguments': ' {"a": 3, "b": 12}', 'name': 'multiply'}, 'type': 'function', 'index': 0}], 'refusal': None}
正如我们所见,我们的LLM生成了工具的参数!您可以查看bind_tools()的文档,了解所有自定义LLM选择工具的方法,以及如何强制LLM调用工具而不是让它决定的指南。
工具调用
如果工具调用包含在LLM响应中,它们将附加到相应的 消息 或 消息块 作为一个工具调用的列表 对象在 .tool_calls
属性中。
请注意,聊天模型可以同时调用多个工具。
一个 ToolCall 是一个包含工具名称、参数值字典以及(可选的)标识符的键值对字典。
没有工具调用的消息默认为此属性为空列表。
query = "What is 3 * 12? Also, what is 11 + 49?"
llm_with_tools.invoke(query).
"""
[{'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 可以有一个名称、字符串参数、标识符和错误消息。
解析
如果需要,输出解析器可以进一步处理输出。例如,我们可以将已填充在.tool_calls上的现有值转换为 Pydantic 对象。
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)
现在你已经学会了如何将工具模式绑定到聊天模型,并且让模型调用工具。
接下来,查看这篇关于实际使用工具的指南,通过调用函数并将结果传回模型:
传递工具结果回模型
更多推荐
所有评论(0)