使用 Hugging Face smolagents 的 AI 代理
Adel Nehme
VP of AI Curriculum, DataCamp



agent = CodeAgent(
tools=[document_search_tool],
model=model,
planning_interval=3,
max_steps=12
)
planning_interval=3:代理每 3 個步驟暫停一次。「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」 -> 在多個城市找到中價位選項

def callback_function(agent_step, agent):
# Do something with the agent step or the agent itself
pass
agent_step:此步驟的細節(計畫、步驟編號等) agent:完整的代理物件(狀態 + 方法)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)
==================================================
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
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 代理