LangChain组件Tools/Toolkits详解(5)——返回产出artifact
LangChain组件Tools/Toolkits详解(5)——返回产出artifact
- 本篇摘要
- 14. LangChain组件Tools/Toolkits详解
-
- 14.5 返回产出artifact
-
- 14.5.1 定义工具
- 14.5.2 使用ToolCall调用工具
- 14.5.3 与模型一起使用
- 14.5.4 从子例化BaseTool返回
- 参考文献
本章目录如下:
- 《LangChain组件Tools/Toolkits详解(1)——Tools接口与创建工具概述》
- 《LangChain组件Tools/Toolkits详解(2)——装饰器@tool》
- 《LangChain组件Tools/Toolkits详解(3)——结构化工具StructuredTool》
- 《LangChain组件Tools/Toolkits详解(4)——处理Error》
- 《LangChain组件Tools/Toolkits详解(5)——返回产出artifact》
- 《LangChain组件Tools/Toolkits详解(6)——特殊类型注解》
- 《LangChain组件Tools/Toolkits详解(7)——工具调用与Toolkits》
本篇摘要
本章介绍LangChain组件Tools/Toolkits。
14. LangChain组件Tools/Toolkits详解
工具(Tools)是一种封装函数及其模式schema的方法,可以传递给聊天模型,使模型能够请求执行带有特定输入的工具函数,例如从数据库获取数据、发出API请求或运行自定义代码。LangChain中的tool抽象类将Python函数与定义函数名称、描述和预期参数的模式schema关联起来,以明确创建工具的作用及调用方式。本节将从Tools接口与创建工具概述、装饰器@tool、结构化工具StructuredTool、处理Error、返回产出artifact、特殊类型注解、工具调用和Toolkits等方面详细介绍工具。
14.5 返回产出artifact
工具是模型可以调用的实用程序,其输出被设计为反馈给模型。然而,有时我们希望将工具执行的一些产出(artifacts)提供给链或代理中的下游组件,但不希望将这些结果暴露给模型本身。例如,如果工具返回一个自定义对象(如文档)、数据帧或图像,我们可能希望将有关此输出的一些元数据metadata传递给模型,而不是将原始输出传递给模型;同时我们可能希望在其他地方访问完整的输出,例如在下游工具中。
Tool和ToolMessage接口使我们可以区分工具输出中用于模型的部分(即 ToolMessage.content)和用于模型外部的部分(ToolMessage.artifact)。
此功能在langchain-core == 0.2.19中添加,因此请确保langchain-core >= 0.2.19。
14.5.1 定义工具
如果我们希望工具能够区分消息内容和其他产出,需要在定义工具时指定 response_format=“content_and_artifact”,并确保返回一个 (content, artifact) 元组。示例如下:
# !pip install -qU "langchain-core>=0.2.19"
import random
from typing import List, Tuple
from langchain_core.tools import tool
@tool(response_format="content_and_artifact")
def generate_random_ints(min: int, max: int, size: int) -> Tuple[str, List[int]]:
"""Generate size random ints in the range [min, max]."""
array = [random.randint(min, max) for _ in range(size)]
content = f"Successfully generated array of {
size} random ints in [{
min}