Transformers 文档

工具

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

Agents 和工具正在被分离到独立的 smolagents 库中。这些文档将在未来被弃用!

工具

工具是 Agent 可以用来完成任务的函数。根据您的任务,工具可以执行网络搜索、回答关于文档的问题、将语音转录为文本等等。

Transformers 为 Agent 提供了一组默认工具。这些工具包括上面提到的工具,以及图像问答、文本到语音、翻译和一个 Python 代码解释器,该解释器在安全环境中执行 LLM 生成的 Python 代码。

设置 add_base_tools=True 以启用这组默认工具。tools 参数用于添加额外的工具。如果您不打算向工具箱添加任何其他工具,请将列表留空。

from transformers import ReactCodeAgent

agent = ReactCodeAgent(tools=[], add_base_tools=True)

您也可以使用 load_tool() 手动加载工具。

from transformers import load_tool, ReactCodeAgent

tool = load_tool("text-to-speech")
audio = tool("This is a text-to-speech tool")
agent = ReactCodeAgent(tools=[audio])

本指南将帮助您学习如何创建自己的工具和管理 Agent 的工具箱。

创建新工具

您可以创建任何您能想到的工具来增强 Agent 的能力。本节中的示例创建了一个工具,该工具从 Hub 返回任务下载次数最多的模型,其代码如下所示。

from huggingface_hub import list_models

task = "text-classification"
model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
print(model.id)

您可以通过两种方式创建工具:使用装饰器或超类。

工具装饰器

创建工具的一种快速而简单的方法是添加 @tool 装饰器。

通过将其包装在一个函数中并添加 @tool 装饰器,将上面的代码转换为工具。该函数需要:

  • 一个清晰地描述工具用途的名称,model_download_counter
  • 输入和输出的类型提示 (str)。
  • 一个更详细地描述工具及其参数的描述。此描述包含在 Agent 的系统提示中。它告诉 Agent 如何 使用该工具,因此请尽量使其尽可能清晰!
from transformers import tool

@tool
def model_download_counter(task: str) -> str:
    """
    This is a tool that returns the checkpoint name of the most downloaded model for a task from the Hugging Face Hub.

    Args:
        task: The task to retrieve the most downloaded model from.
    """
    model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
    return model.id

model_download_counter 工具传递给 Agent 的 tools 参数以使用它。

from transformers import CodeAgent

agent = CodeAgent(tools=[model_download_counter], add_base_tools=True)
agent.run(
    "Can you give me the name of the model that has the most downloads on the 'text-to-video' task on the Hugging Face Hub?"
)

工具超类

继承允许您自定义 Tool 超类,或者更灵活、更全面地构建工具。此示例将向您展示如何构建与 Tool 类相同的 model_download_counter 工具。

Tool 类需要:

  • 一个清晰地描述工具用途的名称,model_download_counter
  • 一个更详细地描述工具及其参数的描述。此描述包含在 Agent 的系统提示中。它告诉 Agent 如何 使用该工具,因此请尽量使其尽可能清晰!
  • 一个 inputs 属性,用于描述输入类型。这是一个字典,包含键 typedescription
  • 一个 outputs 属性,用于描述输出类型。
  • 一个 forward 方法,其中包含在调用工具时要执行的代码。

将以下代码写入名为 model_download.py 的文件。

from transformers import Tool
from huggingface_hub import list_models

class HFModelDownloadsTool(Tool):
    name = "model_download_counter"
    description = """
    This is a tool that returns the checkpoint name of the most downloaded model for a task from the Hugging Face Hub."""

    inputs = {
        "task": {
            "type": "string",
            "description": "the task category (such as text-classification, depth-estimation, etc)",
        }
    }
    output_type = "string"

    def forward(self, task: str):
        model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
        return model.id

model_download.py 导入该工具,并使用 load_tool() 将其加载到 Agent 中。

from model_download import HFModelDownloadsTool
from transformers import load_tool, CodeAgent

tool = HFModelDownloadsTool()
model_counter = load_tool(tool)
agent = CodeAgent(tools=[model_counter], add_base_tools=True)

还可以考虑使用 push_to_hub() 将您的工具分享到 Hub,以便所有人都可以使用它!

from model_download import HFModelDownloadsTool
from transformers import load_tool, CodeAgent

tool = HFModelDownloadsTool()
tool.push_to_hub("{your_username}/hf-model-downloads")
model_counter = load_tool("m-ric/hf-model-downloads")
agent = CodeAgent(tools=[model_counter], add_base_tools=True)

添加和替换工具

Agent 初始化后,无需从头重新初始化 Agent 即可添加或替换其可用工具。

使用 add_tool 将工具添加到现有 Agent。

from transformers import CodeAgent

agent = CodeAgent(tools=[], add_base_tools=True)
agent.toolbox.add_tool(model_download_counter)

现在您可以使用默认的文本到语音工具来朗读文本到视频任务下载次数最多的模型。

agent.run(
    "Can you read out loud the name of the model that has the most downloads on the 'text-to-video' task on the Hugging Face Hub and return the audio?"
)

当向已经运行良好的 Agent 添加工具时,它可能会使 Agent 偏向于您的工具或当前定义的工具之外的其他工具。

使用 update_tool 替换 Agent 的现有工具。如果新工具是对现有工具的一对一替换,这将非常有用,因为 Agent 已经知道如何执行该任务。新工具应遵循与其替换的工具相同的 API,或者应调整系统提示模板以确保更新所有使用替换工具的示例。

agent.toolbox.update_tool(new_model_download_counter)

ToolCollection

ToolCollection 是 Hugging Face Spaces 的集合,可以由 Agent 快速加载和使用。

了解更多关于在 Hub 上创建集合的信息。

创建一个 ToolCollection 对象,并指定您要使用的集合的 collection_slug,然后将其传递给 Agent。为了加快启动过程,工具仅在被 Agent 调用时才加载。

该示例加载了一个图像生成工具集合。

from transformers import ToolCollection, ReactCodeAgent

image_tool_collection = ToolCollection(collection_slug="")
agent = ReactCodeAgent(tools=[*image_tool_collection], add_base_tools=True)
agent.run(
    "Please draw me a picture of rivers and lakes."
)

工具集成

Transformers 支持来自其他几个库的工具,例如 gradio-toolsLangChain

gradio-tools

gradio-tools 是一个库,它使 Gradio 应用程序能够用作工具。凭借 Gradio 应用程序的广泛种类,您可以使用一系列工具增强您的 Agent,例如生成图像和视频或转录音频并进行摘要。

从 gradio-tools 导入并实例化一个工具,例如 StableDiffusionPromptGeneratorTool。此工具可以帮助改进提示以生成更好的图像。

即使在使用图像和音频等不同模态时,gradio-tools 也需要文本输入和输出,这目前是不兼容的。

使用 from_gradio() 加载提示生成器工具。

from gradio_tools import StableDiffusionPromptGeneratorTool
from transformers import Tool, load_tool, CodeAgent

gradio_prompt_generator_tool = StableDiffusionPromptGeneratorTool()
prompt_generator_tool = Tool.from_gradio(gradio_prompt_generator_tool)

现在将其与文本到图像工具一起传递给 Agent。

image_generation_tool = load_tool("huggingface-tools/text-to-image")
agent = CodeAgent(tools=[prompt_generator_tool, image_generation_tool], llm_engine=llm_engine)
agent.run(
    "Improve this prompt, then generate an image of it.", prompt="A rabbit wearing a space suit"
)

LangChain

LangChain 是一个用于处理 LLM 的库,其中包括 Agent 和工具。使用 from_langchain() 方法将任何 LangChain 工具加载到 Agent 中。

下面的示例演示了如何使用 LangChain 的网络搜索工具。

from langchain.agents import load_tools
from transformers import Tool, ReactCodeAgent

search_tool = Tool.from_langchain(load_tools(["serpapi"])[0])
agent = ReactCodeAgent(tools=[search_tool])
agent.run("How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?")
< > 在 GitHub 上更新