智能体课程文档
使用 smolagents 创建我们的第一个 Agent
并获得增强的文档体验
开始使用
使用 smolagents 创建我们的第一个 Agent
在上一节中,我们学习了如何使用 Python 代码从头开始创建 Agent,我们看到了这个过程是多么繁琐。幸运的是,许多 Agent 库通过为您处理大量繁重的工作来简化了这项工作。
在本教程中,您将创建您的第一个 Agent,它能够执行图像生成、网页搜索、时区检查等操作!
您还将把您的 Agent 发布到 Hugging Face Space,这样您就可以与朋友和同事分享它。
让我们开始吧!
什么是 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 后,您需要添加您的 Hugging Face API 令牌,以便您的 Agent 可以访问模型 API。
- 首先,从 https://huggingface.co/settings/tokens 获取您的 Hugging Face 令牌,并授予推理权限(如果您还没有的话)。
- 进入您复制的 Space,然后点击设置 (Settings) 选项卡。
- 向下滚动到变量和秘密 (Variables and Secrets) 部分,然后点击新建秘密 (New Secret)。
- 创建一个名为
HF_TOKEN
的秘密,并将您的令牌粘贴为值。 - 点击保存 (Save) 以安全地存储您的令牌。
在整个课程中,您唯一需要修改的文件是(目前不完整的)“app.py”。您可以在模板中的原始文件中查看它。要找到您的文件,请转到您的 Space 副本,然后点击 Files
选项卡,再点击目录列表中的 app.py
。
让我们一起分解代码
- 文件开头是一些简单但必需的库导入。
from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, 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)}"
工具是我们在本节中鼓励您构建的!我们为您提供了两个示例:
- 一个不工作的虚拟工具,您可以修改它以使其有用。
- 一个实际工作的工具,可以获取世界某地的当前时间。
要定义您的工具,重要的是:
- 为您的函数提供输入和输出类型,例如在
get_current_time_in_timezone(timezone: str) -> str:
中。 - 格式良好的文档字符串。
smolagents
要求所有参数在文档字符串中具有文本描述。
Agent
它使用 Qwen/Qwen2.5-Coder-32B-Instruct
作为 LLM 引擎。这是一个功能强大的模型,我们将通过无服务器 API 访问它。
final_answer = FinalAnswerTool()
model = InferenceClientModel(
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 仍然使用我们在早期部分中通过 InferenceClientModel 类看到的 InferenceClient
!
我们将在单元 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, InferenceClientModel, 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 = InferenceClientModel(
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!不要犹豫,与您的朋友和同事分享它。
由于这是您的第一次尝试,如果它有点 Bug 或运行缓慢,这是完全正常的。在未来的单元中,我们将学习如何构建更好的 Agent。
学习的最佳方式是尝试,所以不要犹豫,更新它,添加更多工具,尝试不同的模型等。
在下一节中,您将完成最终测验并获得您的证书!
< > 在 GitHub 上更新