組み込みツール

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

概要

ツール目的ユースケース
GoogleSearchToolGemini経由のウェブ検索リアルタイムの情報検索
ExitLoopToolループ終了LoopAgentのイテレーションの制御
LoadArtifactsToolアーティファクトのロード格納されたバイナリデータへのアクセス

GoogleSearchTool

GoogleSearchToolは、エージェントがGoogle検索を使用してウェブを検索できるようにします。このツールは、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-2.5-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(())
}

仕組み

通常のFunctionToolとは異なり、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".to_string()))
}

ツールの詳細

プロパティ
Namegoogle_search
Description"Performs a Google search to retrieve information from the web."
ParametersGeminiモデルによって決定されます
Executionサーバーサイド (Geminiグラウンディング)

ユースケース

  • 時事問題: 「今日のニュースで何がありましたか?」
  • 事実に基づくクエリ: 「東京の人口はどれくらいですか?」
  • 最新情報: 「AIの最新の開発状況はどうなっていますか?」
  • 調査タスク: 「再生可能エネルギーのトレンドに関する情報を見つけてください」

クエリ例

// エージェントは、次のようなクエリに対して自動的にGoogle検索を使用します。
// - "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?"

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-2.5-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. agent は続行するか終了するかを評価します。
  2. 終了準備ができたとき、agent は exit_loop を呼び出します。
  3. ツールは actions.escalate = trueactions.skip_summarization = true を設定します。
  4. LoopAgent は escalate フラグを検出し、反復を停止します。

ツール詳細

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

ベストプラクティス

  1. 明確な終了条件: agent の instruction で具体的な条件を定義します。
  2. 常に max_iterations を設定: 安全策として無限ループを防ぎます。
  3. 意味のある指示: agent がいつ終了すべきかを理解するのに役立ちます。
// 良い例: 明確な終了条件
.instruction(
    "テキストを以下のようになるまで改善してください。\n\
     - 文法的な誤りがない\n\
     - 100語未満である\n\
     - 能動態を使用している\n\
     すべての条件が満たされたら、exit_loopを呼び出してください。"
)

// 避けるべき例: 曖昧な条件
.instruction("テキストを改善してください。完了したら終了してください。")

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-2.5-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(())
}

Tool の詳細

プロパティ
Nameload_artifacts
Description"名前でアーティファクトをロードし、その内容を返します。アーティファクト名の配列を受け入れます。"
Parametersartifact_names: 文字列の配列
Returnsartifacts 配列を持つオブジェクト

パラメータ

この tool は artifact_names 配列を持つ JSON オブジェクトを期待します。

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

レスポンス形式

この tool はロードされたアーティファクトを含むオブジェクトを返します。

{
  "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. agent に追加された tool
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);

組み込み Tool の組み合わせ

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

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-2.5-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 {
    /// 新しい GoogleSearchTool インスタンスを作成します
    pub fn new() -> Self;
}

ExitLoopTool

impl ExitLoopTool {
    /// 新しい ExitLoopTool インスタンスを作成します
    pub fn new() -> Self;
}

LoadArtifactsTool

impl LoadArtifactsTool {
    /// 新しい LoadArtifactsTool インスタンスを作成します
    pub fn new() -> Self;
}

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

関連

  • Function Tools - カスタム FunctionTool の作成
  • MCP Tools - ツールプロバイダーとしての MCP サーバーの使用
  • Workflow Agents - LoopAgent での ExitLoopTool の使用
  • Artifacts - artifacts を使用したバイナリデータの管理

前へ: ← Function Tools | 次へ: Browser Tools →