関数ツール

カスタム Rust 関数でエージェントの機能を拡張します。


関数ツールとは?

関数ツールを使うと、エージェントに会話以上の能力を与えられます。たとえば、APIs の呼び出し、計算の実行、データベースへのアクセス、その他任意のカスタムロジックなどです。LLM は、ユーザーのリクエストに基づいてツールを使うタイミングを判断します。

主なポイント:

  • 🚀 #[tool] マクロ - ボイラープレートなしでツールを登録(推奨)
  • 🔧 FunctionTool::new() - 任意の async 関数を手動でラップ
  • 📝 JSON パラメータ - 柔軟な入出力
  • 🎯 型安全なスキーマ - schemars による型からの自動 JSON Schema
  • 🔗 コンテキストアクセス - セッション状態、アーティファクト、メモリ

ツール実行パイプライン

Rendering architecture…

ツールを作成する最も速い方法です。このマクロは、doc コメントを説明として読み取り、引数型から JSON スキーマを導出します。

use adk_tool::tool;
use adk_core::AdkError;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{json, Value};

#[derive(Deserialize, JsonSchema)]
struct WeatherArgs {
    /// The city to look up
    city: String,
    /// Temperature unit (celsius or fahrenheit)
    unit: Option<String>,
}

/// Get the current weather for a city.
#[tool]
async fn get_weather(args: WeatherArgs) -> Result<Value, AdkError> {
    Ok(json!({ "temp": 22, "city": args.city }))
}

// Generated: pub struct GetWeather; — implements adk_core::Tool
// Use it: agent_builder.tool(Arc::new(GetWeather))

ツールにセッションコンテキストが必要な場合は、最初のパラメータとして Arc<dyn ToolContext> を追加します。

use adk_core::ToolContext;
use std::sync::Arc;

/// Search the user's saved documents.
#[tool]
async fn search_docs(
    ctx: Arc<dyn ToolContext>,
    args: SearchArgs,
) -> Result<Value, AdkError> {
    let user_id = ctx.user_id();
    // ... use context for scoped access
}

ツールのメタデータ属性

マクロ内で、ツールを読み取り専用、並行実行安全、または長時間実行として直接指定できます。

/// Look up cached data — no side effects, safe for parallel dispatch.
#[tool(read_only, concurrency_safe)]
async fn cache_lookup(args: LookupArgs) -> Result<Value, AdkError> {
    Ok(json!({"result": "cached"}))
}

/// Start a long-running background report.
#[tool(long_running)]
async fn generate_report(args: ReportArgs) -> Result<Value, AdkError> {
    Ok(json!({"task_id": "abc123", "status": "processing"}))
}

利用可能な属性(すべて任意で、自由に組み合わせ可能):

属性効果
read_onlyis_read_only() → true — 並行Autoディスパッチに必要な 2 つのシグナルのうちの 1 つ
concurrency_safeis_concurrency_safe() → true — 並行Autoディスパッチに必要な 2 つのシグナルのうちの 1 つ
long_runningis_long_running() → true — 保留中のツールを再呼び出しすることを LLM が防ぎます

Plain #[tool] に属性がない場合は既定値(すべて false)が保持されるため、既存のコードに影響はありません。


代替: FunctionTool::new()

動的なツールや明示的な登録を好む場合は、次のようにします:

FunctionTool::new() でツールを作成し、必ずスキーマを追加して、LLM が渡すべきパラメータを把握できるようにします:

use adk_rust::prelude::*;
use adk_rust::Launcher;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::sync::Arc;

#[derive(JsonSchema, Serialize, Deserialize)]
struct WeatherParams {
    /// The city or location to get weather for
    location: String,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    dotenvy::dotenv().ok();
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;

    // Weather tool with proper schema
    let weather_tool = FunctionTool::new(
        "get_weather",
        "Get current weather for a location",
        |_ctx, args| async move {
            let location = args.get("location")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown");
            Ok(json!({
                "location": location,
                "temperature": "22°C",
                "conditions": "sunny"
            }))
        },
    )
    .with_parameters_schema::<WeatherParams>(); // Required for LLM to call correctly!

    let agent = LlmAgentBuilder::new("weather_agent")
        .instruction("You help users check the weather. Always use the get_weather tool.")
        .model(Arc::new(model))
        .tool(Arc::new(weather_tool))
        .build()?;

    Launcher::new(Arc::new(agent)).run().await?;
    Ok(())
}

⚠️ 重要: 必ず .with_parameters_schema<T>() を使ってください。これがないと、LLM は渡すべきパラメータを把握できず、ツールを呼び出さない可能性があります。

動作の仕組み:

  1. ユーザーが「東京の天気は?」と尋ねる
  2. LLM が get_weather{"location": "Tokyo"} 付きで呼び出すと判断する
  3. ツールが {"location": "Tokyo", "temperature": "22°C", "conditions": "sunny"} を返す
  4. LLM が応答を整形する: 「東京の天気は22°Cで晴れです。」

ステップ 2: パラメータの処理

JSON args からパラメータを抽出します:

let order_tool = FunctionTool::new(
    "process_order",
    "Process an order. Parameters: product_id (required), quantity (required), priority (optional)",
    |_ctx, args| async move {
        // Required parameters - return error if missing
        let product_id = args.get("product_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| adk_core::AdkError::tool("product_id is required"))?;
        
        let quantity = args.get("quantity")
            .and_then(|v| v.as_i64())
            .ok_or_else(|| adk_core::AdkError::tool("quantity is required"))?;
        
        // Optional parameter with default
        let priority = args.get("priority")
            .and_then(|v| v.as_str())
            .unwrap_or("normal");
        
        Ok(json!({
            "order_id": "ORD-12345",
            "product_id": product_id,
            "quantity": quantity,
            "priority": priority,
            "status": "confirmed"
        }))
    },
);

ステップ 3: スキーマ付きの型付きパラメータ

複雑なツールでは、JSON Schema を持つ型付き struct を使用します:

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(JsonSchema, Serialize, Deserialize)]
struct CalculatorParams {
    /// The arithmetic operation to perform
    operation: Operation,
    /// First operand
    a: f64,
    /// Second operand
    b: f64,
}

#[derive(JsonSchema, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Operation {
    Add,
    Subtract,
    Multiply,
    Divide,
}

let calculator = FunctionTool::new(
    "calculator",
    "Perform arithmetic operations",
    |_ctx, args| async move {
        let params: CalculatorParams = serde_json::from_value(args)?;
        let result = match params.operation {
            Operation::Add => params.a + params.b,
            Operation::Subtract => params.a - params.b,
            Operation::Multiply => params.a * params.b,
            Operation::Divide if params.b != 0.0 => params.a / params.b,
            Operation::Divide => return Err(adk_core::AdkError::tool("Cannot divide by zero")),
        };
        Ok(json!({ "result": result }))
    },
)
.with_parameters_schema::<CalculatorParams>();

スキーマは schemars を使って Rust の型から自動生成されます。


ステップ 4: マルチツールエージェント

1つのエージェントに複数のツールを追加します:

let agent = LlmAgentBuilder::new("assistant")
    .instruction("Help with calculations, conversions, and weather.")
    .model(Arc::new(model))
    .tool(Arc::new(calc_tool))
    .tool(Arc::new(convert_tool))
    .tool(Arc::new(weather_tool))
    .build()?;

LLM は、ユーザーの要求に基づいて自動的に適切なツールを選択します。


エラーハンドリング

ツール固有の失敗には、Tool コンポーネントを使ってエラーを返します:

use adk_core::{AdkError, ErrorComponent, ErrorCategory};

let divide_tool = FunctionTool::new(
    "divide",
    "Divide two numbers",
    |_ctx, args| async move {
        let a = args.get("a").and_then(|v| v.as_f64())
            .ok_or_else(|| AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.divide.missing_param",
                "Parameter 'a' is required",
            ))?;
        let b = args.get("b").and_then(|v| v.as_f64())
            .ok_or_else(|| AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.divide.missing_param",
                "Parameter 'b' is required",
            ))?;
        
        if b == 0.0 {
            return Err(AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.divide.division_by_zero",
                "Cannot divide by zero",
            ));
        }
        
        Ok(json!({ "result": a / b }))
    },
);

素早く移行する場合は、後方互換性のある省略形も使えます:

Err(AdkError::tool("Parameter 'a' is required"))

エラーメッセージは LLM に渡され、再試行したり別の入力を求めたりできます。


ツールコンテキスト

ToolContext を介してセッション情報にアクセスします:

#[derive(JsonSchema, Serialize, Deserialize)]
struct GreetParams {
    #[serde(default)]
    message: Option<String>,
}

let greet_tool = FunctionTool::new(
    "greet",
    "Greet the user with session info",
    |ctx, _args| async move {
        let user_id = ctx.user_id();
        let session_id = ctx.session_id();
        let agent_name = ctx.agent_name();
        Ok(json!({
            "greeting": format!("Hello, user {}!", user_id),
            "session": session_id,
            "served_by": agent_name
        }))
    },
)
.with_parameters_schema::<GreetParams>();

利用可能なコンテキスト:

  • ctx.user_id() - 現在のユーザー ID
  • ctx.session_id() - 現在のセッション ID
  • ctx.agent_name() - エージェント名
  • ctx.artifacts() - アーティファクトストレージへのアクセス
  • ctx.search_memory(query) - メモリサービスの検索

長時間実行されるツール

データ処理や外部 APIs のように時間のかかる操作には、ノンブロッキングパターンを使用します:

  1. ツールの開始 は task_id を返してすぐに戻る
  2. バックグラウンド作業 は非同期に実行される
  3. ステータスツール でユーザーが進捗を確認できる
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(JsonSchema, Serialize, Deserialize)]
struct ReportParams {
    topic: String,
}

#[derive(JsonSchema, Serialize, Deserialize)]
struct StatusParams {
    task_id: String,
}

// Shared task store
let tasks: Arc<RwLock<HashMap<String, TaskState>>> = Arc::new(RwLock::new(HashMap::new()));
let tasks1 = tasks.clone();
let tasks2 = tasks.clone();

// Tool 1: Start (returns immediately)
let start_tool = FunctionTool::new(
    "generate_report",
    "Start generating a report. Returns task_id immediately.",
    move |_ctx, args| {
        let tasks = tasks1.clone();
        async move {
            let topic = args.get("topic").and_then(|v| v.as_str()).unwrap_or("general").to_string();
            let task_id = format!("task_{}", rand::random::<u32>());
            
            // Store initial state
            tasks.write().await.insert(task_id.clone(), TaskState {
                status: "processing".to_string(),
                progress: 0,
                result: None,
            });

            // Spawn background work (non-blocking!)
            let tasks_bg = tasks.clone();
            let tid = task_id.clone();
            tokio::spawn(async move {
                // Simulate work...
                tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
                if let Some(t) = tasks_bg.write().await.get_mut(&tid) {
                    t.status = "completed".to_string();
                    t.result = Some("Report complete".to_string());
                }
            });

            // Return immediately with task_id
            Ok(json!({"task_id": task_id, "status": "processing"}))
        }
    },
)
.with_parameters_schema::<ReportParams>()
.with_long_running(true);  // Mark as long-running

// Tool 2: Check status
let status_tool = FunctionTool::new(
    "check_report_status",
    "Check report generation status",
    move |_ctx, args| {
        let tasks = tasks2.clone();
        async move {
            let task_id = args.get("task_id").and_then(|v| v.as_str()).unwrap_or("");
            if let Some(t) = tasks.read().await.get(task_id) {
                Ok(json!({"status": t.status, "result": t.result}))
            } else {
                Ok(json!({"error": "Task not found"}))
            }
        }
    },
)
.with_parameters_schema::<StatusParams>();

要点:

  • .with_long_running(true) は、このツールが保留中ステータスを返すことをエージェントに伝えます
  • ツールは tokio::spawn() で作業を起動し、すぐに戻ります
  • ユーザーが進捗をポーリングできるように、ステータス確認ツールを用意します

これにより、LLM がツールを繰り返し呼び出すのを防ぐための注記が追加されます。


ツールからの進捗ストリーミング

長時間実行されるツールは、実行中であっても中間出力を UI に送信できるため、ユーザーはシェルコマンドの stdout、ビルドログ、またはダウンロードのバイトを最終結果を待たずにリアルタイムで確認できます。出力が届いたら ToolContext::emit_progress を呼び出します:

use adk_core::{Result, Tool, ToolContext};
use std::sync::Arc;

#[async_trait::async_trait]
impl Tool for BuildTool {
    // ... name(), description(), parameters_schema() ...

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: serde_json::Value) -> Result<serde_json::Value> {
        // Emit chunks as they arrive — each becomes a partial Event on the
        // agent's EventStream, the SAME stream the model's reply travels on.
        ctx.emit_progress("stdout", "Compiling project...\n").await;
        ctx.emit_progress("stdout", "Build finished in 4.2s\n").await;
        ctx.emit_progress("stderr", "warning: unused variable `x`\n").await;

        // The final return value is still the complete result the model consumes.
        Ok(serde_json::json!({ "status": "ok", "warnings": 1 }))
    }
}

シグネチャ:

async fn emit_progress(&self, stream: &str, chunk: &str)
  • stream — チャンクのラベル: "stdout""stderr"、または任意のカスタムチャネル。
  • chunk — 出力するテキスト(ターミナル風の出力では行ごとに出力します)。

UI への到達方法。フレームワークは各チャンクをエージェントの EventStream 上の部分的な Event として転送します。コンシューマーは event.tool_progress_stream() でそれを検出し、リアルタイムで描画します。第二のチャネルもログのスクレイピングもありません。進捗、モデルのテキスト、そして最終的なツール結果はすべて、1つの順序付けされたストリームで届きます。

後方互換性。既定の emit_progress は no-op なので、ストリーミングしない既存のツールやランナーには影響しません。進捗を出力するのは opt in したツールだけであり、それを観測するのは tool_progress_stream() を確認するコンシューマーだけです。

進捗は上限付きで損失ありです。ツールは、クライアントが消費するより速く出力を生成できます。たとえばコンパイラのログ、シェルコマンド、暴走ループなどです。そのためフレームワークは、無制限に増大させるのではなく、保持して転送する量に上限を設けます:

制限超過時の動作
ツールバッチごとのキュー深さ256 イベントツールは空きができるまで最大 100 ms 待機し、その後チャンクは破棄されます
チャンクあたりのバイト数8 KiBチャンクは文字境界で切り詰められます
ツール呼び出しごとのバイト数1 MiB残りの進捗は転送されません

出力が何らかの理由で取り下げられると、その呼び出しに対してテキスト [adk: tool progress truncated] を含む progress イベントがちょうど 1 つ送出されるため、ギャップは常に静かにではなく可視化されます。したがって、遅い consumer は tool を一時的に遅くしますが、無期限に停止させたりメモリを使い果たしたりすることはありません。

これらの制限は progress にのみ適用されます。tool の最終結果には影響しないため、必要なら大きな結果は tool 内で切り詰めてください。

完全な web UI の例については streaming_bash を参照してください。この UI は、1 つの event feed から live な bash output と 1 回限りの tool result(read_filegrepglob)をレンダリングします。streaming bash tool 自体は adk-devtools にあります。


実行例

cargo adk new tool_agent --template tools
cd tool_agent
cargo run

ベストプラクティス

  1. 明確な説明 - LLM が tool をいつ使うべきか理解できるようにする
  2. 入力を検証する - パラメータ不足時に役立つエラーメッセージを返す
  3. 構造化された JSON を返す - わかりやすいフィールド名を使う
  4. tool の役割を絞る - 各 tool は 1 つのことをうまく行うべき
  5. スキーマを使う - 複雑な tool では、パラメータスキーマを定義する
  6. 安全な読み取り専用 tool にマークする - .with_read_only(true).with_concurrency_safe(true) の両方を設定して、Auto dispatch がそれらを concurrent subset に含められるようにする

Tool Metadata: 読み取り専用と並行実行

より賢い dispatch を可能にするため、tool を読み取り専用または concurrency-safe としてマークします。

// A lookup tool that performs no side effects
let lookup = FunctionTool::new("lookup", "Look up data", |_ctx, args| async move {
    Ok(json!({"result": "cached data"}))
})
.with_read_only(true)
.with_concurrency_safe(true); // Auto mode requires both signals

// A mutation tool (defaults: read_only=false, concurrency_safe=false)
let update = FunctionTool::new("update", "Update record", |_ctx, args| async move {
    Ok(json!({"updated": true}))
});

ToolExecutionStrategy::Auto が有効な場合、dispatch loop はまず、選択された tool が trueis_read_only()is_concurrency_safe() の両方から返す呼び出しを並行に実行します。次に、残りのすべての呼び出しを順次実行します。ToolExecutionStrategy::Parallel はこれらのシグナルをバイパスする明示的な override であり、その呼び出し元が concurrency safety を担います。


SimpleToolContext: エージェントループ外で tool を使う

エージェントループの外で tool を呼び出す必要がある場合(テスト、MCP server mode、sub-agent delegation など)は、完全な ToolContext trait hierarchy を実装する代わりに SimpleToolContext を使ってください。

use adk_tool::SimpleToolContext;
use adk_core::ToolContext;
use std::sync::Arc;

// Construct with just a caller name — all other fields get sensible defaults
let ctx = SimpleToolContext::new("my-test-harness");

// Optionally override the function call ID
let ctx = SimpleToolContext::new("my-mcp-server")
    .with_function_call_id("custom-call-id");

// Bind a session ID so session-aware tools (and MCP servers that key state by
// session) see a stable identifier instead of the empty default.
let ctx = SimpleToolContext::new("my-mcp-server")
    .with_session_id("session-42");

// Use it to execute any tool
let tool_ctx: Arc<dyn ToolContext> = Arc::new(ctx);
let result = my_tool.execute(tool_ctx, json!({"key": "value"})).await?;

デフォルト: user_id()"anonymous"session_id() / branch()""artifacts()Nonesearch_memory() → 空の vec。invocation_idfunction_call_id の両方が自動生成された UUIDs です。tool がセッションごとに state をルーティングまたは永続化する場合は、with_session_id(...) で実際の session を設定してください。


StatefulTool: 呼び出し間で共有される state

呼び出し間で state を維持する必要がある tool(カウンタ、キャッシュ、connection pool など)には、StatefulTool<S> を使ってください。

use adk_tool::StatefulTool;
use adk_core::ToolContext;
use std::sync::Arc;
use tokio::sync::RwLock;

struct AppCache {
    entries: RwLock<HashMap<String, String>>,
}

let cache = Arc::new(AppCache {
    entries: RwLock::new(HashMap::new()),
});

let cache_tool = StatefulTool::new(
    "cache_lookup",
    "Look up a value in the application cache",
    cache.clone(),
    |state, _ctx, args| async move {
        let key = args["key"].as_str().unwrap_or("");
        let entries = state.entries.read().await;
        let value = entries.get(key).cloned().unwrap_or_default();
        Ok(json!({"key": key, "value": value}))
    },
)
.with_read_only(true)
.with_concurrency_safe(true);

StatefulTool は各呼び出し時に Arc<S> を clone します(安価な参照カウントの増分)ので、すべての実行が同じ underlying state を共有します。FunctionTool と同じ builder methods をサポートします: with_long_runningwith_parameters_schemawith_response_schemawith_scopeswith_read_only、および with_concurrency_safe


  • Built-in Tools - 事前構築済みの tool(GoogleSearch、ExitLoop)
  • MCP Tools - Model Context Protocol 統合
  • LlmAgent - agent に tool を追加する

マルチモーダルな関数レスポンス

Gemini 3 models は、関数レスポンスで images、audio、PDFs、および file references を受け取ることをサポートしています。JSON だけではありません。tool は、inline_data および/または file_data 配列をその JSON return value に含めることで、multimodal data を返せます。

/// Tool that returns a chart image alongside JSON metadata.
async fn generate_chart(
    _ctx: Arc<dyn ToolContext>,
    args: serde_json::Value,
) -> Result<serde_json::Value> {
    let png_bytes: Vec<u8> = render_chart(&args);

    // Include inline_data in the return value — the framework extracts it automatically
    Ok(json!({
        "response": {
            "title": "Q4 Sales",
            "chart_type": "bar"
        },
        "inline_data": [{
            "mime_type": "image/png",
            "data": png_bytes
        }]
    }))
}

framework は自動的に次を行います:

  1. inline_data/file_dataFunctionResponseData::from_tool_result() により検出する
  2. inline binary data を Base64 エンコードする
  3. part を functionResponse wire object 内にネストする(Gemini 3 の API format に一致)

File References

外部に保存された大きな file には、bytes を埋め込む代わりに URI を使って file_data を使用してください。

Ok(json!({
    "response": { "document_id": "report-2024", "pages": 12 },
    "file_data": [{
        "mime_type": "application/pdf",
        "file_uri": "gs://my-bucket/reports/report-2024.pdf"
    }]
}))

直接構築

framework-level code(custom agents、conversion layers)では、FunctionResponseData を直接構築します。

use adk_core::{FunctionResponseData, InlineDataPart, FileDataPart};

// JSON + inline image
let frd = FunctionResponseData::with_inline_data(
    "chart_tool",
    json!({"title": "Q4 Chart"}),
    vec![InlineDataPart { mime_type: "image/png".into(), data: png_bytes }],
);

// JSON + file reference
let frd = FunctionResponseData::with_file_data(
    "doc_tool",
    json!({"status": "ok"}),
    vec![FileDataPart { mime_type: "application/pdf".into(), file_uri: "gs://bucket/file.pdf".into() }],
);

// JSON + both
let frd = FunctionResponseData::with_multimodal("tool", json, inline_parts, file_parts);

: Multimodal function responses には Gemini 3 series models(gemini-3-flash-previewgemini-3-pro-preview)が必要です。以前の models は 400 error を返します。

完全に動作する例については examples/multimodal_function_response/ を参照してください。


: ← mistral.rs | : Built-in Tools →