多步代理的使用

使用 Hugging Face smolagents 的 AI Agents

Adel Nehme

VP of AI Curriculum, DataCamp

使用 Hugging Face smolagents 的 AI Agents

示例:旅行助理

使用 Hugging Face smolagents 的 AI Agents

规划间隔:帮助代理重新思考

agent = CodeAgent(
    tools=[document_search_tool],
    model=model,
    planning_interval=3,
    max_steps=12
)
  • planning_interval=3:代理每 3 步暂停一次。
使用 Hugging Face smolagents 的 AI Agents

带规划间隔的代理运行示例

"规划一次两周的欧洲亲子游:成人看历史,孩子有趣味活动,总预算不超过 $5000。"

[步骤 1] 搜索"巴黎 酒店" -> 发现豪华酒店(约 $4000 总计)

[步骤 2] 搜索"巴黎 亲子景点" -> 发现埃菲尔铁塔、卢浮宫、主题公园门票

[步骤 3] 暂停并重思(规划间隔) 酒店过贵 -> 预算超支。 应找更便宜选项 + 亲子活动。

[步骤 4] 搜索"欧洲 亲民亲子酒店" -> 在多座城市找到中档选项

使用 Hugging Face smolagents 的 AI Agents

回调:介入代理流程的钩子

使用 Hugging Face smolagents 的 AI Agents

基础回调函数

def callback_function(agent_step, agent):
    # Do something with the agent step or the agent itself
    pass
  • agent_step:该步骤的详细信息(计划、步号等)
  • agent:完整的代理对象(状态 + 方法)
使用 Hugging Face smolagents 的 AI Agents

规划步骤回调

def planning_callback(agent_step, agent):
    print("AGENT PLANNING")
    print("=" * 50)
    print(agent_step.plan[:300])
    if len(agent_step.plan) > 300:
        print("\n... (plan truncated)")
    print("=" * 50)
AGENT PLANNING
==================================================
Search affordable hotels + kid activities
Then create balanced itinerary...
... (plan truncated)
==================================================
使用 Hugging Face smolagents 的 AI Agents

执行步骤回调

def action_callback(agent_step, agent):
    step_num = agent_step.step_number
    print(f"Step {step_num}: Taking action")

    if agent_step.is_final_answer:
        total_tokens = agent_step.token_usage.total_tokens
        print(f"Total tokens used: {total_tokens}")
Step 2: Taking action!
Step 3: Taking action!
Step 4: Taking action!
Total tokens used: 4,218
使用 Hugging Face smolagents 的 AI Agents

为代理添加回调

from smolagents import ActionStep, PlanningStep

agent = CodeAgent(
    tools=[document_search_tool],
    model=model,
    step_callbacks={PlanningStep: planning_callback, ActionStep: action_callback}
)
使用 Hugging Face smolagents 的 AI Agents

回调能做什么?

  • 记录搜索,了解用户最常查找内容
  • 增加人工审批检查点
  • 将进度推送到仪表板或应用
  • 运行中按表现调整代理行为
  • 以及更多…
使用 Hugging Face smolagents 的 AI Agents

Passons à la pratique !

使用 Hugging Face smolagents 的 AI Agents

Preparing Video For Download...