플러그인
adk-plugin 크레이트는 에이전트를 위한 수명 주기 훅 시스템을 제공합니다. 플러그인은 에이전트 코드를 수정하지 않고도 도구 호출, 모델 호출 및 실행 이벤트를 가로챕니다. 로깅, 가드레일, 캐싱, 비용 추적 및 사용자 지정 미들웨어에 유용합니다.
개요
플러그인 시스템은 EnhancedPlugin 트레이트를 중심으로 구축되었습니다. 필요한 훅만 구현하면 됩니다.
- before_run / after_run — 전체 에이전트 호출을 래핑
- before_tool / after_tool — 도구 실행 가로채기(인수 수정, 조기 반환, 결과 검사)
- before_model / after_model — LLM 호출 가로채기(요청 수정, 응답 캐싱)
- on_event — 에이전트가 생성하는 모든 이벤트 관찰
플러그인은 우선순위에 따라 정렬된 파이프라인에서 실행되므로, 조합 가능한 미들웨어 스택을 구성할 수 있습니다.
설치
[dependencies]
adk-plugin = "2.1.0"
# Or via umbrella crate (included in standard tier)
adk-rust = { version = "2.1.0", features = ["standard"] }
빠른 시작
use adk_plugin::{EnhancedPlugin, PluginContext, ToolCallInfo, ToolResultInfo};
use adk_core::{Content, Result};
use async_trait::async_trait;
use serde_json::Value;
struct LoggingPlugin;
#[async_trait]
impl EnhancedPlugin for LoggingPlugin {
fn name(&self) -> &str { "logging" }
fn priority(&self) -> i32 { 0 }
async fn before_tool(
&self,
ctx: &PluginContext,
tool_call: &mut ToolCallInfo,
) -> Result<Option<Value>> {
tracing::info!(
tool = tool_call.name,
args = %tool_call.args,
"tool call started"
);
Ok(None) // Continue to actual tool execution
}
async fn after_tool(
&self,
ctx: &PluginContext,
tool_result: &mut ToolResultInfo,
) -> Result<()> {
tracing::info!(
tool = tool_result.name,
duration_ms = tool_result.duration_ms,
"tool call completed"
);
Ok(())
}
}
EnhancedPlugin 트레이트
#[async_trait]
pub trait EnhancedPlugin: Send + Sync {
/// Unique plugin identifier
fn name(&self) -> &str;
/// Execution order (lower = runs first) [default: 0]
fn priority(&self) -> i32 { 0 }
/// Called before agent execution starts
async fn before_run(&self, ctx: &PluginContext) -> Result<()> { Ok(()) }
/// Called after agent execution completes
async fn after_run(&self, ctx: &PluginContext) -> Result<()> { Ok(()) }
/// Called before each tool execution.
/// Return Some(value) to short-circuit (skip tool, return this value).
/// Return None to continue with normal execution.
async fn before_tool(
&self,
ctx: &PluginContext,
tool_call: &mut ToolCallInfo,
) -> Result<Option<Value>> { Ok(None) }
/// Called after each tool execution.
/// Can modify the result before it's returned to the LLM.
async fn after_tool(
&self,
ctx: &PluginContext,
tool_result: &mut ToolResultInfo,
) -> Result<()> { Ok(()) }
/// Called before each model (LLM) call.
/// Can modify the request or short-circuit with a cached response.
async fn before_model(
&self,
ctx: &PluginContext,
request: &mut ModelCallInfo,
) -> Result<Option<Content>> { Ok(None) }
/// Called after each model call.
/// Can modify the response before it's processed.
async fn after_model(
&self,
ctx: &PluginContext,
response: &mut ModelResultInfo,
) -> Result<()> { Ok(()) }
/// Called for every event emitted during execution.
async fn on_event(
&self,
ctx: &PluginContext,
event: &Event,
) -> Result<()> { Ok(()) }
}
도구 호출 가로채기
인수 수정
실행 전에 도구 인수를 수정합니다.
async fn before_tool(
&self,
ctx: &PluginContext,
tool_call: &mut ToolCallInfo,
) -> Result<Option<Value>> {
// Inject default values
if tool_call.name == "search" {
if tool_call.args.get("limit").is_none() {
tool_call.args["limit"] = serde_json::json!(10);
}
}
Ok(None) // Continue to tool execution
}
조기 반환(도구 실행 건너뛰기)
도구를 호출하지 않고 값을 직접 반환합니다.
async fn before_tool(
&self,
ctx: &PluginContext,
tool_call: &mut ToolCallInfo,
) -> Result<Option<Value>> {
// Check cache
let cache_key = format!("{}:{}", tool_call.name, tool_call.args);
if let Some(cached) = self.cache.get(&cache_key).await {
return Ok(Some(cached)); // Short-circuit: return cached result
}
Ok(None) // Cache miss: proceed with tool execution
}
결과 수정
실행 후 도구 결과를 수정합니다.
async fn after_tool(
&self,
ctx: &PluginContext,
tool_result: &mut ToolResultInfo,
) -> Result<()> {
// Redact sensitive data from results
if let Some(obj) = tool_result.result.as_object_mut() {
if obj.contains_key("ssn") {
obj.insert("ssn".into(), serde_json::json!("***-**-****"));
}
}
Ok(())
}
모델 호출 가로채기
요청 수정
전송하기 전에 LLM 요청을 수정합니다.
async fn before_model(
&self,
ctx: &PluginContext,
request: &mut ModelCallInfo,
) -> Result<Option<Content>> {
// Add system context to every request
if let Some(ref mut instruction) = request.system_instruction {
instruction.push_str("\nAlways respond in JSON format.");
}
Ok(None)
}
응답 캐싱
async fn before_model(
&self,
ctx: &PluginContext,
request: &mut ModelCallInfo,
) -> Result<Option<Content>> {
let key = self.hash_request(request);
if let Some(cached) = self.cache.get(&key).await {
return Ok(Some(cached)); // Return cached response
}
Ok(None)
}
async fn after_model(
&self,
ctx: &PluginContext,
response: &mut ModelResultInfo,
) -> Result<()> {
// Cache the response for future calls
let key = self.hash_request(&response.original_request);
self.cache.set(&key, response.content.clone()).await;
Ok(())
}
우선순위 기반 파이프라인
플러그인은 우선순위 순서로 실행됩니다(숫자가 낮을수록 먼저 실행).
struct AuthPlugin;
impl EnhancedPlugin for AuthPlugin {
fn name(&self) -> &str { "auth" }
fn priority(&self) -> i32 { -10 } // Runs first
// ...
}
struct LogPlugin;
impl EnhancedPlugin for LogPlugin {
fn name(&self) -> &str { "log" }
fn priority(&self) -> i32 { 0 } // Runs second
// ...
}
struct CachePlugin;
impl EnhancedPlugin for CachePlugin {
fn name(&self) -> &str { "cache" }
fn priority(&self) -> i32 { 10 } // Runs last
// ...
}
before_* 훅의 경우 플러그인은 가장 낮은 우선순위부터 실행됩니다. after_* 훅의 경우에는 역순으로 실행되며(가장 높은 우선순위부터), 중첩된 미들웨어 패턴을 형성합니다.
PluginContext — 공유 상태
PluginContext는 호출 중 모든 플러그인에서 액세스할 수 있는 공유 상태를 제공합니다.
use adk_plugin::PluginContext;
async fn before_tool(
&self,
ctx: &PluginContext,
tool_call: &mut ToolCallInfo,
) -> Result<Option<Value>> {
// Read shared state
let call_count: u64 = ctx.get("tool_call_count").unwrap_or(0);
// Write shared state
ctx.set("tool_call_count", call_count + 1);
// Access invocation metadata
let user_id = ctx.user_id();
let session_id = ctx.session_id();
let agent_name = ctx.agent_name();
Ok(None)
}
에이전트에 플러그인 등록
use adk_agent::LlmAgentBuilder;
use std::sync::Arc;
let agent = LlmAgentBuilder::new("my_agent")
.model(model)
.instruction("You are a helpful assistant.")
.tool(Arc::new(my_tool))
.plugin(Arc::new(LoggingPlugin))
.plugin(Arc::new(CachePlugin::new(cache_store)))
.plugin(Arc::new(CostTrackingPlugin::new()))
.build()?;
예시: 비용 추적 플러그인
use adk_plugin::{EnhancedPlugin, PluginContext, ModelResultInfo};
use adk_core::Result;
use std::sync::atomic::{AtomicU64, Ordering};
struct CostPlugin {
total_tokens: AtomicU64,
}
#[async_trait]
impl EnhancedPlugin for CostPlugin {
fn name(&self) -> &str { "cost_tracker" }
fn priority(&self) -> i32 { 100 }
async fn after_model(
&self,
ctx: &PluginContext,
response: &mut ModelResultInfo,
) -> Result<()> {
if let Some(usage) = &response.usage {
let tokens = usage.prompt_tokens + usage.completion_tokens;
self.total_tokens.fetch_add(tokens as u64, Ordering::Relaxed);
tracing::info!(
total_tokens = self.total_tokens.load(Ordering::Relaxed),
"token usage updated"
);
}
Ok(())
}
}
관련 항목
- 재시도 및 반영 — 도구 실패 복구를 위한 기본 제공 플러그인
- 가드레일 — 입력/출력 검증 플러그인
- 텔레메트리 — 관측성 통합
- 콜백 — 일반적인 경우를 위한 더 간단한 후크 시스템