Skip to main content

LlmAgentBuilder

Struct LlmAgentBuilder 

Source
pub struct LlmAgentBuilder { /* private fields */ }
Expand description

Builder for constructing an LlmAgent with all configuration options.

Implementations§

Source§

impl LlmAgentBuilder

Source

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

Create a new builder with the given agent name.

Source

pub fn description(self, desc: impl Into<String>) -> Self

Set the agent description.

Source

pub fn model(self, model: Arc<dyn Llm>) -> Self

Set the LLM model for this agent.

Source

pub fn instruction(self, instruction: impl Into<String>) -> Self

Set the system instruction for this agent.

Source

pub fn instruction_provider(self, provider: InstructionProvider) -> Self

Set a dynamic instruction provider evaluated per invocation.

Source

pub fn global_instruction(self, instruction: impl Into<String>) -> Self

Set a global instruction prepended to all requests.

Source

pub fn global_instruction_provider( self, provider: GlobalInstructionProvider, ) -> Self

Set a dynamic global instruction provider evaluated per invocation.

Source

pub fn with_skills(self, index: SkillIndex) -> Self

Set a preloaded skills index for this agent.

The best matching skill is injected into the current user turn so stable instructions and conversation history remain available for prompt caching.

Source

pub fn with_auto_skills(self) -> Result<Self>

Auto-load skills from .skills/ in the current working directory.

Source

pub fn with_skills_from_root(self, root: impl AsRef<Path>) -> Result<Self>

Auto-load skills from .skills/ under a custom root directory.

Source

pub fn with_skill_policy(self, policy: SelectionPolicy) -> Self

Customize skill selection behavior.

Source

pub fn with_skill_budget(self, max_chars: usize) -> Self

Limit injected skill content length.

Source

pub fn input_schema(self, schema: Value) -> Self

Set a JSON schema for validating user input.

Source

pub fn output_schema(self, schema: Value) -> Self

Set a JSON schema for structured output from the LLM.

Source

pub fn output_type<T: JsonSchema>(self) -> Self

Derive the output schema from a Rust type using schemars.

This is a convenience method that generates a JSON Schema from T’s JsonSchema implementation and sets it as the output schema.

§Example
use schemars::JsonSchema;
use serde::Deserialize;

#[derive(JsonSchema, Deserialize)]
struct MyOutput {
    name: String,
    score: f64,
}

let agent = LlmAgentBuilder::new("my-agent")
    .model(model)
    .output_type::<MyOutput>()
    .build()?;
Source

pub fn output_max_retries(self, n: usize) -> Self

Set the maximum number of retry attempts for output schema validation.

When the LLM produces output that fails schema validation, the agent will retry up to this many times with a correction prompt. Default is 3.

Source

pub fn disallow_transfer_to_parent(self, disallow: bool) -> Self

Prevent this agent from transferring control back to its parent.

Source

pub fn disallow_transfer_to_peers(self, disallow: bool) -> Self

Prevent this agent from transferring control to peer agents.

Source

pub fn include_contents(self, include: IncludeContents) -> Self

Control which conversation history contents are included in LLM requests.

Source

pub fn output_key(self, key: impl Into<String>) -> Self

Set a state key where the agent’s final output will be stored.

Source

pub fn generate_content_config(self, config: GenerateContentConfig) -> Self

Set default generation parameters (temperature, top_p, top_k, max_output_tokens) applied to every LLM request made by this agent.

These defaults are merged with any per-request config. If output_schema is also set, the schema is preserved alongside these generation parameters.

§Example
use adk_core::GenerateContentConfig;

let agent = LlmAgentBuilder::new("my-agent")
    .model(model)
    .generate_content_config(GenerateContentConfig {
        temperature: Some(0.7),
        max_output_tokens: Some(2048),
        ..Default::default()
    })
    .build()?;
Source

pub fn temperature(self, temperature: f32) -> Self

Set the default temperature for LLM requests. Shorthand for setting just temperature without a full GenerateContentConfig.

Source

pub fn top_p(self, top_p: f32) -> Self

Set the default top_p for LLM requests.

Source

pub fn top_k(self, top_k: i32) -> Self

Set the default top_k for LLM requests.

Source

pub fn max_output_tokens(self, max_tokens: i32) -> Self

Set the default max output tokens for LLM requests.

Source

pub fn max_iterations(self, max: u32) -> Self

Set the maximum number of LLM round-trips (iterations) before the agent stops. Default is 100.

Source

pub fn tool_timeout(self, timeout: Duration) -> Self

Set the timeout for individual tool executions. Default is 5 minutes. Tools that exceed this timeout will return an error.

Source

pub fn tool(self, tool: Arc<dyn Tool>) -> Self

Add a tool to this agent’s toolbox.

Source

pub fn toolset(self, toolset: Arc<dyn Toolset>) -> Self

Register a dynamic toolset for per-invocation tool resolution.

Toolsets are resolved at the start of each run() call using the invocation’s ReadonlyContext. This enables context-dependent tools like per-user browser sessions from a pool.

Source

pub fn sub_agent(self, agent: Arc<dyn Agent>) -> Self

Add a sub-agent that this agent can delegate to.

Source

pub fn before_callback(self, callback: BeforeAgentCallback) -> Self

Add a before-agent callback.

Source

pub fn after_callback(self, callback: AfterAgentCallback) -> Self

Add an after-agent callback.

Source

pub fn before_model_callback(self, callback: BeforeModelCallback) -> Self

Add a before-model callback invoked before each LLM request.

Source

pub fn after_model_callback(self, callback: AfterModelCallback) -> Self

Add an after-model callback invoked after each LLM response.

Source

pub fn before_tool_callback(self, callback: BeforeToolCallback) -> Self

Add a before-tool callback invoked before each tool execution.

Source

pub fn after_tool_callback(self, callback: AfterToolCallback) -> Self

Add an after-tool callback invoked after each tool execution.

Source

pub fn after_tool_callback_full(self, callback: AfterToolCallbackFull) -> Self

Register a rich after-tool callback that receives the tool, arguments, and response value.

This is the V2 callback surface aligned with the Python/Go ADK model where after_tool_callback receives the full tool execution context. Unlike after_tool_callback (which only receives CallbackContext), this callback can inspect and modify tool results directly.

Return Ok(None) to keep the original response, or Ok(Some(value)) to replace the function response sent to the LLM.

These callbacks run after the legacy after_tool_callback chain. ToolOutcome is available via ctx.tool_outcome().

Source

pub fn on_tool_error(self, callback: OnToolErrorCallback) -> Self

Register a callback invoked when a tool execution fails (after retries are exhausted).

If the callback returns Ok(Some(value)), the value is used as a fallback function response to the LLM. If it returns Ok(None), the next callback in the chain is tried. If no callback provides a fallback, the original error is reported to the LLM.

Source

pub fn default_retry_budget(self, budget: RetryBudget) -> Self

Set a default retry budget applied to all tools that do not have a per-tool override.

When a tool execution fails and a retry budget applies, the agent retries up to budget.max_retries times with the configured delay between attempts.

Source

pub fn tool_retry_budget( self, tool_name: impl Into<String>, budget: RetryBudget, ) -> Self

Set a per-tool retry budget that overrides the default for the named tool.

Per-tool budgets take precedence over the default retry budget.

Source

pub fn circuit_breaker_threshold(self, threshold: u32) -> Self

Configure a circuit breaker that temporarily disables tools after threshold consecutive failures within a single invocation.

When a tool’s consecutive failure count reaches the threshold, subsequent calls to that tool are short-circuited with an immediate error response until the next invocation (which resets the state).

Source

pub fn tool_confirmation_policy(self, policy: ToolConfirmationPolicy) -> Self

Configure tool confirmation requirements for this agent.

Source

pub fn require_tool_confirmation(self, tool_name: impl Into<String>) -> Self

Require confirmation for a specific tool name.

Source

pub fn require_tool_confirmation_for_all(self) -> Self

Require confirmation for all tool calls.

Source

pub fn tool_execution_strategy(self, strategy: ToolExecutionStrategy) -> Self

Set the tool execution strategy for this agent.

When set, this overrides the RunConfig’s tool_execution_strategy for this agent’s dispatch loop. When None (the default), the RunConfig value is used. ToolExecutionStrategy::Parallel is an explicit override that bypasses tool safety metadata, so the caller owns concurrency safety.

Source

pub fn input_guardrails(self, guardrails: GuardrailSet) -> Self

Set input guardrails to validate user input before processing.

Input guardrails run before the agent processes the request and can:

  • Block harmful or off-topic content
  • Redact PII from user input
  • Enforce input length limits

Requires the guardrails feature.

Source

pub fn output_guardrails(self, guardrails: GuardrailSet) -> Self

Set output guardrails to validate agent responses.

Output guardrails run after the agent generates a response and can:

  • Enforce JSON schema compliance
  • Redact PII from responses
  • Block harmful content in responses

Requires the guardrails feature.

Source

pub fn tool_guardrails(self, guardrails: ToolGuardrailSet) -> Self

Set guardrails that screen tool calls before they execute.

GuardrailSet validates Content and never sees a tool call, and ToolConfirmationPolicy decides per tool name. Neither can express “this tool may run, but not with these arguments”. A ToolGuardrailSet receives the tool name and the arguments and may allow, deny, or narrow them.

Screening runs before the tool executes and before confirmation is resolved, so a denied call neither prompts the user nor consumes a concurrency permit. A denial is reported to the model as the tool’s result, letting it correct the call rather than stalling the run.

Requires the guardrails feature.

§Example
use adk_agent::guardrails::{PathAllowList, ToolGuardrailSet};

let agent = LlmAgentBuilder::new("ops")
    .tool_guardrails(ToolGuardrailSet::new().with(
        PathAllowList::new("agents-only", ["path"], ["/Users/me/Library/LaunchAgents"])
            .on_tools(["plist_write"]),
    ))
    .build()?;
Source

pub fn build(self) -> Result<LlmAgent>

Build the LlmAgent, returning an error if no model was set.

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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 = !

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<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