組み込みツール

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

プロバイダーネイティブツールは、プロバイダー固有の GenerateContentConfig.extensions blob の代わりに、通常の Tool API を介して宣言されるようになりました。これは、Gemini Google Search、Anthropic Web Search、または OpenAI Responses web search のようなネイティブツールを、同じエージェント内で通常の FunctionTool インスタンスと混在させることができることを意味します。

概要

ツール目的ユースケース
#[tool] macroボイラープレートなしのカスタムツール任意のカスタム関数 — Function Toolsを参照
FunctionTool手動カスタムツール登録動的ツール、クロージャ
GoogleSearchToolGeminiを介したウェブ検索リアルタイム情報検索
UrlContextToolGemini URL グラウンディングライブのURLsを要約または推論
GoogleMapsToolGemini Google Maps グラウンディング場所、ルート、およびローカルコンテキスト
GeminiCodeExecutionToolGeminiネイティブコード実行サーバーサイドPython実行
WebSearchToolAnthropicネイティブウェブ検索Claudeサーバーサイドウェブ検索
OpenAIWebSearchToolOpenAIレスポンスウェブ検索OpenAI-ホスト型検索
AgentToolAgentを呼び出し可能なToolとしてラップするAgentの構成と委任
ExitLoopToolループの終了LoopAgentイテレーションの制御
LoadArtifactsToolアーティファクトの読み込み保存されたバイナリデータへのアクセス

GoogleSearchTool Google検索ツール

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

基本的な使用法

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のgrounding featureによって実行され、ローカルでは実行されません
  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 grounding)

ユースケース

  • 現在のイベント: 「今日のニュースで何が起こりましたか?」
  • 事実に関するクエリ: 「東京の人口はどれくらいですか?」
  • 最新情報: 「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 は、任意のエージェントを呼び出し可能なツールとしてラップし、親エージェントがツール呼び出しワークフローの一部として子エージェントを呼び出すことができるエージェントコンポジションを可能にします。サブエージェントからの状態変更とアーティファクトは、親コンテキストに自動的に転送されます。

基本的な使用法

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-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. エージェントは続行するか終了するかを評価します
  2. 終了する準備ができたとき、エージェントは exit_loop を呼び出します
  3. ツールは actions.escalate = trueactions.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-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(())
}

ツールの詳細

プロパティ
名前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. agentに追加されたツール
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-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 {
    /// 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;
}
  • Function Tools - カスタムFunction Toolの作成
  • MCP Tools - MCPサーバーをツールプロバイダーとして使用する
  • Workflow Agents - LoopAgentでExitLoopToolを使用する
  • Artifacts - アーティファクトでバイナリデータを管理する

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