smolagents 文档

📚 管理智能体的内存

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

📚 管理智能体的内存

归根结底,智能体可以由简单的组件定义:它有工具、提示词。最重要的是,它有过去步骤的记忆,记录了规划、执行和错误的历史。

重放智能体的记忆

我们提供了几个功能来检查过去的智能体运行情况。

您可以检测智能体的运行,并将其显示在一个出色的用户界面中,让您可以放大/缩小特定步骤,如 检测指南 中所述。

您还可以使用 agent.replay(),如下所示

在智能体运行之后

from smolagents import InferenceClientModel, CodeAgent

agent = CodeAgent(tools=[], model=InferenceClientModel(), verbosity_level=0)

result = agent.run("What's the 20th Fibonacci number?")

如果您想重放这最后一次运行,只需使用

agent.replay()

动态更改智能体的记忆

许多高级用例需要动态修改智能体的记忆。

您可以使用以下方式访问智能体的记忆

from smolagents import ActionStep

system_prompt_step = agent.memory.system_prompt
print("The system prompt given to the agent was:")
print(system_prompt_step.system_prompt)

task_step = agent.memory.steps[0]
print("\n\nThe first task step was:")
print(task_step.task)

for step in agent.memory.steps:
    if isinstance(step, ActionStep):
        if step.error is not None:
            print(f"\nStep {step.step_number} got this error:\n{step.error}\n")
        else:
            print(f"\nStep {step.step_number} got these observations:\n{step.observations}\n")

使用 agent.memory.get_full_steps() 以字典形式获取完整步骤。

您还可以使用步骤回调来动态更改智能体的记忆。

步骤回调可以在其参数中访问 agent 本身,因此它们可以像上面所强调的那样访问任何记忆步骤,并根据需要进行更改。例如,假设您正在观察网络浏览器智能体执行的每个步骤的屏幕截图。您希望记录最新的屏幕截图,并从旧步骤中删除图像以节省词元成本。

您可以运行类似下面的代码。注意:此代码不完整,为简洁起见,已删除一些导入和对象定义,请访问 原始脚本 获取完整的可运行代码。

import helium
from PIL import Image
from io import BytesIO
from time import sleep

def update_screenshot(memory_step: ActionStep, agent: CodeAgent) -> None:
    sleep(1.0)  # Let JavaScript animations happen before taking the screenshot
    driver = helium.get_driver()
    latest_step = memory_step.step_number
    for previous_memory_step in agent.memory.steps:  # Remove previous screenshots from logs for lean processing
        if isinstance(previous_memory_step, ActionStep) and previous_memory_step.step_number <= latest_step - 2:
            previous_memory_step.observations_images = None
    png_bytes = driver.get_screenshot_as_png()
    image = Image.open(BytesIO(png_bytes))
    memory_step.observations_images = [image.copy()]

然后,您应该在初始化智能体时将此函数传递给 step_callbacks 参数

CodeAgent(
    tools=[WebSearchTool(), go_back, close_popups, search_item_ctrl_f],
    model=model,
    additional_authorized_imports=["helium"],
    step_callbacks=[update_screenshot],
    max_steps=20,
    verbosity_level=2,
)

前往我们的 视觉网络浏览器代码 查看完整的可运行示例。

逐个步骤运行智能体

这在您有需要数天才能完成的工具调用时非常有用:您可以一步一步地运行您的智能体。这还允许您在每个步骤更新记忆。

from smolagents import InferenceClientModel, CodeAgent, ActionStep, TaskStep

agent = CodeAgent(tools=[], model=InferenceClientModel(), verbosity_level=1)
agent.python_executor.send_tools({**agent.tools})
print(agent.memory.system_prompt)

task = "What is the 20th Fibonacci number?"

# You could modify the memory as needed here by inputting the memory of another agent.
# agent.memory.steps = previous_agent.memory.steps

# Let's start a new task!
agent.memory.steps.append(TaskStep(task=task, task_images=[]))

final_answer = None
step_number = 1
while final_answer is None and step_number <= 10:
    memory_step = ActionStep(
        step_number=step_number,
        observations_images=[],
    )
    # Run one step.
    final_answer = agent.step(memory_step)
    agent.memory.steps.append(memory_step)
    step_number += 1

    # Change the memory as you please!
    # For instance to update the latest step:
    # agent.memory.steps[-1] = ...

print("The final answer is:", final_answer)
< > 在 GitHub 上更新