smolagents 文件

編排一個多智慧體系統 🤖🤝🤖

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

編排一個多智慧體系統 🤖🤝🤖

在這個 Notebook 中,我們將構建一個多智慧體網路瀏覽器:一個由多個智慧體協作解決網路問題的智慧體系統!

它將是一個簡單的層次結構

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

讓我們來設定這個系統。

執行下面這行命令來安裝所需的依賴項

!pip install smolagents[toolkit] --upgrade -q

讓我們登入到 HF,以便呼叫推理提供商

from huggingface_hub import login

login()

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

推理提供商允許訪問數百個模型,由無伺服器推理合作伙伴提供支援。支援的提供商列表可以在 此處 找到。

model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"

🔍 建立一個網頁搜尋工具

對於網頁瀏覽,我們已經可以使用我們的原生 WebSearchTool 工具來提供等同於 Google 搜尋的功能。

但之後我們還需要能夠檢視 WebSearchTool 找到的頁面。為此,我們可以匯入庫的內建 VisitWebpageTool,但我們將重新構建它以瞭解其工作原理。

因此,讓我們使用 markdownify 從頭開始建立我們的 VisitWebpageTool 工具。

import re
import requests
from markdownify import markdownify
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 = markdownify(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])

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

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

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

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

model = InferenceClientModel(model_id=model_id)

web_agent = ToolCallingAgent(
    tools=[WebSearchTool(), visit_webpage],
    model=model,
    max_steps=10,
    name="web_search_agent",
    description="Runs web searches for you.",
)

請注意,我們為這個智慧體提供了 namedescription 屬性,這些是使其可被其管理器智慧體呼叫的強制屬性。

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

由於這個智慧體負責規劃和思考,高階推理將很有益處,因此 CodeAgent 將會很好地工作。

此外,我們想提出一個涉及當前年份並進行額外資料計算的問題:所以讓我們新增 additional_authorized_imports=["time", "numpy", "pandas"],以防智慧體需要這些包。

manager_agent = CodeAgent(
    tools=[],
    model=model,
    managed_agents=[web_agent],
    additional_authorized_imports=["time", "numpy", "pandas"],
)

就是這樣!現在讓我們執行我們的系統!我們選擇一個既需要計算又需要研究的問題

answer = manager_agent.run("If LLM training continues to scale up at the current rhythm until 2030, what would be the electric power in GW required to power the biggest training runs by 2030? What would that correspond to, compared to some countries? Please provide a source for any numbers used.")

我們得到這個報告作為答案

Based on current growth projections and energy consumption estimates, if LLM trainings continue to scale up at the 
current rhythm until 2030:

1. The electric power required to power the biggest training runs by 2030 would be approximately 303.74 GW, which 
translates to about 2,660,762 GWh/year.

2. Comparing this to countries' electricity consumption:
   - It would be equivalent to about 34% of China's total electricity consumption.
   - It would exceed the total electricity consumption of India (184%), Russia (267%), and Japan (291%).
   - It would be nearly 9 times the electricity consumption of countries like Italy or Mexico.

3. Source of numbers:
   - The initial estimate of 5 GW for future LLM training comes from AWS CEO Matt Garman.
   - The growth projection used a CAGR of 79.80% from market research by Springs.
   - Country electricity consumption data is from the U.S. Energy Information Administration, primarily for the year 
2021.

如果 擴充套件假說 繼續成立,看來我們需要一些相當大的發電廠。

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

💡 您可以輕鬆地將這種編排擴充套件到更多的智慧體:一個負責程式碼執行,一個負責網路搜尋,一個處理檔案載入……

< > 在 GitHub 上更新

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