내장 도구
ADK-Rust는 사용자 지정 구현 없이 에이전트 기능을 확장하는 여러 내장 도구를 제공합니다. 이 도구들은 즉시 사용할 수 있으며 에이전트 프레임워크와 원활하게 통합됩니다.
공급자 기본 도구는 이제 공급자별 GenerateContentConfig.extensions blob 대신 일반 Tool API를 통해 선언됩니다. 이는 Gemini Google Search, Anthropic Web Search 또는 OpenAI Responses 웹 검색과 같은 기본 도구를 동일한 에이전트에서 일반 FunctionTool 인스턴스와 혼합할 수 있음을 의미합니다.
개요
| 도구 | 목적 | 사용 사례 |
|---|---|---|
#[tool] macro | 제로-보일러플레이트 사용자 정의 도구 | 모든 사용자 정의 함수 — Function Tools 참조 |
FunctionTool | 수동 사용자 정의 도구 등록 | 동적 도구, 클로저 |
GoogleSearchTool | Gemini를 통한 웹 검색 | 실시간 정보 검색 |
UrlContextTool | Gemini URL grounding | 실시간 URLs 요약 또는 추론 |
GoogleMapsTool | Gemini Google Maps grounding | 장소, 경로 및 지역 컨텍스트 |
GeminiCodeExecutionTool | Gemini native code execution | 서버 측 Python 실행 |
WebSearchTool | Anthropic 네이티브 웹 검색 | Claude 서버 측 웹 검색 |
OpenAIWebSearchTool | OpenAI 응답 웹 검색 | OpenAI-호스팅 검색 |
AgentTool | Agent를 호출 가능한 Tool로 래핑 | Agent 구성 및 위임 |
ExitLoopTool | 루프 종료 | LoopAgent 반복 제어 |
LoadArtifactsTool | 아티팩트 로딩 | 저장된 이진 데이터 액세스 |
GoogleSearchTool
GoogleSearchTool는 에이전트가 Google Search를 사용하여 웹을 검색할 수 있도록 합니다. 이 도구는 grounding 기능을 통해 Gemini 모델에 의해 내부적으로 처리됩니다. 즉, 검색은 모델 자체에 의해 서버 측에서 수행됩니다.
기본 사용법
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 내에서 발생하기 때문입니다:
// 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 model에 의해 결정됨 |
| 실행 | 서버 측 (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는 모든 agent를 호출 가능한 tool로 래핑하여, 부모 agent가 tool 호출 워크플로우의 일부로 자식 agent를 호출할 수 있는 agent 구성을 가능하게 합니다. 하위 agent의 상태 변경 및 아티팩트는 자동으로 부모 컨텍스트로 전달됩니다.
기본 사용법
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()?;
작동 방식
- 부모 agent는 래핑된 agent를 tool로 호출하기로 결정합니다.
AgentTool는StreamingMode::None를 사용하여 호출 컨텍스트를 생성합니다.- 하위 agent는 완료될 때까지 실행되고 전체 응답을 축적합니다.
- 응답 텍스트는 부모 agent로 반환됩니다.
- 상태 델타 및 아티팩트 델타는 부모 컨텍스트로 전달됩니다.
Tool 세부 정보
| 속성 | 값 |
|---|---|
| 이름 | 래핑된 Agent의 이름과 동일 |
| 설명 | 래핑된 Agent의 설명과 동일 |
| 매개변수 | request: string (하위 Agent로 보낼 입력) |
| 반환 | {"response": "..."} 하위 Agent의 텍스트 출력과 함께 |
주요 동작
- 하위 에이전트는 안정적인 응답 캡처를 위해 내부적으로 비스트리밍 모드로 실행됩니다.
- 하위 에이전트의 상태 변경 (
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(())
}
작동 방식
- 에이전트는 계속할지 종료할지 평가합니다.
- 종료 준비가 되면 에이전트는
exit_loop을(를) 호출합니다. - 도구는
actions.escalate = true및actions.skip_summarization = true을(를) 설정합니다. LoopAgent는 에스컬레이트 플래그를 감지하고 반복을 중지합니다.
도구 세부 정보
| 속성 | 값 |
|---|---|
| 이름 | exit_loop |
| 설명 | "루프를 종료합니다. 지시받은 경우에만 이 함수를 호출하십시오." |
| 매개변수 | 없음 |
| 반환 | 빈 객체 {} |
모범 사례
- 명확한 종료 조건: 에이전트의 지침에 특정 조건을 정의합니다.
- 항상 max_iterations를 설정합니다: 안전 조치로 무한 루프를 방지합니다.
- 의미 있는 지침: 에이전트가 언제 종료해야 하는지 이해하도록 돕습니다.
// 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가 작동하려면 다음이 필요합니다:
- 러너에 구성된
ArtifactService - 이전에 서비스에 저장된 아티팩트
- 에이전트에 추가된 도구
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 - 사용자 지정 함수 도구 생성
- MCP Tools - MCP 서버를 도구 제공자로 사용
- Workflow Agents - ExitLoopTool를 LoopAgent와 함께 사용
- Artifacts - 아티팩트로 바이너리 데이터 관리
이전: ← Function Tools | 다음: Browser Tools →