Skip to main content

Agent

Struct Agent 

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

An agent: a model, tools and a conversation, run by the agent loop (Agent).

The agent is owned and its calls take &mut self, so invoking an agent while an invocation runs is a compile error. Share one across tasks with Arc<tokio::sync::Mutex<Agent>>.

use strands::Agent;
use strands::testing::MockModel;

let mut agent = Agent::builder()
    .model(MockModel::new().with_turn("Hello!"))
    .system_prompt("You are a concise assistant.")
    .printer(false)
    .build()?;
let result = agent.invoke("Hi").await?;
assert_eq!(result.to_string(), "Hello!");
assert_eq!(agent.messages().len(), 2);

Implementations§

Source§

impl Agent

Source

pub fn builder() -> AgentBuilder

Starts an agent builder; its setters are the AgentConfig keys.

use strands::Agent;
use strands::testing::MockModel;

let agent = Agent::builder()
    .model(MockModel::new())
    .name("researcher")
    .printer(false)
    .build()?;
assert_eq!(agent.name(), "researcher");
Source

pub fn new(config: AgentConfig) -> Result<Self>

Creates an agent from its configuration (new Agent(config)).

Without a model the agent uses the default Bedrock model, resolved when the agent first calls it.

§Errors

A tool name that is invalid or registered twice, a Bedrock model id without the bedrock feature, or a structured output schema that does not compile when first used.

Source

pub async fn invoke( &mut self, args: impl Into<InvokeArgs>, ) -> Result<AgentResult>

Invokes the agent and returns the final result (invoke); it drains stream.

§Errors

A model error that no retry resolved, a structured output failure, a hook error, a bad resume input, or an invalid limit. An agent stopped for interrupts accepts only the responses: invoke it with a Vec<InterruptResponse>.

Source

pub async fn invoke_with( &mut self, args: impl Into<InvokeArgs>, options: InvokeOptions, ) -> Result<AgentResult>

Invokes the agent with per-invocation options.

§Errors

The same as invoke.

Source

pub fn stream(&mut self, args: impl Into<InvokeArgs>) -> AgentStream<'_>

Streams the invocation (stream): the loop runs as the stream is polled and yields the event records, ending with AgentStreamEvent::AgentResult.

History is always re-invokable: an assistant message with tool uses is appended only after its tools finish. Dropping the stream early cancels the invocation.

Source

pub fn stream_with( &mut self, args: impl Into<InvokeArgs>, options: InvokeOptions, ) -> AgentStream<'_>

Streams the invocation with per-invocation options.

Source

pub async fn initialize(&mut self) -> Result<()>

Initializes the agent’s plugins and fires InitializedEvent (initialize). The first invocation calls it; calling it again does nothing. When a dropped stream cuts it short, the next call continues where it stopped: with the plugin it interrupted, and with the InitializedEvent callbacks that have not run. When an InitializedEvent callback fails, the next call fires every callback again.

§Errors

A plugin that failed to initialize (later calls fail with the same message), or an InitializedEvent hook error.

Source

pub async fn shutdown(&mut self) -> Result<()>

Runs the agent’s shutdown procedures (shutdown): the cleanup a dropped stream left pending, then cancels the background tasks that have not finished (dropping the agent cancels them too) and flushes the memory manager. Safe to call more than once.

§Errors

None today; cleanup hook errors are logged. The memory manager’s flush logs its store failures.

Source

pub fn memory_manager(&self) -> Option<&MemoryManager>

The memory manager, if one is configured.

Source

pub fn take_snapshot( &self, options: impl Into<TakeSnapshotOptions>, ) -> Result<Snapshot>

Captures a point-in-time snapshot of the agent’s state.

use strands::{Agent, SnapshotField, TakeSnapshotOptions};
use strands::testing::MockModel;

let agent = Agent::builder().model(MockModel::new()).printer(false).build()?;
let snapshot = agent.take_snapshot(TakeSnapshotOptions::session())?;
assert!(snapshot.data.contains_key("messages"));

let partial = agent.take_snapshot(TakeSnapshotOptions {
    include: vec![SnapshotField::Messages, SnapshotField::State],
    ..Default::default()
})?;
assert_eq!(partial.data.len(), 2);
§Errors

When the options select no field, or a value fails to serialize.

Source

pub fn load_snapshot(&mut self, snapshot: &Snapshot) -> Result<()>

Restores the agent’s state from a snapshot. Only the fields present in snapshot.data are restored; the others stay as they are.

§Errors

A snapshot of another scope or schema version, data that does not decode, or background tasks still tracked.

Source

pub fn local(&self) -> &LocalAgent

The agent’s view as sequential hooks see it.

Source

pub fn local_mut(&mut self) -> &mut LocalAgent

The agent’s view as sequential hooks see it, mutably.

Source

pub fn id(&self) -> &str

The agent’s id (id).

Source

pub fn name(&self) -> &str

The agent’s name (name).

Source

pub fn description(&self) -> Option<&str>

What the agent does (description).

Source

pub fn session_id(&self) -> &str

A stable id for the conversation session.

Source

pub fn storage(&self) -> Option<&Arc<dyn Storage>>

The default storage backend for agent subsystems, if one is configured (storage).

Source

pub fn session_manager(&self) -> Option<&SessionManager>

The session manager saving and restoring the agent, if one is attached.

Source

pub fn messages(&self) -> &[Message]

The conversation history (messages).

Source

pub fn messages_mut(&mut self) -> &mut Vec<Message>

The conversation history, to edit between invocations.

Source

pub fn system_prompt(&self) -> Option<&SystemPrompt>

The system prompt.

Source

pub fn set_system_prompt(&mut self, system_prompt: Option<SystemPrompt>)

Replaces or clears the system prompt.

Source

pub fn model(&self) -> &Arc<dyn Model> ⓘ

The model the agent calls (model).

Source

pub fn set_model(&mut self, model: impl Into<ModelSource>) -> Result<()>

Replaces the model the agent calls: a model instance, an Arc<dyn Model> or a Bedrock model id, like the builder’s model(..).

§Errors

A Bedrock model id without the bedrock feature, and a ModelRouter (a ModelRouter is accepted only as the agent's configured model, not by set_model): a router is attached when the agent is built, so configure it there.

Source

pub fn aux_model(&self) -> &Arc<dyn Model> ⓘ

The model for auxiliary side calls; the agent’s model unless one was configured.

Source

pub fn set_aux_model(&mut self, aux_model: Option<Arc<dyn Model>>)

Sets the auxiliary model; None follows the agent’s model again.

Source

pub fn sandbox(&self) -> &Arc<dyn Sandbox> ⓘ

Where the agent’s tools run commands and touch files (sandbox): the configured sandbox, or the shared NotASandboxLocalEnvironment when none is configured.

Source

pub fn app_state(&self) -> &StateStore

App state shared with tools.

Source

pub fn model_state(&self) -> &StateStore

The model provider’s runtime state.

Source

pub fn tool_registry(&self) -> &ToolRegistry

The agent’s tools.

Source

pub fn tool_registry_mut(&mut self) -> &mut ToolRegistry

The agent’s tools, to add or remove some.

Source

pub fn tools(&self) -> Vec<Arc<dyn Tool>>

The registered tools (tools).

Source

pub fn tool_executor(&self) -> ToolExecutorStrategy

How the tool calls of one model turn run.

Source

pub fn set_tool_executor( &mut self, tool_executor: impl Into<ToolExecutorStrategy>, )

Sets how the tool calls of one model turn run.

Source

pub fn metrics(&self) -> AgentMetrics

Accumulated loop metrics: cycles, token usage and tool statistics (metrics).

Source

pub fn baggage_attributes(&self) -> &BTreeMap<String, String>

The OpenTelemetry baggage entries every invocation runs under.

Source

pub fn cancel_handle(&self) -> CancelHandle

A handle that cancels the agent’s current invocation (agent.cancel). Cancels while the agent is idle do nothing; the invocation in progress ends with StopReason::Cancelled.

use strands::{Agent, CancelOptions};
use strands::testing::MockModel;

let agent = Agent::builder().model(MockModel::new()).printer(false).build()?;
let cancel = agent.cancel_handle();
std::thread::spawn(move || cancel.cancel(CancelOptions::default()));
Source

pub fn cancel_signal(&self) -> CancelSignal

The cancellation signal of the current invocation.

Source

pub fn add_hook<K: HookEvent>( &self, callback: impl IntoSyncHook<K>, ) -> HookCleanup

Registers a hook closure; see HookRegistry::add_hook.

Source

pub fn add_hook_with<K: HookEvent>( &self, callback: impl IntoSyncHook<K>, options: HookCallbackOptions, ) -> HookCleanup

Registers a hook closure with options.

Source

pub fn add_async_hook<K: HookEvent>( &self, callback: impl IntoAsyncHook<K>, ) -> HookCleanup

Registers an async hook closure; name the event type.

Source

pub fn add_async_hook_with<K: HookEvent>( &self, callback: impl IntoAsyncHook<K>, options: HookCallbackOptions, ) -> HookCleanup

Registers an async hook closure with options.

Source

pub fn add_hook_impl<K: HookEvent>( &self, hook: impl IntoHookImpl<K>, ) -> HookCleanup

Registers a Hook implementation.

Source

pub fn add_hook_impl_with<K: HookEvent>( &self, hook: impl IntoHookImpl<K>, options: HookCallbackOptions, ) -> HookCleanup

Registers a Hook implementation with options.

Source

pub fn add_middleware<S: MiddlewareStage>( &self, middleware: Middleware<S>, ) -> MiddlewareCleanup

Registers a middleware handler for its stage and phase; see middleware.

use strands::Agent;
use strands::middleware::InvokeModelStage;
use strands::testing::MockModel;

let agent = Agent::builder().model(MockModel::new()).printer(false).build()?;
let cleanup = agent.add_middleware(InvokeModelStage::output(|mut result| async move {
    result.result.message.content.retain(|block| block.as_text().is_some());
    Ok(result)
}));
cleanup.remove();
Source§

impl Agent

Source

pub fn as_tool(self, options: AgentAsToolOptions) -> AgentAsTool

Wraps the agent as a tool for another agent. An agent passed to AgentBuilder::tools is wrapped with default options.

use strands::Agent;
use strands::agent::AgentAsToolOptions;
use strands::testing::MockModel;

let researcher = Agent::builder()
    .model(MockModel::new())
    .name("researcher")
    .description("Finds information")
    .printer(false)
    .build()?;
let tool = researcher.as_tool(AgentAsToolOptions::default());
let writer = Agent::builder().model(MockModel::new()).tools([tool]).printer(false).build()?;
assert!(writer.tool_registry().get("researcher").is_some());

An agent with a session manager needs preserve_context(true): a tool built from one without it fails every call with the error try_as_tool returns.

Source

pub fn try_as_tool(self, options: AgentAsToolOptions) -> Result<AgentAsTool>

Wraps the agent as a tool, rejecting a session manager that conflicts with the options.

§Errors

The agent has a session manager and preserve_context is not true: the session manager persists the history while the tool resets it between calls.

Source§

impl Agent

Source

pub fn tool(&mut self, name: impl Into<String>) -> ToolHandle<'_>

A handle that calls the named tool directly (agent.tool.<name>).

Source§

impl Agent

Source

pub fn context_manager(&self) -> Option<&ContextManager>

The resolved context manager, when AgentConfig::context_manager set a preset, a configuration or an instance. Experimental, like the context_manager module: it may change in a minor release.

Trait Implementations§

Source§

impl Debug for Agent

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Agent

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl From<Agent> for ToolSource

Source§

fn from(agent: Agent) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !Freeze for Agent

§

impl !RefUnwindSafe for Agent

§

impl !UnwindSafe for Agent

§

impl Send for Agent

§

impl Sync for Agent

§

impl Unpin for Agent

§

impl UnsafeUnpin for Agent

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