strands/middleware/mod.rs
1//! Middleware: handlers that wrap the model call
2//! ([`InvokeModelStage`]) and each tool execution ([`ExecuteToolStage`]).
3//!
4//! Register a handler with [`Agent::add_middleware`](crate::Agent::add_middleware) (or
5//! [`LocalAgent::add_middleware`](crate::LocalAgent::add_middleware) from a plugin). Three
6//! phases exist:
7//!
8//! - **Input** handlers transform the context: `InvokeModelStage::input(|context| async move { .. })`.
9//! - **Output** handlers transform the result: `InvokeModelStage::output(|result| async move { .. })`.
10//! - **Wrap** handlers get the context and `next` and return the stage's [`StageStream`]: events,
11//! then the outcome, the same shape as a tool's stream. They may short-circuit, retry, filter
12//! or inject events.
13//!
14//! Handlers run Input, then Wrap, then Output, each phase in registration order, whatever order
15//! they were added in. Hooks fire outside the chain, so they see one call per stage even when a
16//! handler short-circuits or retries. Events a handler suppresses never reach hooks or the
17//! agent's stream; events it injects do.
18//!
19//! ```
20//! use std::sync::Arc;
21//! use std::sync::atomic::{AtomicUsize, Ordering};
22//! use strands::Agent;
23//! use strands::middleware::{InvokeModelStage, StageStream};
24//! use strands::testing::MockModel;
25//!
26//! # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
27//! let mut agent = Agent::builder().model(MockModel::new().with_turn("Hello")).printer(false).build()?;
28//! let calls = Arc::new(AtomicUsize::new(0));
29//! let counter = calls.clone();
30//! let cleanup = agent.add_middleware(InvokeModelStage::wrap(move |context, next| {
31//! counter.fetch_add(1, Ordering::Relaxed);
32//! next.call(context)
33//! }));
34//! agent.invoke("Hi").await?;
35//! assert_eq!(calls.load(Ordering::Relaxed), 1);
36//! cleanup.remove();
37//! # Ok::<(), strands::Error>(())
38//! # }).unwrap();
39//! ```
40//!
41//! A Wrap handler that does more than pass through builds its stream by hand; forward the events of
42//! `next` so hooks and the agent's stream still see them ([`StageStream::result`] and
43//! [`StageStream::from_future`] drop them). [`StageStream::from_stream_future`] covers async work
44//! before `next`; for anything else, `async_stream::stream!` (add `async-stream = "0.3"` to your
45//! dependencies) writes the stream as straight-line async code. A handler that retries a failed
46//! model call once:
47//!
48//! ```
49//! use futures::StreamExt;
50//! use strands::Agent;
51//! use strands::middleware::{InvokeModelStage, StageItem, StageStream};
52//! use strands::testing::{MockModel, MockTurn};
53//!
54//! # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
55//! let model = MockModel::from_turns([MockTurn::error(|| strands::Error::other("flaky")), MockTurn::text("Hello")]);
56//! let mut agent = Agent::builder().model(model).printer(false).build()?;
57//! agent.add_middleware(InvokeModelStage::wrap(|context, next| {
58//! StageStream::new(async_stream::stream! {
59//! for attempt in 1..=2 {
60//! let mut stream = next.call(context.clone());
61//! while let Some(item) = stream.next().await {
62//! if attempt == 1 && matches!(item, StageItem::Done(Err(_))) {
63//! break;
64//! }
65//! let done = matches!(item, StageItem::Done(_));
66//! yield item;
67//! if done {
68//! return;
69//! }
70//! }
71//! }
72//! })
73//! }));
74//! assert_eq!(agent.invoke("Hi").await?.to_string(), "Hello");
75//! # Ok::<(), strands::Error>(())
76//! # }).unwrap();
77//! ```
78
79mod registry;
80#[cfg(test)]
81mod registry_tests;
82mod stages;
83mod types;
84
85pub(crate) use registry::MiddlewareRegistry;
86pub(crate) use stages::middleware_interrupt;
87pub use stages::{
88 ExecuteToolContext, ExecuteToolResult, ExecuteToolStage, InvokeModelContext, InvokeModelResult, InvokeModelStage,
89 MiddlewareInterruptResult,
90};
91pub(crate) use types::TerminalFn;
92pub use types::{
93 Middleware, MiddlewareCleanup, MiddlewareError, MiddlewareNext, MiddlewarePhase, MiddlewareStage, StageItem,
94 StageResult, StageStream,
95};