マルチステップエージェントの活用

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

プランニング間隔を使ったエージェントの実行例

「歴史的名所を楽しむ大人と子供向けのアクティビティを含む、5000ドル以内のヨーロッパ2週間家族旅行を計画してください。」

[ステップ1] 「パリのホテル」を検索 -> 高級ホテルが見つかる(合計約4000ドル)

[ステップ2] 「パリの家族向け観光スポット」を検索 -> エッフェル塔、ルーヴル美術館、テーマパークチケットが見つかる

[ステップ3] 一時停止して再考(プランニング間隔) ホテルが高すぎて予算オーバー。 安い宿泊先と子供向けアクティビティを探し直す必要がある。

[ステップ4] 「ヨーロッパのリーズナブルな家族向けホテル」を検索 -> 複数都市の中価格帯の選択肢が見つかる

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