在上一节中,我们学习了如何使用 Python 代码从零开始创建智能体,并且我们 看到了这个过程有多繁琐幸运的是,许多智能体库通过简化这项工作来实现这一点。 为您处理大部分繁琐工作.
在本教程中, 你将创建你的第一个智能体 能够执行诸如图像生成、网络搜索、时区查询等更多操作!
你还将发布你的智能体 在 Hugging Face Space 上,这样你就可以与朋友和同事分享它。.
让我们开始吧!
什么是 smolagents?
为了制作这个智能体,我们将使用 smolagents,一个库,该库 为轻松开发您的智能体提供了框架。.
这个轻量级库旨在简化操作,但它抽象出了构建智能体时的大部分复杂性,使您能够专注于设计智能体的行为。
在下一个单元中,我们将更深入地探讨 smolagents。同时,你也可以查看以下内容。 博客文章 或该库的 GitHub上的仓库.
简而言之, smolagents 是一个专注于 codeAgent一种执行任务的智能体 "操作" 通过代码块,然后 “观察” 通过执行代码获得结果。
这是我们将要构建的一个示例!
我们为我们的智能体提供了 图像生成工具 并让它生成一张猫的图片。
内部的智能体 smolagents 将会拥有 与之前我们构建的自定义智能体具有相同的行为: 正在进行中 循环思考、行动和观察 直到得到最终答案:
令人兴奋,对吧?
让我们构建我们的智能体吧!
首先,复制这个空间: https://huggingface.co/spaces/agents-course/First_agent_template
感谢 Aymeric 用于此模板!🙌
复制这个空间意味着 在自己的个人资料上创建本地副本:

在复制了 Space 之后,你需要添加你的 Hugging Face API 令牌,这样你的智能体就可以访问模型 API:
- 首先,获取你的 Hugging Face 令牌。 https://hf.co/settings/tokens 在获得权限进行推理的情况下,如果您还没有权限的话
- 前往你复制的Space,然后点击 设置 选项卡
- 向下滚动至 变量和秘密密钥 选择并点击 新秘密
- 创建一个名为...的秘密
HF_TOKEN并将你的令牌作为值粘贴 - 点击 保存 安全地存储您的令牌
在本课程中,您唯一需要修改的文件是(目前尚未完成的) "app.py"您可以在这里看到 模板中的原文要找到你的智能体,请进入你的空间副本,然后点击 Files 点击然后继续 app.py 在目录列表中。
让我们一起来分析这段代码:
- 文件以一些简单但必要的库导入开始。
from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
如前所述,我们将直接使用 CodeAgent 类从 smolagents.
工具
现在让我们来介绍这些工具吧!如果你想要回顾一下关于这些工具的知识,请随时返回到之前的介绍。 工具 课程的部分内容。
@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)}"
在本节中,我们鼓励您构建的便是这些工具!我们为您提供两个示例:
- A 非工作用智能体工具 你可以对其进行修改,以使其变得有用。
- An 实际运行的工具 这个智能体获取了世界某个地方当前的时间。
要定义你的工具,需要注意以下几点:
- 为你的函数提供输入和输出类型,例如:
get_current_time_in_timezone(timezone: str) -> str: - 格式良好的文档字符串.
smolagents期望所有参数都具有 文档字符串中的文本描述.
智能体
它使用 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()
这个智能体仍然使用 InferenceClient 我们在前面的章节中看到 推理客户端模型 类!
在介绍框架的单元2中,我们将给出更详细的例子。目前,你需要专注于 向工具列表中添加新工具 使用 tools 智能体的参数。
例如,你可以使用 DuckDuckGoSearchTool 这在代码的第一行被导入了,或者你可以进行检查。 image_generation_tool 该内容将在代码的后面部分从Hub中加载。
添加工具将使你的智能体拥有新的能力。在这里尝试发挥创意吧!
系统提示
智能体的系统提示存储在一个独立的文件中。 prompts.yaml 该文件包含预定义的指令,用于指导智能体的行为。
将提示存储在 YAML 文件中可以方便地进行定制,并能在不同的智能体或用例之间重复使用。
你可以检查 空间的文件结构 看看在哪里 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()
你的 目标 是为了熟悉空间和智能体。
目前,模板中的智能体 不使用任何工具,因此请尽量为它提供一些预先制作好的工具,甚至自己创建一些新的工具!
我们热切期待您在Discord频道中展示的出色智能体成果。 #智能体展示!
恭喜你,你已经构建了自己的第一个智能体!请毫不犹豫地与你的朋友和同事分享它。
由于这是你第一次尝试,所以出现一些漏洞或运行速度较慢是完全正常的。在后续的单元学习中,我们将学习如何构建更优秀的智能体。
学习的最佳方式是尝试,所以请不要犹豫,不断更新内容,添加更多工具,尝试使用其他模型等。
在下一节中,你将填写最后的测验并获得你的证书!