Expand description
Middleware: handlers that wrap the model call
(InvokeModelStage) and each tool execution (ExecuteToolStage).
Register a handler with Agent::add_middleware (or
LocalAgent::add_middleware from a plugin). Three
phases exist:
- Input handlers transform the context:
InvokeModelStage::input(|context| async move { .. }). - Output handlers transform the result:
InvokeModelStage::output(|result| async move { .. }). - Wrap handlers get the context and
nextand return the stage’sStageStream: events, then the outcome, the same shape as a tool’s stream. They may short-circuit, retry, filter or inject events.
Handlers run Input, then Wrap, then Output, each phase in registration order, whatever order they were added in. Hooks fire outside the chain, so they see one call per stage even when a handler short-circuits or retries. Events a handler suppresses never reach hooks or the agent’s stream; events it injects do.
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use strands::Agent;
use strands::middleware::{InvokeModelStage, StageStream};
use strands::testing::MockModel;
let mut agent = Agent::builder().model(MockModel::new().with_turn("Hello")).printer(false).build()?;
let calls = Arc::new(AtomicUsize::new(0));
let counter = calls.clone();
let cleanup = agent.add_middleware(InvokeModelStage::wrap(move |context, next| {
counter.fetch_add(1, Ordering::Relaxed);
next.call(context)
}));
agent.invoke("Hi").await?;
assert_eq!(calls.load(Ordering::Relaxed), 1);
cleanup.remove();A Wrap handler that does more than pass through builds its stream by hand; forward the events of
next so hooks and the agent’s stream still see them (StageStream::result and
StageStream::from_future drop them). StageStream::from_stream_future covers async work
before next; for anything else, async_stream::stream! (add async-stream = "0.3" to your
dependencies) writes the stream as straight-line async code. A handler that retries a failed
model call once:
use futures::StreamExt;
use strands::Agent;
use strands::middleware::{InvokeModelStage, StageItem, StageStream};
use strands::testing::{MockModel, MockTurn};
let model = MockModel::from_turns([MockTurn::error(|| strands::Error::other("flaky")), MockTurn::text("Hello")]);
let mut agent = Agent::builder().model(model).printer(false).build()?;
agent.add_middleware(InvokeModelStage::wrap(|context, next| {
StageStream::new(async_stream::stream! {
for attempt in 1..=2 {
let mut stream = next.call(context.clone());
while let Some(item) = stream.next().await {
if attempt == 1 && matches!(item, StageItem::Done(Err(_))) {
break;
}
let done = matches!(item, StageItem::Done(_));
yield item;
if done {
return;
}
}
}
})
}));
assert_eq!(agent.invoke("Hi").await?.to_string(), "Hello");Structs§
- Execute
Tool Context - What tool-stage handlers receive (
ExecuteToolContext).tool_useis a copy of the model’s request;invocation_stateis shared. - Execute
Tool Result - What the tool stage produces (
ExecuteToolResult). - Execute
Tool Stage - One tool execution (
ExecuteToolStage): add telemetry, validate inputs, mock or cache results. - Invoke
Model Context - What model-stage handlers receive (
InvokeModelContext). Collections are copies of the agent’s;invocation_stateis shared with hooks, tools and the result. - Invoke
Model Result - What the model stage produces (
InvokeModelResult). - Invoke
Model Stage - The model call (
InvokeModelStage): rate-limit, cache, route or transform model inputs. - Middleware
- A middleware handler for the stage
S, ready forAgent::add_middleware. Build one with the stage’sinput,outputorwrap, for exampleInvokeModelStage::input. - Middleware
Cleanup - Removes a registered middleware handler;
Agent::add_middlewarereturns it. - Middleware
Interrupt Result - What a middleware interrupt returns on resume (
MiddlewareInterruptResult); an object so it can grow without breaking callers. - Middleware
Next - The rest of the chain a Wrap handler calls (
MiddlewareNext). Cheap to clone; call it more than once to retry. - Stage
Stream - The stream a Wrap handler and
nextreturn: events, then oneStageItem::Done. A stream that ends without one is a stage error.
Enums§
- Middleware
Error - Why a stage did not produce a result.
- Middleware
Phase - The phase a handler runs in (
MiddlewarePhaseKind). The chain composes Input outermost, then Output, then Wrap next to the stage, so handlers run Input, Wrap, Output. - Stage
Item - One item of a stage stream: an event, or the stage outcome that ends the stream.
Traits§
- Middleware
Stage - A middleware interception point (
MiddlewareStage), sealed to the SDK’s stages:InvokeModelStageandExecuteToolStage.
Type Aliases§
- Stage
Result - The outcome of a stage.