内置工具
ADK-Rust 提供了几个内置工具,无需自定义实现即可扩展 Agent 功能。这些工具开箱即用,并与 Agent 框架无缝集成。
概述
| 工具 | 目的 | 用例 |
|---|---|---|
GoogleSearchTool | 通过 Gemini 进行网络搜索 | 实时信息检索 |
ExitLoopTool | 循环终止 | 控制 LoopAgent 迭代 |
LoadArtifactsTool | 加载 Artifact | 访问存储的二进制数据 |
GoogleSearchTool
GoogleSearchTool 使 Agent 能够使用 Google Search 搜索网络。该工具通过 Gemini 模型的 grounding 功能在内部处理,这意味着搜索是由模型本身在服务器端执行的。
基本用法
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 的工作方式有所不同:
- 服务器端执行:搜索由 Gemini 的 grounding 功能执行,而非本地
- 自动调用:模型根据查询决定何时进行搜索
- 集成结果:搜索结果直接整合到模型的响应中
如果直接调用该工具实现,它会返回一个错误,因为实际的搜索发生在 Gemini API 内部:
// 这是内部处理的 - 你不需要直接调用它
async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
Err(AdkError::Tool("GoogleSearch is handled internally by Gemini".to_string()))
}
工具详情
| 属性 | 值 |
|---|---|
| 名称 | google_search |
| 描述 | "执行 Google 搜索以从网络检索信息。" |
| 参数 | 由 Gemini 模型决定 |
| 执行 | 服务器端 (Gemini grounding) |
用例
- 时事:"今天新闻发生了什么?"
- 事实查询:"东京的人口是多少?"
- 最新信息:"AI 的最新进展是什么?"
- 研究任务:"查找有关可再生能源趋势的信息"
示例查询
// Agent 将自动使用 Google Search 处理以下查询:
// - "本周纽约的天气预报是什么?"
// - "谁赢得了最新的冠军赛?"
// - "科技公司目前的股价是多少?"
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(())
}
工作原理
- Agent 评估是继续还是退出
- 准备退出时,Agent 调用
exit_loop - 该工具设置
actions.escalate = true和actions.skip_summarization = true LoopAgent检测到 escalate 标志并停止迭代
工具详情
| 属性 | 值 |
|---|---|
| 名称 | exit_loop |
| 描述 | "退出循环。仅当您收到指示时才调用此函数。" |
| 参数 | 无 |
| 返回值 | 空对象 {} |
最佳实践
- 明确的退出标准:在 Agent 的指令中定义具体的条件
- 始终设置 max_iterations:作为安全措施防止无限循环
- 有意义的指令:帮助 Agent 理解何时退出
// 良好:明确的退出标准
.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."
)
// 避免:模糊的标准
.instruction("Improve the text. Exit when done.")
LoadArtifactsTool
LoadArtifactsTool 允许 agent 按名称检索已存储的 artifact。当 agent 需要访问先前保存的文件、图像或其他二进制数据时,这非常有用。
基本用法
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 并返回其内容。接受一个 artifact 名称数组。" |
| 参数 | artifact_names: 字符串数组 |
| 返回值 | 包含 artifacts 数组的对象 |
参数
该工具需要一个包含 artifact_names 数组的 JSON 对象:
{
"artifact_names": ["document.txt", "image.png", "data.json"]
}
响应格式
该工具返回一个包含已加载 artifact 的对象:
{
"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 工作,您需要:
- 在 runner 中配置
ArtifactService - 先前保存到 service 的 artifact
- 添加到 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 trait,以与内置工具相同的模式创建自己的工具:
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 {
"此工具功能描述"
}
async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
// 您的工具逻辑在此
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 - 将 ExitLoopTool 与 LoopAgent 结合使用
- Artifacts - 使用 artifacts 管理二进制数据
上一页:← Function Tools | 下一页:Browser Tools →