多步驟代理的運作

使用 Hugging Face smolagents 的 AI 代理

Adel Nehme

VP of AI Curriculum, DataCamp

使用 Hugging Face smolagents 的 AI 代理

範例:旅遊助理

使用 Hugging Face smolagents 的 AI 代理

規劃間隔:幫助代理重新思考

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

含規劃間隔的代理執行流程

「Plan a 2-week family vacation to Europe with historical sites for adults and fun activities for kids, staying under $5000.」

[Step 1] 搜尋「Paris hotels」 -> 找到豪華飯店(總計約 $4000)

[Step 2] 搜尋「Paris attractions for families」 -> 找到艾菲爾鐵塔、羅浮宮、主題樂園門票

[Step 3] 暫停並重想(規劃間隔) 飯店太貴 -> 超出預算。 我該找更便宜且適合親子的選項。

[Step 4] 搜尋「affordable family hotels in Europe」 -> 在多個城市找到中價位選項

使用 Hugging Face smolagents 的 AI 代理

回呼:掛勾代理的執行流程

使用 Hugging Face smolagents 的 AI 代理

基本回呼函式

def callback_function(agent_step, agent):
    # Do something with the agent step or the agent itself
    pass
  • agent_step:此步驟的細節(計畫、步驟編號等)
  • agent:完整的代理物件(狀態 + 方法)
使用 Hugging Face smolagents 的 AI 代理

規劃步驟回呼

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

動作步驟回呼

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

將回呼加入代理

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

回呼可以做什麼?

  • 記錄搜尋,以了解使用者最常找什麼
  • 加入人工審核檢查點
  • 將進度更新送到儀表板或應用程式
  • 依表現在執行中調整代理行為
  • 還有更多……
使用 Hugging Face smolagents 的 AI 代理

一起來練習吧!

使用 Hugging Face smolagents 的 AI 代理

Preparing Video For Download...