기본 제공 도구

ADK-Rust는 사용자 지정 구현 없이 에이전트 기능을 확장할 수 있는 여러 기본 제공 도구를 제공합니다. 이러한 도구는 별도의 설정 없이 바로 사용할 수 있으며 에이전트 프레임워크와 원활하게 통합됩니다.

이제 제공업체 기본 도구는 제공업체별 GenerateContentConfig.extensions 블롭 대신 일반 Tool API를 통해 선언됩니다. 따라서 동일한 에이전트에서 Gemini Google Search, Anthropic Web Search 또는 OpenAI Responses 웹 검색과 같은 네이티브 도구를 일반 FunctionTool 인스턴스와 함께 사용할 수 있습니다.

개요

도구목적사용 사례
#[tool] 매크로상용구 없는 사용자 지정 도구모든 사용자 지정 함수 — 함수 도구 참조
FunctionTool사용자 지정 도구 수동 등록동적 도구, 클로저
GoogleSearchToolGemini를 통한 웹 검색실시간 정보 검색
UrlContextToolGemini URL 그라운딩실시간 URLs에 대한 요약 또는 추론
GoogleMapsToolGemini Google Maps 그라운딩장소, 경로 및 현지 맥락
GeminiCodeExecutionToolGemini 네이티브 코드 실행서버 측 Python 실행
WebSearchToolAnthropic 네이티브 웹 검색Claude 서버 측 웹 검색
OpenAIWebSearchToolOpenAI 응답 웹 검색OpenAI 호스팅 검색
AgentTool에이전트를 호출 가능한 도구로 래핑에이전트 구성 및 위임
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-3.7-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(())
}

작동 방식

일반적인 함수 도구와 달리 GoogleSearchTool은 다음과 같이 작동합니다.

  1. 서버 측 실행: 검색은 로컬이 아니라 Gemini의 grounding 기능을 통해 수행됩니다.
  2. 자동 호출: 모델은 쿼리에 따라 검색할 시점을 결정합니다.
  3. 통합된 결과: 검색 결과는 모델의 응답에 직접 통합됩니다.

실제 검색은 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 모델에 의해 결정됨
실행서버 측 (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는 모든 에이전트를 호출 가능한 도구로 래핑하여 위임 후 반환 구성을 지원합니다. 호출자는 자식 에이전트를 호출하고 그 결과를 받은 다음 실행을 재개합니다. 자식이 생성한 상태 및 아티팩트 델타는 부모 도구 이벤트에 병합됩니다. 자식 세션은 각 이벤트를 즉시 적용하므로, 위임된 워크플로의 이후 단계에서는 이전 상태/기록 변경 사항을 확인할 수 있습니다.

레거시 기본값은 계속 격리되며 이전 버전과의 호환성을 유지합니다. 이식 가능한 팀은 부모 기록/상태 스냅샷, 메모리 전달, 전파된 실패, 유한한 위임 깊이, 정확한 상태/기록 프로젝션, 등록된 자식 핸드오프의 내부 실행을 선택적으로 활성화합니다. 소비된 자식 핸드오프는 이벤트로 계속 표시되지만, 전달하기 전에 전송 동작이 제거되므로 부모 Runner가 이를 두 번 실행할 수 없습니다. 요청 메타데이터, 취소, 스코프, 시크릿, 아티팩트 및 병렬 공유 상태는 구성된 전달 정책을 따릅니다. AgentTool 자체는 Runner의 전역 핸드오프 루프를 실행하지 않습니다. 컴파일된 TeamSpec가 혼합 토폴로지에 필요한 정확한 중첩 핸드오프 레지스트리를 제공합니다. 컴파일된 팀은 중첩 이벤트 전달도 선택적으로 활성화하므로 위임된 활동이 부모 이벤트 스트림에 계속 표시됩니다. 독립 실행형 AgentTool는 forward_events(true)이 선택되지 않는 한 레거시 이벤트 출력을 유지합니다.

제어된 write-back을 위해 입력 state_keys projection과 독립적으로 output_state_keys을 사용합니다. state_merge_policy(RejectConflicts)은 현재 부모 값과 위임이 시작될 때 생성된 스냅샷을 비교하고 충돌하는 쓰기를 원자적으로 거부합니다. artifact_prefixes은 동일한 allowlist 원칙을 artifact 이름에 적용합니다. 독립 실행형 기본값은 하위 호환성을 위해 여전히 last-writer-wins 방식으로 제한 없이 출력을 허용하며, 컴파일된 팀은 정확한 edge 정책을 선택적으로 활성화합니다.

기본 사용법

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

작동 방식

  1. 부모 agent가 래핑된 agent를 tool로 호출하기로 결정합니다
  2. AgentTool이 StreamingMode::None를 사용하여 invocation context를 생성합니다
  3. 하위 agent가 실행을 완료하고 전체 response를 누적합니다
  4. response text가 부모 agent에 반환됩니다
  5. state delta와 artifact delta가 부모 context로 전달됩니다

Tool 세부 정보

속성값
이름래핑된 에이전트의 이름과 동일
설명래핑된 에이전트의 설명과 동일
매개변수request: 문자열 (하위 에이전트에 보낼 입력)
반환값{"response": "..."} 및 하위 에이전트의 텍스트 출력

주요 동작

  • 하위 에이전트는 안정적인 응답 캡처를 위해 내부적으로 비스트리밍 모드로 실행됩니다
  • 하위 에이전트의 상태 변경(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-3.7-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(())
}

작동 방식

  1. 에이전트가 계속 진행할지 종료할지 평가합니다
  2. 종료할 준비가 되면 에이전트가 exit_loop를 호출합니다
  3. 도구가 actions.escalate = true 및 actions.skip_summarization = true을 설정합니다
  4. LoopAgent가 에스컬레이션 플래그를 감지하고 반복을 중지합니다

도구 세부 정보

속성값
이름exit_loop
설명"루프를 종료합니다. 지시받은 경우에만 이 함수를 호출하세요."
매개변수없음
반환값빈 객체 {}

모범 사례

  1. 명확한 종료 기준: 에이전트의 지침에 구체적인 조건을 정의합니다.
  2. 항상 max_iterations 설정: 안전 조치로 무한 루프를 방지합니다.
  3. 의미 있는 지침: 에이전트가 종료 시점을 이해하도록 돕습니다.
// 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-3.7-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가 작동하려면 다음이 필요합니다:

  1. 러너에 구성된 ArtifactService
  2. 서비스에 이전에 저장된 아티팩트
  3. 에이전트에 추가된 도구
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-3.7-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;
}

이전: ← 함수 도구 | 다음: 브라우저 도구 →

기본 제공 도구 - ADK-Rust 문서 | ADK-Rust