管理代理的记忆

使用 Hugging Face smolagents 的 AI Agents

Adel Nehme

VP of AI Curriculum, DataCamp

记忆为何重要

使用 Hugging Face smolagents 的 AI Agents

默认无状态

每次 .run() 调用都会重新开始。

  • 示例:
career_advisor.run("What career skills should I highlight?")
You should highlight Python, SQL, data visualization, 
machine learning fundamentals, and communication skills tailored to business outcomes.
career_advisor.run("Can you format those skills as bullet points?")
Sorry, I'm not sure which skills you're referring to. Could you clarify?
使用 Hugging Face smolagents 的 AI Agents

在交互间保留记忆

career_advisor.run("What career skills should I highlight?")
You should highlight Python, SQL, data visualization, 
machine learning fundamentals, and communication skills tailored to business outcomes.
  • 传入 reset=False
career_advisor.run("Can you format those skills as bullet points?", reset=False)
Sure! Here are the skills as bullet points:
- Python
- SQL
- Data visualization
...
使用 Hugging Face smolagents 的 AI Agents

记忆也有助于调试

User: What's the expected salary?
Agent: It's $80,000
User: Wait, that seems wrong...
Agent: Sorry, I'm not sure what you mean

检查该次运行发生了什么:

  • 回看代理生成的全部代码
  • 追踪其推理、动作与工具使用
  • 调试错误答案或有问题的逻辑
使用 Hugging Face smolagents 的 AI Agents

代理运行了哪些代码?

.return_full_code() 方法可查看所有已执行代码。

executed_code = career_advisor.memory.return_full_code()
print(executed_code)
# ...other steps omitted for brevity

salary = 80000  # <- hardcoded?

# script continues...
使用 Hugging Face smolagents 的 AI Agents

代理在想什么?

conversation_steps = career_advisor.memory.get_succinct_steps()
print(conversation_steps[5])
{
  "step_number": 5,
  "tool_calls": [
    {"function": {"name": "python_interpreter"}},
    {"function": {"name": "web_search"}}
  ],
  "code_action": "import requests\nskills = requests.get('api.jobsearch.com').json()",
  "observations": "resume_agent found 15 relevant skills for transition",
  "token_usage": {"total_tokens": 334},
  ...
}
使用 Hugging Face smolagents 的 AI Agents

保存会话以供分析

import json

def save_agent_memory(agent):
    with open("agent_memory.json", "w") as f:
        json.dump(agent.memory.get_succinct_steps(), f, indent=2, default=str)

# Save memory to a file
save_agent_memory(career_advisor)

日志可用于:

  • 事后分析
  • 回归测试
  • 持续改进代理行为
使用 Hugging Face smolagents 的 AI Agents

修复代理失败:调整什么

  • 记忆问题:使用 reset=False,或按需重置
  • 推理问题:尝试更强的模型
  • 行为不一致:优化 system prompt
  • 工具混淆:完善工具 docstring
使用 Hugging Face smolagents 的 AI Agents

让我们来练习!

使用 Hugging Face smolagents 的 AI Agents

Preparing Video For Download...