내장 Tool

adk-rust는 사용자 정의 구현 없이 Agent의 기능을 확장하는 여러 내장 Tool을 제공합니다. 이 Tool들은 즉시 사용할 수 있으며 Agent 프레임워크와 원활하게 통합됩니다.

개요

Tool목적사용 사례
GoogleSearchToolGemini를 통한 웹 검색실시간 정보 검색
ExitLoopTool루프 종료LoopAgent 반복 제어
LoadArtifactsToolArtifact 로딩저장된 바이너리 데이터 액세스

GoogleSearchTool

GoogleSearchTool은 Agent가 Google 검색을 사용하여 웹을 검색할 수 있도록 합니다. 이 Tool은 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은 다르게 작동합니다.

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

실제 검색은 Gemini API 내에서 발생하므로, 이 Tool 구현은 직접 호출될 경우 오류를 반환합니다.

// 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".to_string()))
}

Tool 세부 정보

속성
이름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?"

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

    // 반복적인 개선을 위해 ExitLoopTool을 가진 에이전트 생성
    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()?;

    // LoopAgent에서 사용
    let loop_agent = LoopAgent::new(
        "iterative_refiner",
        vec![Arc::new(refiner)],
    ).with_max_iterations(5);

    println!("루프 에이전트가 종료 기능과 함께 생성되었습니다!");
    Ok(())
}

작동 방식

  1. Agent는 계속할지 종료할지 평가합니다.
  2. 종료할 준비가 되면 Agentexit_loop를 호출합니다.
  3. Toolactions.escalate = trueactions.skip_summarization = true를 설정합니다.
  4. LoopAgentescalate 플래그를 감지하고 반복을 중지합니다.

도구 세부 정보

속성
이름exit_loop
설명"루프를 종료합니다. 지시를 받았을 때만 이 함수를 호출하십시오."
매개변수없음
반환빈 객체 {}

모범 사례

  1. 명확한 종료 기준: Agentinstruction에 특정 조건을 정의하십시오.
  2. 항상 max_iterations 설정: 안전 조치로 무한 루프를 방지하십시오.
  3. 의미 있는 instruction: 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")?;

    // artifact 로딩 기능을 가진 agent 생성
    let agent = LlmAgentBuilder::new("document_analyzer")
        .description("저장된 문서를 분석합니다")
        .instruction(
            "저장된 artifact를 로드하고 분석할 수 있습니다. \
             load_artifacts tool을 사용하여 이름으로 문서를 검색하십시오. \
             이 tool은 artifact 이름 배열을 허용합니다."
        )
        .model(Arc::new(model))
        .tool(Arc::new(LoadArtifactsTool::new()))
        .build()?;

    println!("artifact 로딩 기능을 가진 agent가 생성되었습니다!");
    Ok(())
}

Tool 상세 정보

속성
이름load_artifacts
설명"이름으로 artifact를 로드하고 그 내용을 반환합니다. artifact 이름 배열을 허용합니다."
매개변수artifact_names: 문자열 배열
반환artifacts 배열을 포함하는 객체

매개변수

이 tool은 artifact_names 배열을 가진 JSON 객체를 기대합니다:

{
  "artifact_names": ["document.txt", "image.png", "data.json"]
}

응답 형식

이 tool은 로드된 artifact를 포함하는 객체를 반환합니다:

{
  "artifacts": [
    {
      "name": "document.txt",
      "content": "문서의 텍스트 내용..."
    },
    {
      "name": "image.png",
      "content": {
        "mime_type": "image/png",
        "data": "base64-encoded-data..."
      }
    },
    {
      "name": "missing.txt",
      "error": "artifact를 찾을 수 없습니다"
    }
  ]
}

요구사항

LoadArtifactsTool가 작동하려면 다음이 필요합니다:

  1. runner에 구성된 ArtifactService
  2. 서비스에 이전에 저장된 artifact
  3. agent에 추가된 tool
use adk_rust::prelude::*;
use std::sync::Arc;

// artifact service 설정
let artifact_service = Arc::new(InMemoryArtifactService::new());

// artifact service로 runner 구성
let runner = Runner::new(agent)
    .with_artifact_service(artifact_service);

내장 Tool 결합하기

여러 내장 tool을 함께 사용할 수 있습니다:

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

    // 여러 내장 tool을 가진 agent 생성
    let agent = LlmAgentBuilder::new("research_agent")
        .description("검색 및 artifact 기능을 갖춘 리서치 agent")
        .instruction(
            "당신은 리서치 agent입니다. 다음을 수행할 수 있습니다:\n\
             - google_search를 사용하여 최신 정보를 웹에서 검색\n\
             - load_artifacts를 사용하여 저장된 문서 로드\n\
             이 tool들을 사용하여 질문에 포괄적으로 답변하는 데 도움을 주십시오."
        )
        .model(Arc::new(model))
        .tool(Arc::new(GoogleSearchTool))
        .tool(Arc::new(LoadArtifactsTool::new()))
        .build()?;

    println!("다중 tool agent가 생성되었습니다!");
    Ok(())
}

사용자 지정 내장 Tool 생성

Tool 트레이트를 구현하여 내장 Tool과 동일한 패턴으로 자신만의 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 {
    /// 새로운 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 서버를 Tool 제공자로 사용하기
  • Workflow Agents - LoopAgent와 함께 ExitLoopTool 사용하기
  • Artifacts - Artifact를 사용하여 이진 데이터 관리하기

이전: ← Function Tools | 다음: Browser Tools →