開源 AI 食譜文件

讓多個智慧體在多智慧體層級結構中協作 🤖🤝🤖

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Open In Colab

讓多個智慧體在多智慧體層級結構中協作 🤖🤝🤖

作者:Aymeric Roucher

本教程是高階教程。您應首先了解此菜譜中的概念!

在此筆記本中,我們將建立一個多智慧體網頁瀏覽器:一個包含多個智慧體的智慧體系統,它們協作使用網頁解決問題!

這將是一個簡單的層級結構,使用 ManagedAgent 物件來封裝託管的網頁搜尋智慧體。

              +----------------+
              | 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 推理 API

from huggingface_hub import notebook_login

notebook_login()

⚡️ 我們的智慧體將由Qwen/Qwen2.5-72B-Instruct 提供支援,使用 HfApiEngine 類,該類使用 HF 的推理 API:推理 API 允許快速輕鬆地執行任何 OS 模型。

注意: 推理 API 根據各種標準託管模型,部署的模型可能會在沒有事先通知的情況下更新或替換。在此處瞭解更多資訊

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

🔍 建立網頁搜尋工具

對於網頁瀏覽,我們已經可以使用預先存在的 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

構建我們的多智慧體系統 🤖🤝🤖

現在我們有了所有工具 searchvisit_webpage,我們可以使用它們來建立網頁智慧體。

該智慧體應選擇哪種配置?

  • 網頁瀏覽是一個不需要並行工具呼叫的單時間線任務,因此 JSON 工具呼叫非常適合。因此,我們選擇 ReactJsonAgent
  • 此外,由於有時網頁搜尋需要探索許多頁面才能找到正確的答案,我們傾向於將 max_iterations 增加到 10。
from smolagents import CodeAgent, ToolCallingAgent, InferenceClientModel, ManagedAgent, DuckDuckGoSearchTool

model = InferenceClientModel(model_id)

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

然後,我們將此智慧體封裝到 ManagedAgent 中,使其可以被其管理器智慧體呼叫。

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

最後,我們建立一個管理器智慧體,並在初始化時將其管理的智慧體傳遞給其 managed_agents 引數。

由於該智慧體負責規劃和思考,高階推理將非常有益,因此 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?")

我們的智慧體成功高效地協作完成了任務!✅

💡 您可以輕鬆地將其擴充套件到更多智慧體:一個執行程式碼,一個執行網頁搜尋,一個處理檔案載入……

🤔💭 甚至可以考慮更復雜的樹狀層級結構,一個 CEO 智慧體管理多箇中層經理,每個經理都有多個下屬。

我們甚至可以新增更多的中間管理層,每個層級都有多次日常會議,大量的敏捷開發(Scrum 主管),每個新元件都會增加足夠的摩擦,確保任務永遠無法完成……嗯,等等,不,讓我們堅持我們簡單的結構。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.