Transformers 文档

代理,超级增强 - 多代理、外部工具等

代理,超级增强 - 多代理、外部工具等

什么是代理?

如果你是transformers.agents的新手,请确保首先阅读主要的agents文档

在本页面中,我们将重点介绍transformers.agents的几种高级用法。

多代理

多智能体已经在微软的框架Autogen中引入。 它简单意味着有多个智能体一起工作来解决你的任务,而不是只有一个。 在大多数基准测试中,它经验上产生了更好的性能。这种更好性能的原因在概念上很简单:对于许多任务,你更愿意在子任务上使用专门的单元,而不是使用一个全能的系统。在这里,拥有具有独立工具集和记忆的智能体可以实现高效的专业化。

你可以轻松地使用transformers.agents构建分层多代理系统。

为此,将代理封装在ManagedAgent对象中。该对象需要参数agentnamedescription,这些参数将被嵌入到管理代理的系统提示中,以便让它知道如何调用这个被管理的代理,就像我们对工具所做的那样。

这是一个使用我们的DuckDuckGoSearchTool来管理特定网页搜索代理的示例:

from transformers.agents import ReactCodeAgent, HfApiEngine, DuckDuckGoSearchTool, ManagedAgent

llm_engine = HfApiEngine()

web_agent = ReactCodeAgent(tools=[DuckDuckGoSearchTool()], llm_engine=llm_engine)

managed_web_agent = ManagedAgent(
    agent=web_agent,
    name="web_search",
    description="Runs web searches for you. Give it your query as an argument."
)

manager_agent = ReactCodeAgent(
    tools=[], llm_engine=llm_engine, managed_agents=[managed_web_agent]
)

manager_agent.run("Who is the CEO of Hugging Face?")

有关高效多代理实现的深入示例,请参阅我们如何将多代理系统推上GAIA排行榜的榜首

高级工具使用

通过子类化Tool直接定义一个工具,并将其分享到Hub

让我们再次以主文档中的工具示例为例,我们已经为其实现了一个tool装饰器。

如果你需要添加变化,比如为你的工具添加自定义属性,你可以按照细粒度的方法构建你的工具:构建一个继承自Tool超类的类。

自定义工具需要:

  • 一个属性 name,它对应于工具本身的名称。名称通常描述工具的功能。由于代码返回任务中下载次数最多的模型,我们将其命名为 model_download_counter
  • 属性 description 用于填充代理的系统提示。
  • 一个inputs属性,它是一个包含"type""description"键的字典。它包含帮助Python解释器对输入做出明智选择的信息。
  • 一个output_type属性,用于指定输出类型。
  • 一个包含要执行的推理代码的forward方法。

inputsoutput_type 的类型应该在 Pydantic 格式 中。

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 most downloaded model of a given task on the Hugging Face Hub.
    It returns the name of the checkpoint."""

    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

现在自定义的HfModelDownloadsTool类已经准备好了,你可以将其保存到名为model_downloads.py的文件中并导入使用。

from model_downloads import HFModelDownloadsTool

tool = HFModelDownloadsTool()

你也可以通过在工具上调用push_to_hub()来将你的自定义工具分享到Hub。确保你已经在Hub上为它创建了一个仓库,并且正在使用具有读取权限的令牌。

tool.push_to_hub("{your_username}/hf-model-downloads")

使用~Tool.load_tool函数加载工具,并将其传递给您代理中的tools参数。

from transformers import load_tool, CodeAgent

model_download_tool = load_tool("m-ric/hf-model-downloads")

导入空间作为工具 🚀

你可以使用Tool.from_space()方法直接从Hub导入一个Space作为工具!

您只需要提供Hub上Space的ID、名称以及一个描述,这将帮助您的代理理解该工具的功能。在底层,这将使用gradio-client库来调用Space。

例如,让我们从Hub导入FLUX.1-dev Space,并使用它生成图像。

from transformers import Tool

image_generation_tool = Tool.from_space(
    "black-forest-labs/FLUX.1-dev",
    name="image_generator",
    description="Generate an image from a prompt")

image_generation_tool("A sunny beach")

瞧,这是你的图片!🏖️

然后你可以像使用其他工具一样使用这个工具。例如,让我们改进提示a rabbit wearing a space suit并生成它的图像。

from transformers import ReactCodeAgent

agent = ReactCodeAgent(tools=[image_generation_tool])

agent.run(
    "Improve this prompt, then generate an image of it.", prompt='A rabbit wearing a space suit'
)
=== Agent thoughts:
improved_prompt could be "A bright blue space suit wearing rabbit, on the surface of the moon, under a bright orange sunset, with the Earth visible in the background"

Now that I have improved the prompt, I can use the image generator tool to generate an image based on this prompt.
>>> Agent is executing the code below:
image = image_generator(prompt="A bright blue space suit wearing rabbit, on the surface of the moon, under a bright orange sunset, with the Earth visible in the background")
final_answer(image)

这有多酷?🤩

使用 gradio-tools

gradio-tools 是一个强大的库,允许将 Hugging Face Spaces 用作工具。它支持许多现有的 Spaces 以及自定义的 Spaces。

Transformers 支持通过 Tool.from_gradio() 方法使用 gradio_tools。例如,我们可以使用来自 gradio-tools 工具包的 StableDiffusionPromptGeneratorTool 来改进提示以生成更好的图像。

导入并实例化工具,然后将其传递给 Tool.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)

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

使用 LangChain 工具

我们热爱Langchain,并认为它拥有一套非常引人注目的工具。 要从LangChain导入工具,请使用from_langchain()方法。

以下是您如何使用LangChain网络搜索工具重新创建介绍中的搜索结果的方法。 此工具需要pip install google-search-results才能正常工作。

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) are in BERT base encoder compared to the encoder from the architecture proposed in Attention is All You Need?")

在酷炫的Gradio界面中展示您的代理运行

你可以利用 gradio.Chatbot 来显示你的代理的思考过程,使用 stream_to_gradio,这里是一个示例:

import gradio as gr
from transformers import (
    load_tool,
    ReactCodeAgent,
    HfApiEngine,
    stream_to_gradio,
)

# Import tool from Hub
image_generation_tool = load_tool("m-ric/text-to-image")

llm_engine = HfApiEngine("meta-llama/Meta-Llama-3-70B-Instruct")

# Initialize the agent with the image generation tool
agent = ReactCodeAgent(tools=[image_generation_tool], llm_engine=llm_engine)


def interact_with_agent(task):
    messages = []
    messages.append(gr.ChatMessage(role="user", content=task))
    yield messages
    for msg in stream_to_gradio(agent, task):
        messages.append(msg)
        yield messages + [
            gr.ChatMessage(role="assistant", content="⏳ Task not finished yet!")
        ]
    yield messages


with gr.Blocks() as demo:
    text_input = gr.Textbox(lines=1, label="Chat Message", value="Make me a picture of the Statue of Liberty.")
    submit = gr.Button("Run illustrator agent!")
    chatbot = gr.Chatbot(
        label="Agent",
        type="messages",
        avatar_images=(
            None,
            "https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png",
        ),
    )
    submit.click(interact_with_agent, [text_input], [chatbot])

if __name__ == "__main__":
    demo.launch()
< > Update on GitHub