开源 AI 食谱文档

让多个 Agent 在多 Agent 层级结构中协作 🤖🤝🤖

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Open In Colab

让多个 Agent 在多 Agent 层级结构中协作 🤖🤝🤖

作者:Aymeric Roucher

本教程是高级教程。您应该首先了解此其他食谱中的概念!

在本笔记本中,我们将创建一个多 Agent Web 浏览器:一个 Agent 系统,其中多个 Agent 协作使用 Web 解决问题!

这将是一个简单的层级结构,使用 ManagedAgent 对象来包装托管的 Web 搜索 Agent

              +----------------+
              | Manager agent  |
              +----------------+
                       |
        _______________|______________
       |                              |
  Code interpreter   +--------------------------------+
       tool          |         Managed agent          |
                     |      +------------------+      |
                     |      | Web Search agent |      |
                     |      +------------------+      |
                     |         |            |         |
                     |  Web Search tool     |         |
                     |             Visit webpage tool |
                     +--------------------------------+

让我们设置这个系统。

运行下面这行代码来安装所需的依赖项

!pip install markdownify duckduckgo-search smolagents --upgrade -q

让我们登录以调用 HF Inference API

from huggingface_hub import notebook_login

notebook_login()

⚡️ 我们的 Agent 将由 Qwen/Qwen2.5-72B-Instruct 提供支持,使用 HfApiEngine 类,该类使用 HF 的 Inference API:Inference API 允许快速轻松地运行任何 OS 模型。

注意: Inference API 基于各种标准托管模型,部署的模型可能会在没有事先通知的情况下更新或替换。在此处了解更多信息here

model_id = "Qwen/Qwen2.5-72B-Instruct"

🔍 创建 Web 搜索工具

对于 Web 浏览,我们可以使用我们预先存在的 DuckDuckGoSearchTool 工具来提供与 Google 搜索等效的功能。

但是,我们也需要能够查看 DuckDuckGoSearchTool 找到的页面。为此,我们可以导入库的内置 VisitWebpageTool,但我们将重新构建它以了解它是如何完成的。

因此,让我们从头开始使用 markdownify 创建我们的 VisitWebpageTool 工具。

import re
import requests
from markdownify import markdownify as md
from requests.exceptions import RequestException
from smolagents import tool


@tool
def visit_webpage(url: str) -> str:
    """Visits a webpage at the given URL and returns its content as a markdown string.

    Args:
        url: The URL of the webpage to visit.

    Returns:
        The content of the webpage converted to Markdown, or an error message if the request fails.
    """
    try:
        # Send a GET request to the URL
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for bad status codes

        # Convert the HTML content to Markdown
        markdown_content = md(response.text).strip()

        # Remove multiple line breaks
        markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)

        return markdown_content

    except RequestException as e:
        return f"Error fetching the webpage: {str(e)}"
    except Exception as e:
        return f"An unexpected error occurred: {str(e)}"

好的,现在让我们初始化并测试我们的工具!

>>> print(visit_webpage("https://en.wikipedia.org/wiki/Hugging_Face")[:500])
Hugging Face - Wikipedia

[Jump to content](#bodyContent)

Main menu

Main menu
move to sidebar
hide

Navigation

* [Main page](/wiki/Main_Page "Visit the main page [z]")
* [Contents](/wiki/Wikipedia:Contents "Guides to browsing Wikipedia")
* [Current events](/wiki/Portal:Current_events "Articles related to current events")
* [Random article](/wiki/Special:Random "Visit a randomly selected article [x]")
* [About Wikipedia](/wiki/Wikipedia:About "Learn about Wikipedia and how it works")
* [Contac

构建我们的多 Agent 系统 🤖🤝🤖

现在我们有了所有工具 searchvisit_webpage,我们可以使用它们来创建 Web Agent。

为这个 Agent 选择哪个配置?

  • Web 浏览是一项单时间线任务,不需要并行工具调用,因此 JSON 工具调用非常适合。因此,我们选择 ReactJsonAgent
  • 此外,由于有时 Web 搜索需要浏览许多页面才能找到正确的答案,因此我们更倾向于将 max_iterations 的数量增加到 10。
from smolagents import CodeAgent, ToolCallingAgent, HfApiModel, ManagedAgent, DuckDuckGoSearchTool

model = HfApiModel(model_id)

web_agent = ToolCallingAgent(
    tools=[DuckDuckGoSearchTool(), visit_webpage],
    model=model,
    max_iterations=10,
)

然后,我们将此 Agent 包装到 ManagedAgent 中,使其可以被其管理器 Agent 调用。

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

最后,我们创建一个管理器 Agent,并在初始化时将我们的托管 Agent 传递给它的 managed_agents 参数。

由于此 Agent 的任务是规划和思考,因此高级推理将是有益的,因此 ReactCodeAgent 将是最佳选择。

此外,我们想问一个涉及当前年份的问题:因此,让我们添加 additional_authorized_imports=["time", "datetime"]

manager_agent = CodeAgent(
    tools=[],
    model=model,
    managed_agents=[managed_web_agent],
    additional_authorized_imports=["time", "datetime"],
)

就这样!现在让我们运行我们的系统!我们选择一个需要一些计算的问题,然后

manager_agent.run("How many years ago was Stripe founded?")

我们的 Agent 成功地协作以高效地解决任务!✅

💡 您可以轻松地将其扩展到更多 Agent:一个执行代码,一个进行 Web 搜索,一个处理文件加载......

🤔💭 甚至可以考虑进行更复杂的树状层级结构,一个 CEO Agent 管理多个中层经理,每个经理有几个下属。

我们甚至可以添加更多的中间管理层,每个管理层都有多次日常会议,大量的敏捷方法与 Scrum Master,并且每个新组件都会增加足够的摩擦,以确保任务永远无法完成......嗯,等等,不,让我们坚持我们简单的结构。

< > 在 GitHub 上更新