Skip to main content

PluginBuilder

Struct PluginBuilder 

Source
pub struct PluginBuilder { /* private fields */ }
Available on crate feature plugin only.
Expand description

Builder for creating plugins with a fluent API.

PluginBuilder provides a chainable interface for constructing Plugin instances without manually filling out a PluginConfig struct. Each method configures a single lifecycle callback, and build produces the final Plugin.

§End-to-End Example

use adk_plugin::PluginBuilder;
use std::sync::Arc;

let plugin = PluginBuilder::new("audit-trail")
    .before_agent(Box::new(|ctx| {
        Box::pin(async move {
            tracing::info!("agent starting");
            Ok(())
        })
    }))
    .after_agent(Box::new(|ctx| {
        Box::pin(async move {
            tracing::info!("agent finished");
            Ok(())
        })
    }))
    .before_tool(Box::new(|ctx| {
        Box::pin(async move {
            if let Some(name) = ctx.tool_name() {
                tracing::info!(tool = name, "tool invoked");
            }
            Ok(())
        })
    }))
    .after_tool(Box::new(|ctx| {
        Box::pin(async move {
            tracing::info!("tool completed");
            Ok(())
        })
    }))
    .before_model(Box::new(|ctx, request| {
        Box::pin(async move {
            tracing::debug!(model = ?request.model, "sending request to model");
            Ok(request)
        })
    }))
    .after_model(Box::new(|ctx, response| {
        Box::pin(async move {
            tracing::debug!("model responded");
            Ok(None)
        })
    }))
    .close_fn(|| Box::pin(async { tracing::info!("plugin closed") }))
    .build();

assert_eq!(plugin.name(), "audit-trail");

Implementations§

Source§

impl PluginBuilder

Source

pub fn new(name: impl Into<String>) -> PluginBuilder

Create a new plugin builder with the given name.

The name uniquely identifies this plugin within a PluginManager.

let builder = PluginBuilder::new("my-plugin");
Source

pub fn on_user_message( self, callback: Box<dyn Fn(Arc<dyn InvocationContext>, Content) -> Pin<Box<dyn Future<Output = Result<Option<Content>, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked when a user message is received.

The callback can inspect or modify the incoming Content. Return Ok(Some(content)) to replace the message, or Ok(None) to keep the original.

builder.on_user_message(Box::new(|ctx, content| {
    Box::pin(async move {
        tracing::info!(role = %content.role, "user message received");
        Ok(None) // pass through unchanged
    })
}))
Source

pub fn on_event( self, callback: Box<dyn Fn(Arc<dyn InvocationContext>, Event) -> Pin<Box<dyn Future<Output = Result<Option<Event>, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked for each event generated by the agent.

The callback can inspect or modify Event objects before they are yielded to the caller. Return Ok(Some(event)) to replace the event, or Ok(None) to keep the original.

builder.on_event(Box::new(|ctx, event| {
    Box::pin(async move {
        tracing::debug!(id = %event.id, "event emitted");
        Ok(None)
    })
}))
Source

pub fn before_run( self, callback: Box<dyn Fn(Arc<dyn InvocationContext>) -> Pin<Box<dyn Future<Output = Result<Option<Content>, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked before the agent run starts.

Use this for setup, validation, or early exit. Return Ok(Some(content)) to skip the run entirely and return that content, or Ok(None) to proceed normally.

builder.before_run(Box::new(|ctx| {
    Box::pin(async move {
        tracing::info!("run starting");
        Ok(None) // continue with the run
    })
}))
Source

pub fn after_run( self, callback: Box<dyn Fn(Arc<dyn InvocationContext>) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked after the agent run completes.

Use this for cleanup, logging, or metrics collection. This callback is for side effects only and does not emit events.

builder.after_run(Box::new(|ctx| {
    Box::pin(async move {
        tracing::info!("run completed");
    })
}))
Source

pub fn before_agent( self, callback: Box<dyn Fn(Arc<dyn CallbackContext>) -> Pin<Box<dyn Future<Output = Result<Option<Content>, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked before agent execution.

Runs each time an agent is about to execute. Useful for tracing, permission checks, or injecting state.

builder.before_agent(Box::new(|ctx| {
    Box::pin(async move {
        tracing::info!("agent starting");
        Ok(())
    })
}))
Source

pub fn after_agent( self, callback: Box<dyn Fn(Arc<dyn CallbackContext>) -> Pin<Box<dyn Future<Output = Result<Option<Content>, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked after agent execution.

Runs each time an agent finishes. Useful for logging duration, collecting metrics, or post-processing results.

builder.after_agent(Box::new(|ctx| {
    Box::pin(async move {
        tracing::info!("agent finished");
        Ok(())
    })
}))
Source

pub fn before_model( self, callback: Box<dyn Fn(Arc<dyn CallbackContext>, LlmRequest) -> Pin<Box<dyn Future<Output = Result<BeforeModelResult, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked before an LLM call.

The callback receives the LlmRequest and can modify it or skip the call entirely by returning a pre-built response.

builder.before_model(Box::new(|ctx, request| {
    Box::pin(async move {
        tracing::debug!(model = ?request.model, "calling model");
        Ok(request) // pass through unchanged
    })
}))
Source

pub fn after_model( self, callback: Box<dyn Fn(Arc<dyn CallbackContext>, LlmResponse) -> Pin<Box<dyn Future<Output = Result<Option<LlmResponse>, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked after an LLM call.

The callback receives the LlmResponse and can modify or replace it. Return Ok(Some(response)) to replace, or Ok(None) to keep the original.

builder.after_model(Box::new(|ctx, response| {
    Box::pin(async move {
        tracing::debug!("model responded");
        Ok(None) // keep original response
    })
}))
Source

pub fn on_model_error( self, callback: Box<dyn Fn(Arc<dyn CallbackContext>, LlmRequest, String) -> Pin<Box<dyn Future<Output = Result<Option<LlmResponse>, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked when an LLM call returns an error.

The callback receives the original LlmRequest and the error message. Return Ok(Some(response)) to provide a fallback response, or Ok(None) to propagate the error.

builder.on_model_error(Box::new(|ctx, request, error| {
    Box::pin(async move {
        tracing::warn!(error = %error, "model error, no fallback");
        Ok(None) // propagate the error
    })
}))
Source

pub fn before_tool( self, callback: Box<dyn Fn(Arc<dyn CallbackContext>) -> Pin<Box<dyn Future<Output = Result<Option<Content>, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked before tool execution.

Runs each time a tool is about to execute. The CallbackContext provides tool_name() and tool_input() for tool-specific logic.

builder.before_tool(Box::new(|ctx| {
    Box::pin(async move {
        if let Some(name) = ctx.tool_name() {
            tracing::info!(tool = name, "tool starting");
        }
        Ok(())
    })
}))
Source

pub fn after_tool( self, callback: Box<dyn Fn(Arc<dyn CallbackContext>) -> Pin<Box<dyn Future<Output = Result<Option<Content>, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked after tool execution.

Runs each time a tool finishes. Useful for logging results, collecting metrics, or auditing tool usage.

builder.after_tool(Box::new(|ctx| {
    Box::pin(async move {
        tracing::info!("tool completed");
        Ok(())
    })
}))
Source

pub fn on_tool_error( self, callback: Box<dyn Fn(Arc<dyn CallbackContext>, Arc<dyn Tool>, Value, String) -> Pin<Box<dyn Future<Output = Result<Option<Value>, AdkError>> + Send>> + Send + Sync>, ) -> PluginBuilder

Set the callback invoked when a tool returns an error.

The callback receives the tool name, the error, and the CallbackContext. Use this to log failures or provide fallback values.

builder.on_tool_error(Box::new(|ctx, tool_name, error| {
    Box::pin(async move {
        tracing::warn!(tool = %tool_name, error = %error, "tool failed");
        Ok(None) // propagate the error
    })
}))
Source

pub fn close_fn( self, f: impl Fn() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync + 'static, ) -> PluginBuilder

Set the async cleanup function called when the plugin is closed.

Use this to release resources, flush buffers, or perform final cleanup.

builder.close_fn(|| Box::pin(async {
    tracing::info!("plugin shutting down");
}))
Source

pub fn build(self) -> Plugin

Consume the builder and produce a Plugin.

Only callbacks that were explicitly set will be active; all others remain None.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more