函数工具
使用自定义 Rust 函数扩展 agent 的能力。
什么是函数工具?
函数工具使 agent 能够拥有超越对话的能力——调用 API、执行计算、访问数据库或任何自定义逻辑。LLM 根据用户的请求决定何时使用工具。
主要亮点:
- 🔧 将任何 async 函数封装为可调用工具
- 📝 JSON 参数 - 灵活的输入/输出
- 🎯 类型安全 schema - 可选的 JSON Schema 验证
- 🔗 上下文访问 - 会话状态、artifact、内存
第一步:基本工具
使用 FunctionTool::new() 创建一个工具,并且始终添加 schema,以便 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 将不知道要传递什么参数,并且可能不会调用该工具。
工作原理:
- 用户询问:"东京天气如何?"
- LLM 决定使用
{"location": "Tokyo"}调用get_weather - 工具返回
{"location": "Tokyo", "temperature": "22°C", "conditions": "sunny"} - LLM 格式化响应:"东京天气晴朗,气温 22°C。"
第二步:参数处理
从 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".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"
}))
},
);
步骤 3:带 Schema 的类型化参数
对于复杂的工具,请使用带有 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>();
该 schema 是使用 schemars 从 Rust 类型自动生成的。
步骤 4:多工具 Agent
将多个工具添加到一个 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()?;
LLM 会根据用户的请求自动选择正确的工具。
错误处理
对于工具特定的错误,返回 AdkError::Tool:
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 }))
},
);
错误消息会传递给 LLM,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()- 当前用户 IDctx.session_id()- 当前会话 IDctx.agent_name()- Agent 的名称ctx.artifacts()- 访问 artifact 存储ctx.search_memory(query)- 搜索 memory 服务
长时间运行的工具
对于需要大量时间(数据处理、外部API调用)的操作,请使用非阻塞模式:
- 启动工具立即返回一个
task_id - 后台工作异步运行
- 状态工具允许用户检查进度
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>();
这会添加一个注释,以防止LlmAgent重复调用该工具。
运行示例
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
最佳实践
- 清晰的描述 - 帮助LlmAgent理解何时使用该工具
- 验证输入 - 为缺失的参数返回有用的错误消息
- 返回结构化 JSON - 使用清晰的字段名称
- 保持工具专注 - 每个工具应专注于做好一件事
- 使用 schemas - 对于复杂工具,定义参数 schemas
相关
上一页:← mistral.rs | 下一页:内置工具 →