插件
adk-plugin crate 为 agent 提供生命周期钩子系统。插件可以拦截工具调用、模型调用和执行事件,而无需修改 agent 代码——适用于日志记录、防护措施、缓存、成本跟踪和自定义中间件。
概述
插件系统围绕 EnhancedPlugin trait 构建。你只需实现所需的钩子:
- before_run / after_run — 包装整个 agent 调用
- before_tool / after_tool — 拦截工具执行(修改参数、短路执行、检查结果)
- before_model / after_model — 拦截 LLM 调用(修改请求、缓存响应)
- on_event — 观察 agent 发出的每个事件
插件按优先级顺序在管道中运行,从而支持可组合的中间件栈。
安装
[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 Trait
#[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)
}
向 Agent 注册插件
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(())
}
}