Skip to main content

AgentBuilder

Struct AgentBuilder 

Source
pub struct AgentBuilder<S: State = Empty> { /* private fields */ }
Expand description

Builds an Agent; the setters are the AgentConfig keys.

Implementations§

Source§

impl<S: State> AgentBuilder<S>

Source

pub fn model(self, value: impl Into<ModelSource>) -> AgentBuilder<SetModel<S>>
where S::Model: IsUnset,

Optional (Some / Option setters). The model the agent calls: a model instance, a ModelRouter or a Bedrock model id. Defaults to Bedrock, resolved when the agent first calls it. With a router, the agent’s model is the router’s default model.

Source

pub fn maybe_model( self, value: Option<impl Into<ModelSource>>, ) -> AgentBuilder<SetModel<S>>
where S::Model: IsUnset,

Optional (Some / Option setters). The model the agent calls: a model instance, a ModelRouter or a Bedrock model id. Defaults to Bedrock, resolved when the agent first calls it. With a router, the agent’s model is the router’s default model.

Source

pub fn aux_model( self, value: impl Into<ModelSource>, ) -> AgentBuilder<SetAuxModel<S>>
where S::AuxModel: IsUnset,

Optional (Some / Option setters). The model for auxiliary side calls (conversation-manager summaries, memory extraction, classification); defaults to model. The context manager’s summarize strategy does not use it: it resolves its own model, then model. A router is rejected: side calls run outside the loop it attaches to.

Source

pub fn maybe_aux_model( self, value: Option<impl Into<ModelSource>>, ) -> AgentBuilder<SetAuxModel<S>>
where S::AuxModel: IsUnset,

Optional (Some / Option setters). The model for auxiliary side calls (conversation-manager summaries, memory extraction, classification); defaults to model. The context manager’s summarize strategy does not use it: it resolves its own model, then model. A router is rejected: side calls run outside the loop it attaches to.

Source

pub fn messages(self, value: Vec<Message>) -> AgentBuilder<SetMessages<S>>
where S::Messages: IsUnset,

Optional (Some / Option setters). Default: <Vec<Message> as Default>::default().

Initial conversation history.

Source

pub fn maybe_messages( self, value: Option<Vec<Message>>, ) -> AgentBuilder<SetMessages<S>>
where S::Messages: IsUnset,

Optional (Some / Option setters). Default: <Vec<Message> as Default>::default().

Initial conversation history.

Source

pub fn system_prompt( self, value: impl Into<SystemPrompt>, ) -> AgentBuilder<SetSystemPrompt<S>>
where S::SystemPrompt: IsUnset,

Optional (Some / Option setters). The system prompt.

Source

pub fn maybe_system_prompt( self, value: Option<impl Into<SystemPrompt>>, ) -> AgentBuilder<SetSystemPrompt<S>>
where S::SystemPrompt: IsUnset,

Optional (Some / Option setters). The system prompt.

Source

pub fn app_state(self, value: JsonObject) -> AgentBuilder<SetAppState<S>>
where S::AppState: IsUnset,

Optional (Some / Option setters). Initial app state.

Source

pub fn maybe_app_state( self, value: Option<JsonObject>, ) -> AgentBuilder<SetAppState<S>>
where S::AppState: IsUnset,

Optional (Some / Option setters). Initial app state.

Source

pub fn model_state(self, value: JsonObject) -> AgentBuilder<SetModelState<S>>
where S::ModelState: IsUnset,

Optional (Some / Option setters). Initial model-provider state, such as a restored response id.

Source

pub fn maybe_model_state( self, value: Option<JsonObject>, ) -> AgentBuilder<SetModelState<S>>
where S::ModelState: IsUnset,

Optional (Some / Option setters). Initial model-provider state, such as a restored response id.

Source

pub fn printer(self, value: bool) -> AgentBuilder<SetPrinter<S>>
where S::Printer: IsUnset,

Optional (Some / Option setters). Print text, reasoning and tool activity to stdout as it streams. Defaults to true; turn it off in services with printer(false).

Source

pub fn maybe_printer(self, value: Option<bool>) -> AgentBuilder<SetPrinter<S>>
where S::Printer: IsUnset,

Optional (Some / Option setters). Print text, reasoning and tool activity to stdout as it streams. Defaults to true; turn it off in services with printer(false).

Source

pub fn retry_strategy( self, value: Vec<RetryStrategy>, ) -> AgentBuilder<SetRetryStrategy<S>>
where S::RetryStrategy: IsUnset,

Optional (Some / Option setters). Retry strategies for failed model calls. None installs the default DefaultModelRetryStrategy; an empty list disables retries.

Source

pub fn maybe_retry_strategy( self, value: Option<Vec<RetryStrategy>>, ) -> AgentBuilder<SetRetryStrategy<S>>
where S::RetryStrategy: IsUnset,

Optional (Some / Option setters). Retry strategies for failed model calls. None installs the default DefaultModelRetryStrategy; an empty list disables retries.

Source

pub fn structured_output_schema_json( self, value: JsonSchema, ) -> AgentBuilder<SetStructuredOutputSchema<S>>
where S::StructuredOutputSchema: IsUnset,

Optional (Some / Option setters). JSON schema the agent’s final answer must satisfy. The builder sets it from a type with structured_output_schema::<T>(), or from JSON with structured_output_schema_json(..).

Source

pub fn maybe_structured_output_schema_json( self, value: Option<JsonSchema>, ) -> AgentBuilder<SetStructuredOutputSchema<S>>
where S::StructuredOutputSchema: IsUnset,

Optional (Some / Option setters). JSON schema the agent’s final answer must satisfy. The builder sets it from a type with structured_output_schema::<T>(), or from JSON with structured_output_schema_json(..).

Source

pub fn name(self, value: impl Into<String>) -> AgentBuilder<SetName<S>>
where S::Name: IsUnset,

Optional (Some / Option setters). The agent’s name. Defaults to Strands Agent.

Source

pub fn maybe_name( self, value: Option<impl Into<String>>, ) -> AgentBuilder<SetName<S>>
where S::Name: IsUnset,

Optional (Some / Option setters). The agent’s name. Defaults to Strands Agent.

Source

pub fn description( self, value: impl Into<String>, ) -> AgentBuilder<SetDescription<S>>
where S::Description: IsUnset,

Optional (Some / Option setters). What the agent does.

Source

pub fn maybe_description( self, value: Option<impl Into<String>>, ) -> AgentBuilder<SetDescription<S>>
where S::Description: IsUnset,

Optional (Some / Option setters). What the agent does.

Source

pub fn id(self, value: impl Into<String>) -> AgentBuilder<SetId<S>>
where S::Id: IsUnset,

Optional (Some / Option setters). The agent’s id. Defaults to agent.

Source

pub fn maybe_id( self, value: Option<impl Into<String>>, ) -> AgentBuilder<SetId<S>>
where S::Id: IsUnset,

Optional (Some / Option setters). The agent’s id. Defaults to agent.

Source

pub fn sort_tools(self, value: bool) -> AgentBuilder<SetSortTools<S>>
where S::SortTools: IsUnset,

Optional (Some / Option setters). Send tool specs to the model sorted by name on every request (model calls, context summaries, token counts), to keep prompt-cache prefixes stable when the same tools are registered in a different order, for example from MCP servers (sortTools). Sorting happens before middleware, which can still reorder them. Defaults to false, which keeps registration order.

Source

pub fn maybe_sort_tools( self, value: Option<bool>, ) -> AgentBuilder<SetSortTools<S>>
where S::SortTools: IsUnset,

Optional (Some / Option setters). Send tool specs to the model sorted by name on every request (model calls, context summaries, token counts), to keep prompt-cache prefixes stable when the same tools are registered in a different order, for example from MCP servers (sortTools). Sorting happens before middleware, which can still reorder them. Defaults to false, which keeps registration order.

Source

pub fn tool_executor( self, value: impl Into<ToolExecutorStrategy>, ) -> AgentBuilder<SetToolExecutor<S>>
where S::ToolExecutor: IsUnset,

Optional (Some / Option setters). How the tool calls of one model turn run. Defaults to concurrent.

Source

pub fn maybe_tool_executor( self, value: Option<impl Into<ToolExecutorStrategy>>, ) -> AgentBuilder<SetToolExecutor<S>>
where S::ToolExecutor: IsUnset,

Optional (Some / Option setters). How the tool calls of one model turn run. Defaults to concurrent.

Source

pub fn conversation_manager( self, manager: impl ConversationManager, ) -> AgentBuilder<SetConversationManager<S>>
where S::ConversationManager: IsUnset,

Optional (Some / Option setters). Keeps the history within the context window. Defaults to a SlidingWindowConversationManager of 40 messages; a stateful model uses NullConversationManager and rejects one. The builder’s conversation_manager(..) takes a manager by value or as an Arc.

Source

pub fn maybe_conversation_manager( self, value: Option<impl ConversationManager>, ) -> AgentBuilder<SetConversationManager<S>>
where S::ConversationManager: IsUnset,

Optional (Some / Option setters). Keeps the history within the context window. Defaults to a SlidingWindowConversationManager of 40 messages; a stateful model uses NullConversationManager and rejects one. The builder’s conversation_manager(..) takes a manager by value or as an Arc.

Source

pub fn context_manager( self, value: impl Into<ContextManagerStrategy>, ) -> AgentBuilder<SetContextManager<S>>
where S::ContextManager: IsUnset,

Optional (Some / Option setters). Strategy-driven context management: a preset, a configuration, an instance, or Disabled. When set (except Disabled) it owns overflow recovery and compression, and a co-provided conversation_manager is ignored.

Source

pub fn maybe_context_manager( self, value: Option<impl Into<ContextManagerStrategy>>, ) -> AgentBuilder<SetContextManager<S>>
where S::ContextManager: IsUnset,

Optional (Some / Option setters). Strategy-driven context management: a preset, a configuration, an instance, or Disabled. When set (except Disabled) it owns overflow recovery and compression, and a co-provided conversation_manager is ignored.

Source

pub fn background_tasks( self, value: impl Into<Toggle<BackgroundTasksConfig>>, ) -> AgentBuilder<SetBackgroundTasks<S>>
where S::BackgroundTasks: IsUnset,

Optional (Some / Option setters). Background tool execution: true, a BackgroundTasksConfig, or false. Unset is off.

Source

pub fn maybe_background_tasks( self, value: Option<impl Into<Toggle<BackgroundTasksConfig>>>, ) -> AgentBuilder<SetBackgroundTasks<S>>
where S::BackgroundTasks: IsUnset,

Optional (Some / Option setters). Background tool execution: true, a BackgroundTasksConfig, or false. Unset is off.

Source

pub fn trace_attributes( self, attributes: impl IntoIterator<Item = (impl Into<String>, impl Into<AttributeValue>)>, ) -> AgentBuilder<SetTraceAttributes<S>>
where S::TraceAttributes: IsUnset,

Optional (Some / Option setters). Attributes added to every span of the agent, replacing a standard attribute of the same name. Keys other than the standard ones need the otel feature. The builder takes any iterator of key and value pairs.

Source

pub fn maybe_trace_attributes( self, value: Option<impl IntoIterator<Item = (impl Into<String>, impl Into<AttributeValue>)>>, ) -> AgentBuilder<SetTraceAttributes<S>>
where S::TraceAttributes: IsUnset,

Optional (Some / Option setters). Attributes added to every span of the agent, replacing a standard attribute of the same name. Keys other than the standard ones need the otel feature. The builder takes any iterator of key and value pairs.

Source

pub fn baggage_attributes( self, entries: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>, ) -> AgentBuilder<SetBaggageAttributes<S>>
where S::BaggageAttributes: IsUnset,

Optional (Some / Option setters). OpenTelemetry baggage entries attached to the context for every invocation, propagated to downstream services in the W3C baggage header; needs the otel feature. The builder takes any iterator of key and value pairs.

Source

pub fn maybe_baggage_attributes( self, value: Option<impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>>, ) -> AgentBuilder<SetBaggageAttributes<S>>
where S::BaggageAttributes: IsUnset,

Optional (Some / Option setters). OpenTelemetry baggage entries attached to the context for every invocation, propagated to downstream services in the W3C baggage header; needs the otel feature. The builder takes any iterator of key and value pairs.

Source

pub fn sandbox(self, sandbox: impl IntoSandbox) -> AgentBuilder<SetSandbox<S>>
where S::Sandbox: IsUnset,

Optional (Some / Option setters). Where sandbox-aware tools run commands and code and read and write files (sandbox). None uses the shared NotASandboxLocalEnvironment, the host with no isolation. A configured sandbox’s get_tools are registered at initialization, except those whose name is already registered. The builder’s sandbox(..) takes a sandbox by value or as an Arc.

Source

pub fn maybe_sandbox( self, value: Option<impl IntoSandbox>, ) -> AgentBuilder<SetSandbox<S>>
where S::Sandbox: IsUnset,

Optional (Some / Option setters). Where sandbox-aware tools run commands and code and read and write files (sandbox). None uses the shared NotASandboxLocalEnvironment, the host with no isolation. A configured sandbox’s get_tools are registered at initialization, except those whose name is already registered. The builder’s sandbox(..) takes a sandbox by value or as an Arc.

Source

pub fn storage(self, storage: impl IntoStorage) -> AgentBuilder<SetStorage<S>>
where S::Storage: IsUnset,

Optional (Some / Option setters). Default storage backend for agent subsystems (storage). Subsystems without their own storage (the session manager, the context manager’s archive) resolve from it, each under its own namespace; a subsystem’s own storage always wins. The builder’s storage(..) takes a storage by value or as an Arc.

Source

pub fn maybe_storage( self, value: Option<impl IntoStorage>, ) -> AgentBuilder<SetStorage<S>>
where S::Storage: IsUnset,

Optional (Some / Option setters). Default storage backend for agent subsystems (storage). Subsystems without their own storage (the session manager, the context manager’s archive) resolve from it, each under its own namespace; a subsystem’s own storage always wins. The builder’s storage(..) takes a storage by value or as an Arc.

Source

pub fn session_manager( self, value: SessionManager, ) -> AgentBuilder<SetSessionManager<S>>
where S::SessionManager: IsUnset,

Optional (Some / Option setters). Saves and restores the agent’s session. With one attached, the agent’s session id is the manager’s and the model receives it in its AgentMetadata.

Source

pub fn maybe_session_manager( self, value: Option<SessionManager>, ) -> AgentBuilder<SetSessionManager<S>>
where S::SessionManager: IsUnset,

Optional (Some / Option setters). Saves and restores the agent’s session. With one attached, the agent’s session id is the manager’s and the model receives it in its AgentMetadata.

Source

pub fn memory_manager( self, value: impl Into<MemoryManagerSource>, ) -> AgentBuilder<SetMemoryManager<S>>
where S::MemoryManager: IsUnset,

Optional (Some / Option setters). Cross-session memory: a MemoryManager or a MemoryManagerConfig the agent builds one from.

Source

pub fn maybe_memory_manager( self, value: Option<impl Into<MemoryManagerSource>>, ) -> AgentBuilder<SetMemoryManager<S>>
where S::MemoryManager: IsUnset,

Optional (Some / Option setters). Cross-session memory: a MemoryManager or a MemoryManagerConfig the agent builds one from.

Source§

impl<S: State> AgentBuilder<S>

Source

pub fn tools( self, tools: impl IntoIterator<Item = impl Into<ToolSource>>, ) -> Self

Adds tools: any iterator of tools, agents, Arc<dyn Tool>s or nested lists (tools). Mixed types go through tool_list!.

Source

pub fn plugins(self, plugins: impl IntoIterator<Item = impl Plugin>) -> Self

Adds plugins, by value or as Arcs (plugins).

Source

pub fn interventions( self, handlers: impl IntoIterator<Item = impl InterventionHandler>, ) -> Self

Adds intervention handlers of one type, by value or as Arcs (interventions). Add handlers of different types with intervention, one at a time, or as a list of Arc<dyn InterventionHandler>:

use std::sync::Arc;

use strands::Agent;
use strands::interventions::InterventionHandler;
use strands::testing::MockModel;
use strands::vended_interventions::hitl::{HumanInTheLoop, HumanInTheLoopConfig};

struct Audit;

#[strands::async_trait]
impl InterventionHandler for Audit {
    fn name(&self) -> &str {
        "audit"
    }
}

let one_by_one = Agent::builder()
    .model(MockModel::new())
    .intervention(HumanInTheLoop::default())
    .intervention(Audit)
    .printer(false)
    .build()?;
let shared: [Arc<dyn InterventionHandler>; 2] = [Arc::new(HumanInTheLoop::default()), Arc::new(Audit)];
let listed = Agent::builder().model(MockModel::new()).interventions(shared).printer(false).build()?;
Source

pub fn intervention(self, handler: impl InterventionHandler) -> Self

Adds one intervention handler, by value or as an Arc (an Arc<dyn InterventionHandler> included), after the ones already added.

Source

pub fn structured_output_schema<T: SchemarsJsonSchema>( self, ) -> AgentBuilder<SetStructuredOutputSchema<S>>
where S::StructuredOutputSchema: IsUnset,

Sets the structured output schema from a type’s schemars schema; needs schemars = "1" in your dependencies.

Source§

impl<S: IsComplete> AgentBuilder<S>

Source

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

Builds the agent.

§Errors

The same errors as Agent::new.

Auto Trait Implementations§

§

impl<S = Empty> !RefUnwindSafe for AgentBuilder<S>

§

impl<S = Empty> !UnwindSafe for AgentBuilder<S>

§

impl<S> Freeze for AgentBuilder<S>

§

impl<S> Send for AgentBuilder<S>

§

impl<S> Sync for AgentBuilder<S>

§

impl<S> Unpin for AgentBuilder<S>

§

impl<S> UnsafeUnpin for AgentBuilder<S>

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
§

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

§

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.

§

impl<T> FutureExt for T

§

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

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

fn with_current_context(self) -> WithContext<Self> ⓘ

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

impl<T> Instrument for T

§

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

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

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
§

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

§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
§

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + 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
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + 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
§

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

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

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

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