Agents 课程文档

让我们使用 smolagents 创建我们的第一个 Agent

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

让我们使用 smolagents 创建我们的第一个 Agent

在上一节中,我们学习了如何使用 Python 代码从头开始创建 Agent,并且我们看到了这个过程是多么繁琐。 幸运的是,许多 Agent 库通过为您处理大部分繁重的工作来简化这项工作。

在本教程中,您将创建您的第一个 Agent,它能够执行图像生成、网络搜索、时区检查等操作!

您还将把您的 Agent 发布在 Hugging Face Space 上,以便您可以与朋友和同事分享

让我们开始吧!

什么是 smolagents?

smolagents

为了创建这个 Agent,我们将使用 smolagents,这是一个提供框架以便轻松开发您的 Agent 的库。

这个轻量级库旨在简化操作,但它抽象出了构建 Agent 的大部分复杂性,让您专注于设计 Agent 的行为。

我们将在下一个单元中更深入地了解 smolagents。同时,您也可以查看这篇博客文章或该库在 GitHub 上的仓库

简而言之,smolagents 是一个专注于 codeAgent 的库,这是一种通过代码块执行 “行动”,然后通过执行代码 “观察” 结果的 Agent。

这是一个我们将构建的示例!

我们为 Agent 提供了图像生成工具,并要求它生成一张猫的图像。

smolagents 内部的 Agent 将具有与我们之前构建的自定义 Agent 相同的行为:它将进行思考、行动和观察循环,直到得出最终答案

令人兴奋,对吧?

让我们构建我们的 Agent!

首先,复制这个 Space:https://huggingface.co/spaces/agents-course/First_agent_template

感谢 Aymeric 提供的这个模板! 🙌

复制这个 Space 意味着在您自己的个人资料上创建一个本地副本

Duplicate

复制 Space 后,您需要添加您的 Hugging Face API 令牌,以便您的 Agent 可以访问模型 API

  1. 首先,从 https://huggingface.co/settings/tokens 获取您的 Hugging Face 令牌,并授予推理权限(如果您还没有令牌)
  2. 转到您复制的 Space,然后单击Settings(设置)选项卡
  3. 向下滚动到 Variables and Secrets(变量和密钥)部分,然后单击 New Secret(新建密钥)
  4. 创建一个名为 HF_TOKEN 的密钥,并将您的令牌粘贴为值
  5. 单击 Save(保存)以安全地存储您的令牌

在本课程中,您唯一需要修改的文件是(当前不完整的)“app.py”。您可以在 模板中的原始文件 中查看。要找到您的文件,请转到您的 Space 副本,然后单击 Files(文件)选项卡,然后在目录列表中单击 app.py

让我们一起分解代码

  • 该文件以一些简单但必要的库导入开始
from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml

如前所述,我们将直接使用 smolagents 中的 CodeAgent 类。

工具

现在让我们深入了解工具!如果您想复习工具的相关知识,请随时回到课程的 工具 部分。

@tool
def my_custom_tool(arg1:str, arg2:int)-> str: # it's important to specify the return type
    # Keep this format for the tool description / args description but feel free to modify the tool
    """A tool that does nothing yet 
    Args:
        arg1: the first argument
        arg2: the second argument
    """
    return "What magic will you build ?"

@tool
def get_current_time_in_timezone(timezone: str) -> str:
    """A tool that fetches the current local time in a specified timezone.
    Args:
        timezone: A string representing a valid timezone (e.g., 'America/New_York').
    """
    try:
        # Create timezone object
        tz = pytz.timezone(timezone)
        # Get current time in that timezone
        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
        return f"The current local time in {timezone} is: {local_time}"
    except Exception as e:
        return f"Error fetching time for timezone '{timezone}': {str(e)}"

工具是我们在本节中鼓励您构建的内容!我们为您提供两个示例

  1. 一个无法工作的虚拟工具,您可以修改它以使其变得有用。
  2. 一个实际可行的工具,它可以获取世界上某个地方的当前时间。

要定义您的工具,重要的是

  1. 为您的函数提供输入和输出类型,例如 get_current_time_in_timezone(timezone: str) -> str:
  2. 格式良好的文档字符串smolagents 期望所有参数在文档字符串中都有文本描述

Agent

它使用 Qwen/Qwen2.5-Coder-32B-Instruct 作为 LLM 引擎。这是一个非常强大的模型,我们将通过无服务器 API 访问它。

final_answer = FinalAnswerTool()
model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
    custom_role_conversions=None,
)

with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)
    
# We're creating our CodeAgent
agent = CodeAgent(
    model=model,
    tools=[final_answer], # add your tools here (don't remove final_answer)
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=prompt_templates
)

GradioUI(agent).launch()

这个 Agent 仍然使用我们在前面部分看到的 InferenceClient,它在 HfApiModel 类后面!

当我们在单元 2 中介绍框架时,我们将提供更深入的示例。现在,您需要专注于使用 Agent 的 tools 参数向工具列表添加新工具

例如,您可以使用代码第一行导入的 DuckDuckGoSearchTool,或者您可以检查稍后在代码中从 Hub 加载的 image_generation_tool

添加工具将赋予您的 Agent 新的功能,尝试在此处发挥创造力!

系统提示

Agent 的系统提示存储在一个单独的 prompts.yaml 文件中。此文件包含预定义的指令,用于指导 Agent 的行为。

将提示存储在 YAML 文件中可以轻松自定义并在不同的 Agent 或用例中重复使用。

您可以查看 Space 的文件结构,了解 prompts.yaml 文件的位置以及它在项目中的组织方式。

完整的“app.py”

from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool

from Gradio_UI import GradioUI

# Below is an example of a tool that does nothing. Amaze us with your creativity!
@tool
def my_custom_tool(arg1:str, arg2:int)-> str: # it's important to specify the return type
    # Keep this format for the tool description / args description but feel free to modify the tool
    """A tool that does nothing yet 
    Args:
        arg1: the first argument
        arg2: the second argument
    """
    return "What magic will you build ?"

@tool
def get_current_time_in_timezone(timezone: str) -> str:
    """A tool that fetches the current local time in a specified timezone.
    Args:
        timezone: A string representing a valid timezone (e.g., 'America/New_York').
    """
    try:
        # Create timezone object
        tz = pytz.timezone(timezone)
        # Get current time in that timezone
        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
        return f"The current local time in {timezone} is: {local_time}"
    except Exception as e:
        return f"Error fetching time for timezone '{timezone}': {str(e)}"


final_answer = FinalAnswerTool()
    model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
    custom_role_conversions=None,
)


# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)

# Load system prompt from prompt.yaml file
with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)
    
agent = CodeAgent(
    model=model,
    tools=[final_answer], # add your tools here (don't remove final_answer)
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=prompt_templates # Pass system prompt to CodeAgent
)


GradioUI(agent).launch()

您的 目标 是熟悉 Space 和 Agent。

目前,模板中的 Agent 不使用任何工具,因此请尝试为其提供一些预制工具,甚至自己制作一些新工具!

我们热切期待在 discord 频道 #agents-course-showcase 中看到您令人惊叹的 Agent 输出!


恭喜,您已经构建了您的第一个 Agent!不要犹豫与您的朋友和同事分享。

由于这是您的第一次尝试,所以如果它有点错误或速度较慢,这是完全正常的。在未来的单元中,我们将学习如何构建更好的 Agent。

最好的学习方法是尝试,所以不要犹豫更新它,添加更多工具,尝试使用其他模型等等。

在下一节中,您将填写最终测验并获得您的证书!

< > 在 GitHub 上更新