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ステップごとにエージェントが一時停止して再計画する。「歴史的名所を楽しむ大人と子供向けのアクティビティを含む、5000ドル以内のヨーロッパ2週間家族旅行を計画してください。」
[ステップ1] 「パリのホテル」を検索 -> 高級ホテルが見つかる(合計約4000ドル)
[ステップ2] 「パリの家族向け観光スポット」を検索 -> エッフェル塔、ルーヴル美術館、テーマパークチケットが見つかる
[ステップ3] 一時停止して再考(プランニング間隔) ホテルが高すぎて予算オーバー。 安い宿泊先と子供向けアクティビティを探し直す必要がある。
[ステップ4] 「ヨーロッパのリーズナブルな家族向けホテル」を検索 -> 複数都市の中価格帯の選択肢が見つかる

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 エージェント