构建使用代码的 Agent

smolagents 中,Code Agent 是默认的 Agent 类型。它们生成 Python 工具调用,执行行动,实现高效、富有表现力、准确的行动表示。

其精简方式减少所需的行动数量,简化复杂操作,实现现有代码函数的复用。smolagents 实现构建 Code Agent 的轻量级框架,整个实现大约只有 1000 行代码。


1. 为什么使用 smolagents

在多步骤 Agent 处理中,LLM 编写及执行行动,通常涉及外部工具调用。传统方法使用 JSON 格式指定工具名称和参数,系统必须解析才能确定执行哪个工具

然而,研究表明,支持工具调用的 LLM 直接使用代码时效果更好。这是 smolagents 的核心原则。

使用代码而非 JSON 编写行动具有以下几个关键优势:


2. Code Agent 的工作原理

上图展示 CodeAgent.run() 的运行方式,其遵循 ReAct 框架。在 smolagents 中,Agent 的主要抽象是 MultiStepAgent,其为核心构件。Code Agent 是特殊的 MultiStepAgent

Code Agent 通过步骤循环执行行为,现有的变量和知识将被整合到 Agent 的上下文中,这些信息都保存在执行日志中:

  1. 系统提示词存储在 SystemPromptStep 中,用户查询记录在 TaskStep 中。
  1. 执行下面的 while 循环:
    1. 方法 agent.write_memory_to_messages() 将 Agent 的日志写到 LLM 可读的聊天消息列表中。
    1. 这些消息被发送到用于生成 completion 的 Model
    1. 解析 completion,提取行动,在本例中,由于使用的是 Code Agent,所以行动应该是代码片段。
    1. 执行行动。
    1. 结果将被记录到记忆系统中的 ActionStep 里。

在每个步骤结束时,如果 Agent 包含函数调用(在 agent.step_callback 中),它们将被执行。


3. 示例

Alfred 正在 Wayne 家族庄园策划一场派对,需要你的帮助确保一切顺利进行。为帮助他,我们将运用所学的关于多步骤 Code Agent 如何运作的知识。

如果尚未安装 smolagents,那么运行如下命令安装:

pip install smolagents -U

下面登录 Hugging Face Hub,以便访问 Serverless 推理 API。

from huggingface_hub import login

login()

3.1. 使用 smolagents 为派对选择音乐播放列表

音乐是成功派对的重要组成部分!Alfred 需要一些帮助,以选择播放列表。幸运的是,smolagents 可以帮我们解决这个问题!我们可以构建能够使用 DuckDuckGo 搜索网络的 Agent。为使 Agent 能够使用该工具,在创建 Agent 时将其包含在工具列表中。

对于模型,我们将使用 HfApiModel,它提供对 Hugging Face 的 Serverless 推理 API 的访问。默认模型是 "Qwen/Qwen2.5-Coder-32B-Instruct",这个模型性能优秀且支持快速推理,但也可以从 Hub 中选择任何兼容的模型。

运行 Agent 非常简单:

from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel

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

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 的派对生成的播放列表!

3.2. 使用工具准备菜单

既然已经选择播放列表,现在需要为客人们组织菜单。Alfred 可以再次利用 smolagents 完成该任务。此处使用 @tool 装饰器定义作为工具的自定义函数。稍后将详细介绍创建工具的过程,现在可以直接运行代码。

下面的示例使用 @tool 装饰器创建工具,并且将其包含在工具列表中。

from smolagents import CodeAgent, tool, HfApiModel

# 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=HfApiModel())

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

Agent 将运行若干步,直到找到答案。在文档字符串中精确地指定可用值有助于 Agent 直接指定已存在的参数值,并且限制幻觉。

3.3. 在 Agent 内部使用 Python import

smolagents 是专攻编写及执行 Python 代码片段的 Agent,为安全性起见,其提供沙箱执行环境。

代码执行具有严格的安全考量 - 默认情况下,将阻止从预定义的安全列表之外导入。但可以通过在 additional_authorized_imports 中以字符串形式传递的方式,授权额外的导入。

在创建 Agent 时,可以使用 additional_authorized_imports 导入 datetime 模块。

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

agent = CodeAgent(tools=[], model=HfApiModel(), 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 同时支持本地和基于 API 的语言模型,使其能够适应各种开发环境。