組み込みツール

ADK-Rust は、カスタム実装を必要とせずにエージェントの機能を拡張する、複数の組み込みツールを提供します。これらのツールはすぐに使用でき、エージェントフレームワークとシームレスに統合されます。

プロバイダー固有の GenerateContentConfig.extensions blob ではなく、通常の Tool API を通じてプロバイダーのネイティブツールを宣言できるようになりました。これにより、Gemini Google Search、Anthropic Web Search、または OpenAI Responses のウェブ検索などのネイティブツールを、通常の FunctionTool インスタンスと同じエージェント内で組み合わせて使用できます。

概要

ツール目的使用例
#[tool] マクロボイラープレート不要のカスタムツール任意のカスタム関数 — 関数ツールを参照
FunctionToolカスタムツールの手動登録動的ツール、クロージャ
GoogleSearchToolGemini 経由のウェブ検索リアルタイム情報検索
UrlContextToolGemini URL グラウンディング最新の URLs の要約または推論
GoogleMapsToolGemini Google Maps グラウンディング場所、ルート、地域のコンテキスト
GeminiCodeExecutionToolGemini ネイティブコード実行サーバー側 Python 実行
WebSearchToolAnthropic ネイティブウェブ検索Claude サーバーサイドウェブ検索
OpenAIWebSearchToolOpenAI Responses ウェブ検索OpenAI ホスト型検索
AgentToolエージェントを呼び出し可能なツールとしてラップエージェントの構成と委任
ExitLoopToolループの終了LoopAgent の反復を制御
LoadArtifactsToolアーティファクトの読み込み保存されたバイナリデータへのアクセス

GoogleSearchTool

GoogleSearchTool により、エージェントは Google Search を使用してウェブを検索できます。このツールは、グラウンディング機能を通じて Gemini モデルによって内部的に処理されます。つまり、検索はモデル自体によってサーバー側で実行されます。

基本的な使用方法

use adk_rust::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = GeminiModel::new(&api_key, "gemini-3.7-flash")?;

    // Create the GoogleSearchTool
    let search_tool = GoogleSearchTool;

    // Add to agent
    let agent = LlmAgentBuilder::new("research_assistant")
        .description("An assistant that can search the web for information")
        .instruction(
            "You are a research assistant. When asked about current events, \
             recent news, or factual information, use the google_search tool \
             to find accurate, up-to-date information."
        )
        .model(Arc::new(model))
        .tool(Arc::new(search_tool))
        .build()?;

    println!("Agent created with Google Search capability!");
    Ok(())
}

仕組み

通常の関数ツールとは異なり、GoogleSearchTool は次のように動作します。

  1. サーバー側での実行: 検索はローカルではなく、Gemini のグラウンディング機能によって実行されます
  2. 自動呼び出し: モデルはクエリに基づいて検索するタイミングを判断します
  3. 結果の統合: 検索結果はモデルのレスポンスに直接組み込まれます

実際の検索は Gemini API 内で行われるため、ツールの実装を直接呼び出すとエラーが返されます。

// This is handled internally - you don't call it directly
async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
    Err(AdkError::tool("GoogleSearch is handled internally by Gemini"))
}

ツールの詳細

プロパティ値
名前google_search
説明"ウェブから情報を取得するために Google 検索を実行します。"
パラメータGemini モデルによって決定
実行サーバー側(Gemini グラウンディング)

ユースケース

  • 現在の出来事: 「今日のニュースで何が起きましたか?」
  • 事実に関する質問: 「東京の人口はどのくらいですか?」
  • 最新情報: 「AI における最新の進展は何ですか?」
  • 調査タスク: 「再生可能エネルギーの動向に関する情報を見つけてください」

クエリの例

// The agent will automatically use Google Search for queries like:
// - "What's the weather forecast for New York this week?"
// - "Who won the latest championship game?"
// - "What are the current stock prices for tech companies?"

AgentTool

AgentTool は任意のエージェントを呼び出し可能なツールとしてラップし、委譲して結果を返す構成を可能にします。呼び出し元は子エージェントを呼び出してその結果を受け取り、その後処理を再開します。子エージェントが出力した状態とアーティファクトの差分は、親ツールのイベントにマージされます。子セッションも各イベントを直ちに適用するため、委譲されたワークフローの後続ステップでは、それ以前の状態や履歴の変更を確認できます。

従来のデフォルトは分離されたままで、後方互換性があります。ポータブルチームでは、親の履歴および状態スナップショット、メモリの転送、伝播された失敗、委譲の有限深度、状態および履歴の正確な投影、登録済みの子ハンドオフの内部実行をオプトインできます。消費された子ハンドオフはイベントとして引き続き表示されますが、転送前にその転送アクションがクリアされるため、親 Runner が二重に実行することはありません。リクエストのメタデータ、キャンセル、スコープ、シークレット、アーティファクト、並列共有状態は、構成された転送ポリシーに従います。AgentTool 自体は Runner のグローバルなハンドオフループを実行しません。コンパイル済みの TeamSpec が、混在トポロジーに必要な正確なネストされたハンドオフレジストリを提供します。コンパイル済みのチームでは、ネストされたイベント転送もオプトインされるため、委譲されたアクティビティが親のイベントストリームに引き続き表示されます。スタンドアロンの AgentTool は、forward_events(true) が選択されない限り、従来のイベント出力を維持します。

制御された書き戻しには、入力の state_keys projection とは独立して output_state_keys を使用します。state_merge_policy(RejectConflicts) は、現在の親の値と委譲開始時に取得したスナップショットを比較し、競合する書き込みをアトミックに拒否します。artifact_prefixes は、同じ許可リストの原則をアーティファクト名にも適用します。スタンドアロンのデフォルトでは、後勝ちで無制限の出力が引き続き使用され、後方互換性が維持されます。コンパイル済みのチームでは、各エッジのポリシーを明示的に選択できます。

基本的な使用方法

use adk_rust::prelude::*;
use adk_tool::AgentTool;
use std::sync::Arc;

let sub_agent = LlmAgentBuilder::new("summarizer")
    .description("Summarizes text content")
    .instruction("Summarize the provided text concisely.")
    .model(model.clone())
    .build()?;

let agent_tool = AgentTool::new(Arc::new(sub_agent));

let coordinator = LlmAgentBuilder::new("coordinator")
    .instruction("Use the summarizer tool when asked to summarize content.")
    .model(model.clone())
    .tool(Arc::new(agent_tool))
    .build()?;

動作の仕組み

  1. 親エージェントが、ラップされたエージェントをツールとして呼び出すことを決定する
  2. AgentTool が StreamingMode::None を含む呼び出しコンテキストを作成する
  3. サブエージェントが完了まで実行され、完全な応答を蓄積する
  4. 応答テキストが親エージェントに返される
  5. 状態差分とアーティファクト差分が親コンテキストに転送される

ツールの詳細

プロパティ値
名前ラップされたエージェントの名前と同じ
説明ラップされたエージェントの説明と同じ
パラメーターrequest: string(サブエージェントに送信する入力)
戻り値サブエージェントのテキスト出力を含む {"response": "..."}

主な動作

  • サブエージェントは、信頼性の高いレスポンス取得のため、内部では非ストリーミングモードで実行されます
  • サブエージェントによる状態変更(output_key)は、親セッションに伝播します
  • サブエージェントによって保存されたアーティファクトは、親コンテキストに転送されます
  • エージェントの構成パターンについて詳しくは、マルチエージェントシステムを参照してください

ExitLoopTool

ExitLoopToolは、反復プロセスを終了すべきタイミングを通知するためにLoopAgentとともに使用される制御ツールです。呼び出されると、escalateフラグを設定し、ループを終了させます。

基本的な使用方法

use adk_rust::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = GeminiModel::new(&api_key, "gemini-3.7-flash")?;

    // Create an agent with ExitLoopTool for iterative refinement
    let refiner = LlmAgentBuilder::new("content_refiner")
        .description("Iteratively improves content quality")
        .instruction(
            "Review the content and improve it. Check for:\n\
             1. Clarity and readability\n\
             2. Grammar and spelling\n\
             3. Logical flow\n\n\
             If the content meets all quality standards, call the exit_loop tool.\n\
             Otherwise, provide an improved version."
        )
        .model(Arc::new(model))
        .tool(Arc::new(ExitLoopTool::new()))
        .build()?;

    // Use in a LoopAgent
    let loop_agent = LoopAgent::new(
        "iterative_refiner",
        vec![Arc::new(refiner)],
    ).with_max_iterations(5);

    println!("Loop agent created with exit capability!");
    Ok(())
}

動作の仕組み

  1. エージェントは、続行するか終了するかを判断します
  2. 終了の準備が整うと、エージェントはexit_loopを呼び出します
  3. ツールはactions.escalate = trueとactions.skip_summarization = trueを設定します
  4. LoopAgentはエスカレーションフラグを検出し、反復を停止します

ツールの詳細

プロパティ値
名前exit_loop
説明"ループを終了します。この関数は、実行するよう指示された場合にのみ呼び出してください。"
パラメータなし
戻り値空のオブジェクト {}

ベストプラクティス

  1. 明確な終了条件: エージェントの指示に具体的な条件を定義する
  2. 常に max_iterations を設定する: 安全対策として無限ループを防止する
  3. 意味のある指示: エージェントが終了すべきタイミングを理解できるようにする
// Good: Clear exit criteria
.instruction(
    "Improve the text until it:\n\
     - Has no grammatical errors\n\
     - Is under 100 words\n\
     - Uses active voice\n\
     When all criteria are met, call exit_loop."
)

// Avoid: Vague criteria
.instruction("Improve the text. Exit when done.")

LoadArtifactsTool

LoadArtifactsTool により、エージェントは保存されたアーティファクトを名前で取得できます。これは、以前に保存されたファイル、画像、その他のバイナリデータにエージェントがアクセスする必要がある場合に便利です。

基本的な使用方法

use adk_rust::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = GeminiModel::new(&api_key, "gemini-3.7-flash")?;

    // Create agent with artifact loading capability
    let agent = LlmAgentBuilder::new("document_analyzer")
        .description("Analyzes stored documents")
        .instruction(
            "You can load and analyze stored artifacts. \
             Use the load_artifacts tool to retrieve documents by name. \
             The tool accepts an array of artifact names."
        )
        .model(Arc::new(model))
        .tool(Arc::new(LoadArtifactsTool::new()))
        .build()?;

    println!("Agent created with artifact loading capability!");
    Ok(())
}

ツールの詳細

プロパティ値
名前load_artifacts
説明「名前でアーティファクトを読み込み、その内容を返します。アーティファクト名の配列を受け付けます。」
パラメータartifact_names: 文字列の配列
戻り値artifacts 配列を持つオブジェクト

パラメータ

このツールは、artifact_names配列を含むJSONオブジェクトを必要とします。

{
  "artifact_names": ["document.txt", "image.png", "data.json"]
}

レスポンス形式

このツールは、読み込まれたアーティファクトを含むオブジェクトを返します。

{
  "artifacts": [
    {
      "name": "document.txt",
      "content": "The text content of the document..."
    },
    {
      "name": "image.png",
      "content": {
        "mime_type": "image/png",
        "data": "base64-encoded-data..."
      }
    },
    {
      "name": "missing.txt",
      "error": "Artifact not found"
    }
  ]
}

要件

LoadArtifactsToolを動作させるには、以下が必要です。

  1. runner で構成されたArtifactService
  2. サービスに以前保存されたアーティファクト
  3. エージェントに追加されたツール
use adk_rust::prelude::*;
use std::sync::Arc;

// Set up artifact service
let artifact_service = Arc::new(InMemoryArtifactService::new());

// Configure runner with artifact service
let runner = Runner::new(agent)
    .with_artifact_service(artifact_service);

組み込みツールの組み合わせ

複数の組み込みツールを組み合わせて使用できます。

use adk_rust::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = GeminiModel::new(&api_key, "gemini-3.7-flash")?;

    // Create agent with multiple built-in tools
    let agent = LlmAgentBuilder::new("research_agent")
        .description("Research agent with search and artifact capabilities")
        .instruction(
            "You are a research agent. You can:\n\
             - Search the web using google_search for current information\n\
             - Load stored documents using load_artifacts\n\
             Use these tools to help answer questions comprehensively."
        )
        .model(Arc::new(model))
        .tool(Arc::new(GoogleSearchTool))
        .tool(Arc::new(LoadArtifactsTool::new()))
        .build()?;

    println!("Multi-tool agent created!");
    Ok(())
}

カスタム組み込みツールの作成

Toolトレイトを実装することで、組み込みツールと同じパターンに従って独自のツールを作成できます。

use adk_rust::prelude::*;
use async_trait::async_trait;
use serde_json::{json, Value};
use std::sync::Arc;

pub struct MyCustomTool;

impl MyCustomTool {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl Tool for MyCustomTool {
    fn name(&self) -> &str {
        "my_custom_tool"
    }

    fn description(&self) -> &str {
        "Description of what this tool does"
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        // Your tool logic here
        Ok(json!({ "result": "success" }))
    }
}

APIリファレンス

GoogleSearchTool

impl GoogleSearchTool {
    /// Create a new GoogleSearchTool instance
    pub fn new() -> Self;
}

ExitLoopTool

impl ExitLoopTool {
    /// Create a new ExitLoopTool instance
    pub fn new() -> Self;
}

LoadArtifactsTool

impl LoadArtifactsTool {
    /// Create a new LoadArtifactsTool instance
    pub fn new() -> Self;
}

impl Default for LoadArtifactsTool {
    fn default() -> Self;
}

前へ: ← 関数ツール | 次へ: ブラウザーツール →