跳转到内容
Hugging Face 智能体课程
1. 课程运作方式及问答环节
单元2. 智能体框架

构建使用代码的智能体

Google Colab

Discord

代码智能体是默认的智能体类型。 smolagents它们生成Python工具调用来执行操作,从而实现高效、富有表现力且准确的操作表示。

他们的精简方法减少了所需操作的数量,简化了复杂操作,并使得现有代码函数的重用成为可能。 smolagents 提供了一个用于构建代码智能体的轻量级框架,代码量约为1,000行。

代码与JSON操作 论文中的图表 可执行代码操作能培育出更优秀的大型语言模型智能体

[!TIP] 如果您想了解更多关于为什么代码智能体如此有效,请查看 本指南 从 smolagents 文档中。

为什么选择智能体?

在多步智能体过程中,大语言模型编写并执行动作,通常涉及外部工具调用。传统方法使用 JSON 格式来指定工具名称和字符串形式的参数。 系统必须解析这些信息以确定要执行哪个工具。.

然而,研究表明 工具调用的大型语言模型能够更高效地处理代码。这是一项核心原则。 smolagents,如上面图表所示 可执行代码操作能培育出更优秀的大型语言模型智能体.

用代码而不是 JSON 编写动作具有几个关键优势:

  • 可组合性:能够轻松组合和复用动作。
  • 对象管理: 直接处理像图像这样的复杂结构
  • 通用性: 表达任何计算上可行的任务
  • 对 LLM 来说很自然: 智能体在 LLM 训练数据中已经存在高质量的代码

智能体如何工作?

来自 https://huggingface.co/docs/smolagents/conceptual_guides/react

上面的图表展示了如何 CodeAgent.run() 按照我们在第1单元中提到的ReAct框架进行运作。智能体的主要抽象化之处在于 smolagents 是 MultiStepAgent,作为核心构建模块。 CodeAgent 是一种特殊的 MultiStepAgent正如我们在下面的例子中看到的那样。

A CodeAgent 通过一系列步骤来执行动作,现有的变量和知识被纳入智能体的上下文中,该上下文保存在执行日志中:

  1. 系统提示信息存储在一个地方。 SystemPromptStep,并且用户查询被记录下来了 TaskStep.

  2. 然后,执行以下循环:

    2.1 方法 agent.write_memory_to_messages() 将智能体的日志写入一个LLM可读取的列表中 聊天消息.

    2.2 这些消息被发送到智能体。 Model,它生成一个完成词。

    2.3 完成后的内容被解析以提取操作,就我们的情况而言,这应该是一个代码片段,因为我们正在处理一个 CodeAgent.

    2.4 该动作已执行。

    2.5 结果被记录到内存中。 ActionStep.

在每个步骤的末尾,如果智能体包含任何函数调用(在 agent.step_callback), 它们被执行了。

来看一些例子

[!TIP] 您可以按照代码进行操作。 这个笔记本 您可以使用 Google Colab来运行它。

阿尔弗雷德正在韦恩家族的宅邸举办一场派对,他需要你的帮助来确保一切顺利进行。为了协助他,我们将运用我们所学的关于多步骤的方法。 CodeAgent 运行。

Alfred Party

如果您尚未安装 smolagents 不过,您可以通过运行以下命令来实现这一点:

pip install smolagents -U

我们还可以登录 Hugging Face Hub,以访问 Serverless Inference API。

from huggingface_hub import login

login()

为派对选择播放列表 smolagents

音乐是成功举办派对的重要组成部分!阿尔弗雷德需要一些帮助来挑选播放列表。幸运的是, smolagents 智能体已经为我们做好了准备!我们可以构建一个能够使用 DuckDuckGo 搜索网络的智能体。为了让智能体能够使用这个工具,我们在创建智能体时将其添加到工具列表中。

Alfred 播放列表

对于模型,我们将依赖 InferenceClientModel,提供对 Hugging Face 的访问 无服务器推理API. 默认模型是 "Qwen/Qwen2.5-Coder-32B-Instruct"该智能体性能优越,适用于快速推理,但您可以从中心库中选择任何兼容的模型。

运行智能体非常简单:

from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel

agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=InferenceClientModel())

agent.run("Search for the best music recommendations for a party at the Wayne's mansion.")

当你运行这个示例时,输出结果将是 显示正在执行的工作流程步骤的追踪它还会打印出相应的 Python 代码,并附带消息:

 ─ Executing parsed code: ──────────────────────────────────────────────────────────────────────────────────────── 
  results = web_search(query="best music for a Batman party")                                                      
  print(results)                                                                                                   
 ───────────────────────────────────────────────────────────────────────────────────────────────────────────────── 

经过几步操作之后,你会看到智能体生成的播放列表,阿尔弗雷德可以使用它来组织派对!🎵

使用自定义工具准备菜单

Alfred Menu

既然我们已经选好了播放列表,接下来就需要为宾客整理菜单了。同样,Alfred可以发挥作用。 smolagents 为此,我们采用了 @tool 使用装饰器来定义作为一个工具的自定义函数。我们将在后面更详细地介绍工具创建,所以目前,我们可以简单地运行代码。

如下面的例子所示,我们将使用以下工具来创建智能体: @tool 装饰器,并将其包含在内 tools 列表。

from smolagents import CodeAgent, tool, InferenceClientModel

# Tool to suggest a menu based on the occasion
@tool
def suggest_menu(occasion: str) -> str:
    """
    Suggests a menu based on the occasion.
    Args:
        occasion (str): The type of occasion for the party. Allowed values are:
                        - "casual": Menu for casual party.
                        - "formal": Menu for formal party.
                        - "superhero": Menu for superhero party.
                        - "custom": Custom menu.
    """
    if occasion == "casual":
        return "Pizza, snacks, and drinks."
    elif occasion == "formal":
        return "3-course dinner with wine and dessert."
    elif occasion == "superhero":
        return "Buffet with high-energy and healthy food."
    else:
        return "Custom menu for the butler."

# Alfred, the butler, preparing the menu for the party
agent = CodeAgent(tools=[suggest_menu], model=InferenceClientModel())

# Preparing the menu for the party
agent.run("Prepare a formal menu for the party.")

智能体会运行几步,直到找到答案。在文档字符串中明确指定允许的值有助于引导智能体进行下一步操作。 occasion 存在并限制幻觉的论点值。

菜单已经准备好了!🥗

使用智能体内部的 Python 导入语句

我们已经准备好了播放列表和菜单,但还需要检查一个至关重要的细节:准备时间!

阿尔弗雷德需要计算如果现在开始准备,一切何时能够就绪,以便他们需要其他超级英雄的帮助。

smolagents 专注于编写和执行Python代码片段的智能体,提供安全隔离的执行环境。

代码执行具有严格的安全措施 在预定义的安全列表之外进行的导入默认是会被阻止的。但是,您可以通过将其作为字符串传递来授权额外的导入。 additional_authorized_imports有关安全代码执行的更多详细信息,请参阅官方文档。 指南.

在创建智能体时,我们将使用 additional_authorized_imports 允许导入 datetime module.

from smolagents import CodeAgent, InferenceClientModel
import numpy as np
import time
import datetime

agent = CodeAgent(tools=[], model=InferenceClientModel(), additional_authorized_imports=['datetime'])

agent.run(
    """
    Alfred needs to prepare for the party. Here are the tasks:
    1. Prepare the drinks - 30 minutes
    2. Decorate the mansion - 60 minutes
    3. Set up the menu - 45 minutes
    4. Prepare the music and playlist - 45 minutes

    If we start right now, at what time will the party be ready?
    """
)

这些例子只是使用代码智能体所能实现的开始,我们已经开始看到它们在准备聚会方面的实用性。 您可以在以下链接了解更多关于如何构建代码智能体的信息: smolagents 文档.

总结来说, smolagents 专注于编写和执行Python代码片段的智能体,提供安全隔离的执行环境。它支持本地和基于API的语言模型,使其适用于各种开发环境。

将我们的定制派对准备智能体共享给中心

难道不会吗? 很荣幸能与社区分享我们自己的智能体 Alfred。通过这种方式,任何人都可以直接从Hub下载并使用智能体,从而轻松成为Gotham的终极派对策划者!让我们实现这一愿景吧!🎉

这个 smolagents 该库通过允许您与社区共享完整的智能体,并下载其他智能体以便立即使用,使这一切成为可能。其操作方式非常简单,如下所示:

# Change to your username and repo name
agent.push_to_hub('sergiopaniego/AlfredAgent')

要再次下载智能体,请使用以下代码:

# Change to your username and repo name
alfred_agent = agent.from_hub('sergiopaniego/AlfredAgent', trust_remote_code=True)

alfred_agent.run("Give me the best playlist for a party at Wayne's mansion. The party idea is a 'villain masquerade' theme")  

同样令人兴奋的是,这些共享智能体可以直接通过 Hugging Face Spaces 访问,从而可以实时与它们进行交互。您还可以探索其他智能体。 这里.

例如, 智能体 可用 这里你可以直接在下方尝试使用。

你可能会好奇——阿尔弗雷德是如何使用这样的智能体来构建这样的智能体的? smolagents? 通过整合多个工具,他可以生成如下智能体。暂时不必担心这些工具,因为在本单元的后续部分,我们将有一个专门的章节来详细探讨这些工具。

from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, Tool, tool, VisitWebpageTool

@tool
def suggest_menu(occasion: str) -> str:
    """
    Suggests a menu based on the occasion.
    Args:
        occasion: The type of occasion for the party.
    """
    if occasion == "casual":
        return "Pizza, snacks, and drinks."
    elif occasion == "formal":
        return "3-course dinner with wine and dessert."
    elif occasion == "superhero":
        return "Buffet with high-energy and healthy food."
    else:
        return "Custom menu for the butler."

@tool
def catering_service_tool(query: str) -> str:
    """
    This tool returns the highest-rated catering service in Gotham City.
    
    Args:
        query: A search term for finding catering services.
    """
    # Example list of catering services and their ratings
    services = {
        "Gotham Catering Co.": 4.9,
        "Wayne Manor Catering": 4.8,
        "Gotham City Events": 4.7,
    }
    
    # Find the highest rated catering service (simulating search query filtering)
    best_service = max(services, key=services.get)
    
    return best_service

class SuperheroPartyThemeTool(Tool):
    name = "superhero_party_theme_generator"
    description = """
    This tool suggests creative superhero-themed party ideas based on a category.
    It returns a unique party theme idea."""
    
    inputs = {
        "category": {
            "type": "string",
            "description": "The type of superhero party (e.g., 'classic heroes', 'villain masquerade', 'futuristic Gotham').",
        }
    }
    
    output_type = "string"

    def forward(self, category: str):
        themes = {
            "classic heroes": "Justice League Gala: Guests come dressed as their favorite DC heroes with themed cocktails like 'The Kryptonite Punch'.",
            "villain masquerade": "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains.",
            "futuristic gotham": "Neo-Gotham Night: A cyberpunk-style party inspired by Batman Beyond, with neon decorations and futuristic gadgets."
        }
        
        return themes.get(category.lower(), "Themed party idea not found. Try 'classic heroes', 'villain masquerade', or 'futuristic Gotham'.")


# Alfred, the butler, preparing the menu for the party
agent = CodeAgent(
    tools=[
        DuckDuckGoSearchTool(), 
        VisitWebpageTool(),
        suggest_menu,
        catering_service_tool,
        SuperheroPartyThemeTool(),
	FinalAnswerTool()
    ], 
    model=InferenceClientModel(),
    max_steps=10,
    verbosity_level=2
)

agent.run("Give me the best playlist for a party at the Wayne's mansion. The party idea is a 'villain masquerade' theme")

如你所见,我们已经创建了一个 CodeAgent 通过多种工具来增强智能体的功能,使其成为终极派对策划者,能够与社区共享!🎉

现在,轮到你了:创建你自己的智能体,并利用我们刚刚学到的知识与社区分享!🕵️💡

[!TIP] 如果您希望分享您的智能体项目,请创建一个空间并添加标签。 智能体课程 在 Hugging Face Hub 上。我们非常希望看到你创作的内容!

使用 OpenTelemetry 和 Langfuse 检查我们的 Party Preparator 智能体 📡

在智能体对Party Preparator Agent进行微调时,他越来越厌倦了调试其运行过程。智能体本质上是不可预测的,且难以被监控。但由于他希望打造出终极的Party Preparator Agent,并将其应用于实际生产环境中,因此他需要强大的可追溯性,以便未来能够对其进行监控和分析。

再次, smolagents 来救救啦!它欣然接受 OpenTelemetry 用于规范智能体运行的工具,从而实现无缝的监控和日志记录。在Hugging Face、smolagents、LlamaIndex、LangGraph及其他库的支持下。 Langfuse 以及 SmolagentsInstrumentor阿尔弗雷德能够轻松追踪和分析其智能体的行为。

设置起来非常简单!

首先,我们需要安装必要的依赖项:

pip install opentelemetry-sdk opentelemetry-exporter-otlp openinference-instrumentation-smolagents langfuse

接下来,Alfred已经在Langfuse上创建了账户,并且已经准备好了API密钥。如果您还没有注册,可以访问Langfuse Cloud进行注册。 这里 或探索 替代方案.

获取了 API 密钥后,需要按照以下步骤对其进行正确配置:

import os

# Get keys for your project from the project settings page: https://cloud.langfuse.com
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." 
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..." 
os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region
# os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region

在环境变量设置完成后,我们现在可以初始化 Langfuse 客户端。get_client() 函数使用环境变量中提供的凭据来初始化 Langfuse 客户端。

from langfuse import get_client
 
langfuse = get_client()
 
# Verify connection
if langfuse.auth_check():
    print("Langfuse client is authenticated and ready!")
else:
    print("Authentication failed. Please check your credentials and host.")

最后,Alfred已经准备好初始化了。 SmolagentsInstrumentor 并开始跟踪智能体的表现。

from openinference.instrumentation.smolagents import SmolagentsInstrumentor

SmolagentsInstrumentor().instrument()

Alfred 现已连接 🔌!正在运行… smolagents 智能体正在与 Langfuse 进行交互,这使他能够完全了解智能体的行为。有了这个设置,他可以重新审视之前的运行结果,并进一步改进他的 Party Preparator 智能体。

[!TIP] 要了解更多关于智能体追踪以及利用收集的数据来评估其性能的信息,请查看相关文档。 奖励单元2.

from smolagents import CodeAgent, InferenceClientModel

agent = CodeAgent(tools=[], model=InferenceClientModel())
alfred_agent = agent.from_hub('sergiopaniego/AlfredAgent', trust_remote_code=True)
alfred_agent.run("Give me the best playlist for a party at Wayne's mansion. The party idea is a 'villain masquerade' theme")  

Alfred 现在可以访问这些日志。 这里 对其进行审查和分析。

[!TIP] 实际上,在执行过程中出现了一个小错误。你能从日志中找出它吗?试着了解智能体是如何处理这个错误的,同时仍然返回有效的答案的。 这里 如果您想验证您的答案,这是通往错误的直接链接。当然,错误已经在此时被修复了,更多细节可以在这里找到。 提出.

与此同时, 建议的播放列表 为派对筹备营造完美的氛围。很酷,对吧?🎶


既然我们已经创建了第一个Code Agent,那么让我们 了解我们如何创建工具调用智能体,第二种可用的智能体 smolagents.

资源