管理代理記憶體

使用 Hugging Face smolagents 的 AI 代理

Adel Nehme

VP of AI Curriculum, DataCamp

使用 Hugging Face smolagents 的 AI 代理

預設無狀態

每次呼叫 .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 代理

在互動間保留記憶

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 代理

記憶體也能幫你除錯

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 代理

代理實際執行了哪些程式碼?

.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 代理

代理在想什麼?

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 代理

儲存代理工作階段以供分析

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 代理

修正代理失敗:可調整項目

  • 記憶體問題: 使用 reset=False,或有意地重設
  • 推理問題: 嘗試更強的模型
  • 行為不一致: 改善系統提示
  • 工具混淆: 釐清工具的 docstring
使用 Hugging Face smolagents 的 AI 代理

一起來練習吧!

使用 Hugging Face smolagents 的 AI 代理

Preparing Video For Download...