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
impl Agent
Sourcepub fn builder() -> AgentBuilder
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");Sourcepub fn new(config: AgentConfig) -> Result<Self>
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.
Sourcepub async fn invoke(
&mut self,
args: impl Into<InvokeArgs>,
) -> Result<AgentResult>
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>.
Sourcepub async fn invoke_with(
&mut self,
args: impl Into<InvokeArgs>,
options: InvokeOptions,
) -> Result<AgentResult>
pub async fn invoke_with( &mut self, args: impl Into<InvokeArgs>, options: InvokeOptions, ) -> Result<AgentResult>
Sourcepub fn stream(&mut self, args: impl Into<InvokeArgs>) -> AgentStream<'_>
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.
Sourcepub fn stream_with(
&mut self,
args: impl Into<InvokeArgs>,
options: InvokeOptions,
) -> AgentStream<'_>
pub fn stream_with( &mut self, args: impl Into<InvokeArgs>, options: InvokeOptions, ) -> AgentStream<'_>
Streams the invocation with per-invocation options.
Sourcepub async fn initialize(&mut self) -> Result<()>
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.
Sourcepub async fn shutdown(&mut self) -> Result<()>
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.
Sourcepub fn memory_manager(&self) -> Option<&MemoryManager>
pub fn memory_manager(&self) -> Option<&MemoryManager>
The memory manager, if one is configured.
Sourcepub fn take_snapshot(
&self,
options: impl Into<TakeSnapshotOptions>,
) -> Result<Snapshot>
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.
Sourcepub fn load_snapshot(&mut self, snapshot: &Snapshot) -> Result<()>
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.
Sourcepub fn local(&self) -> &LocalAgent
pub fn local(&self) -> &LocalAgent
The agent’s view as sequential hooks see it.
Sourcepub fn local_mut(&mut self) -> &mut LocalAgent
pub fn local_mut(&mut self) -> &mut LocalAgent
The agent’s view as sequential hooks see it, mutably.
Sourcepub fn description(&self) -> Option<&str>
pub fn description(&self) -> Option<&str>
What the agent does (description).
Sourcepub fn session_id(&self) -> &str
pub fn session_id(&self) -> &str
A stable id for the conversation session.
Sourcepub fn storage(&self) -> Option<&Arc<dyn Storage>>
pub fn storage(&self) -> Option<&Arc<dyn Storage>>
The default storage backend for agent subsystems, if one is configured (storage).
Sourcepub fn session_manager(&self) -> Option<&SessionManager>
pub fn session_manager(&self) -> Option<&SessionManager>
The session manager saving and restoring the agent, if one is attached.
Sourcepub fn messages_mut(&mut self) -> &mut Vec<Message>
pub fn messages_mut(&mut self) -> &mut Vec<Message>
The conversation history, to edit between invocations.
Sourcepub fn system_prompt(&self) -> Option<&SystemPrompt>
pub fn system_prompt(&self) -> Option<&SystemPrompt>
The system prompt.
Sourcepub fn set_system_prompt(&mut self, system_prompt: Option<SystemPrompt>)
pub fn set_system_prompt(&mut self, system_prompt: Option<SystemPrompt>)
Replaces or clears the system prompt.
Sourcepub fn set_model(&mut self, model: impl Into<ModelSource>) -> Result<()>
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.
Sourcepub fn aux_model(&self) -> &Arc<dyn Model> ⓘ
pub fn aux_model(&self) -> &Arc<dyn Model> ⓘ
The model for auxiliary side calls; the agent’s model unless one was configured.
Sourcepub fn set_aux_model(&mut self, aux_model: Option<Arc<dyn Model>>)
pub fn set_aux_model(&mut self, aux_model: Option<Arc<dyn Model>>)
Sets the auxiliary model; None follows the agent’s model again.
Sourcepub fn sandbox(&self) -> &Arc<dyn Sandbox> ⓘ
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.
Sourcepub fn app_state(&self) -> &StateStore
pub fn app_state(&self) -> &StateStore
App state shared with tools.
Sourcepub fn model_state(&self) -> &StateStore
pub fn model_state(&self) -> &StateStore
The model provider’s runtime state.
Sourcepub fn tool_registry(&self) -> &ToolRegistry
pub fn tool_registry(&self) -> &ToolRegistry
The agent’s tools.
Sourcepub fn tool_registry_mut(&mut self) -> &mut ToolRegistry
pub fn tool_registry_mut(&mut self) -> &mut ToolRegistry
The agent’s tools, to add or remove some.
Sourcepub fn tool_executor(&self) -> ToolExecutorStrategy
pub fn tool_executor(&self) -> ToolExecutorStrategy
How the tool calls of one model turn run.
Sourcepub fn set_tool_executor(
&mut self,
tool_executor: impl Into<ToolExecutorStrategy>,
)
pub fn set_tool_executor( &mut self, tool_executor: impl Into<ToolExecutorStrategy>, )
Sets how the tool calls of one model turn run.
Sourcepub fn metrics(&self) -> AgentMetrics
pub fn metrics(&self) -> AgentMetrics
Accumulated loop metrics: cycles, token usage and tool statistics (metrics).
Sourcepub fn baggage_attributes(&self) -> &BTreeMap<String, String>
pub fn baggage_attributes(&self) -> &BTreeMap<String, String>
The OpenTelemetry baggage entries every invocation runs under.
Sourcepub fn cancel_handle(&self) -> CancelHandle
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()));Sourcepub fn cancel_signal(&self) -> CancelSignal
pub fn cancel_signal(&self) -> CancelSignal
The cancellation signal of the current invocation.
Sourcepub fn add_hook<K: HookEvent>(
&self,
callback: impl IntoSyncHook<K>,
) -> HookCleanup
pub fn add_hook<K: HookEvent>( &self, callback: impl IntoSyncHook<K>, ) -> HookCleanup
Registers a hook closure; see HookRegistry::add_hook.
Sourcepub fn add_hook_with<K: HookEvent>(
&self,
callback: impl IntoSyncHook<K>,
options: HookCallbackOptions,
) -> HookCleanup
pub fn add_hook_with<K: HookEvent>( &self, callback: impl IntoSyncHook<K>, options: HookCallbackOptions, ) -> HookCleanup
Registers a hook closure with options.
Sourcepub fn add_async_hook<K: HookEvent>(
&self,
callback: impl IntoAsyncHook<K>,
) -> HookCleanup
pub fn add_async_hook<K: HookEvent>( &self, callback: impl IntoAsyncHook<K>, ) -> HookCleanup
Registers an async hook closure; name the event type.
Sourcepub fn add_async_hook_with<K: HookEvent>(
&self,
callback: impl IntoAsyncHook<K>,
options: HookCallbackOptions,
) -> HookCleanup
pub fn add_async_hook_with<K: HookEvent>( &self, callback: impl IntoAsyncHook<K>, options: HookCallbackOptions, ) -> HookCleanup
Registers an async hook closure with options.
Sourcepub fn add_hook_impl<K: HookEvent>(
&self,
hook: impl IntoHookImpl<K>,
) -> HookCleanup
pub fn add_hook_impl<K: HookEvent>( &self, hook: impl IntoHookImpl<K>, ) -> HookCleanup
Registers a Hook implementation.
Sourcepub fn add_hook_impl_with<K: HookEvent>(
&self,
hook: impl IntoHookImpl<K>,
options: HookCallbackOptions,
) -> HookCleanup
pub fn add_hook_impl_with<K: HookEvent>( &self, hook: impl IntoHookImpl<K>, options: HookCallbackOptions, ) -> HookCleanup
Registers a Hook implementation with options.
Sourcepub fn add_middleware<S: MiddlewareStage>(
&self,
middleware: Middleware<S>,
) -> MiddlewareCleanup
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
impl Agent
Sourcepub fn as_tool(self, options: AgentAsToolOptions) -> AgentAsTool
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.
Sourcepub fn try_as_tool(self, options: AgentAsToolOptions) -> Result<AgentAsTool>
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
impl Agent
Sourcepub fn tool(&mut self, name: impl Into<String>) -> ToolHandle<'_>
pub fn tool(&mut self, name: impl Into<String>) -> ToolHandle<'_>
A handle that calls the named tool directly (agent.tool.<name>).
Source§impl Agent
impl Agent
Sourcepub fn context_manager(&self) -> Option<&ContextManager>
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§
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> FutureExt for T
impl<T> FutureExt for T
§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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