Herramientas de Función

Extienda las capacidades del agente con funciones Rust personalizadas.


¿Qué son las Herramientas de Función?

Las herramientas de función le permiten dotar a los agentes de habilidades más allá de la conversación: llamar a APIs, realizar cálculos, acceder a bases de datos o cualquier lógica personalizada. El LlmAgent decide cuándo usar una herramienta basándose en la solicitud del usuario.

Puntos clave:

  • 🔧 Envuelva cualquier función async como una herramienta invocable
  • 📝 Parámetros JSON - entrada/salida flexible
  • 🎯 Esquemas de tipo seguro - validación opcional de JSON Schema
  • 🔗 Acceso al contexto - estado de la Session, artefactos, memoria

Paso 1: Herramienta Básica

Cree una herramienta con FunctionTool::new() y siempre agregue un esquema para que el LlmAgent sepa qué parámetros pasar:

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

⚠️ Importante: Siempre use .with_parameters_schema<T>() - sin él, el LlmAgent no sabrá qué parámetros pasar y es posible que no invoque la herramienta.

Cómo funciona:

  1. El usuario pregunta: "¿Qué tiempo hace en Tokio?"
  2. El LlmAgent decide llamar a get_weather con {"location": "Tokyo"}
  3. La herramienta devuelve {"location": "Tokyo", "temperature": "22°C", "conditions": "sunny"}
  4. El LlmAgent formatea la respuesta: "El tiempo en Tokio es soleado a 22°C."

Paso 2: Manejo de Parámetros

Extraiga parámetros del args JSON:

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".into()))?;
        
        let quantity = args.get("quantity")
            .and_then(|v| v.as_i64())
            .ok_or_else(|| adk_core::AdkError::Tool("quantity is required".into()))?;
        
        // 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"
        }))
    },
);

Paso 3: Parámetros Tipados con Esquema

Para herramientas complejas, usa structs tipados con JSON Schema:

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".into())),
        };
        Ok(json!({ "result": result }))
    },
)
.with_parameters_schema::<CalculatorParams>();

El esquema se autogenera a partir de tipos Rust usando schemars.


Paso 4: Agente Multi-Herramienta

Añade múltiples herramientas a un solo Agent:

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()?;

El LLM elige automáticamente la herramienta correcta basándose en la solicitud del usuario.


Manejo de Errores

Devuelve AdkError::Tool para errores específicos de la herramienta:

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(|| adk_core::AdkError::Tool("Parameter 'a' is required".into()))?;
        let b = args.get("b").and_then(|v| v.as_f64())
            .ok_or_else(|| adk_core::AdkError::Tool("Parameter 'b' is required".into()))?;
        
        if b == 0.0 {
            return Err(adk_core::AdkError::Tool("Cannot divide by zero".into()));
        }
        
        Ok(json!({ "result": a / b }))
    },
);

Los mensajes de error se pasan al LLM, que puede reintentar o solicitar una entrada diferente.


Contexto de la Herramienta

Accede a la información de la sesión a través de 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>();

Contexto disponible:

  • ctx.user_id() - ID de usuario actual
  • ctx.session_id() - ID de sesión actual
  • ctx.agent_name() - Nombre del Agent
  • ctx.artifacts() - Acceso al almacenamiento de artefactos
  • ctx.search_memory(query) - Servicio de memoria de búsqueda

Herramientas de larga ejecución

Para operaciones que toman un tiempo significativo (procesamiento de datos, APIs externas), use el patrón no bloqueante:

  1. La herramienta de inicio retorna inmediatamente con un task_id
  2. El trabajo en segundo plano se ejecuta de forma asíncrona
  3. La herramienta de estado permite a los usuarios verificar el progreso
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>();

Puntos clave:

  • .with_long_running(true) le indica al agent que esta herramienta retorna un estado pendiente
  • La herramienta inicia el trabajo con tokio::spawn() y retorna inmediatamente
  • Proporcione una herramienta de verificación de estado para que los usuarios puedan consultar el progreso

Esto añade una nota para evitar que el LLM llame a la herramienta repetidamente.


Ejemplos de ejecución

cd official_docs_examples/tools/function_tools_test

# Basic tool with closure
cargo run --bin basic

# Tool with typed JSON schema
cargo run --bin with_schema

# Multi-tool agent (3 tools)
cargo run --bin multi_tool

# Tool context (session info)
cargo run --bin context

# Long-running tool
cargo run --bin long_running

Mejores prácticas

  1. Descripciones claras - Ayude al LLM a entender cuándo usar la herramienta
  2. Valide las entradas - Retorne mensajes de error útiles para parámetros faltantes
  3. Retorne JSON estructurado - Use nombres de campo claros
  4. Mantenga las herramientas enfocadas - Cada herramienta debe hacer una cosa bien
  5. Use schemas - Para herramientas complejas, defina schemas de parámetros

Relacionado


Anterior: ← mistral.rs | Siguiente: Herramientas integradas →