Skip to main content

strands/middleware/
stages.rs

1//! The built-in stages and their contexts and the middleware interrupt.
2
3use std::collections::HashSet;
4use std::fmt;
5use std::future::Future;
6use std::sync::Arc;
7
8use indexmap::IndexMap;
9
10use super::registry::{MiddlewareRegistry, StageRegistry};
11use super::types::{Middleware, MiddlewareNext, MiddlewareStage, StageResult, StageStream, private};
12use crate::agent::{InvocationContext, InvocationState, ToolAgent};
13use crate::cancel::CancelSignal;
14use crate::interrupt::{Interrupt, InterruptError, InterruptSource, InterruptState};
15use crate::models::{Model, StreamAggregatedResult};
16use crate::tools::Tool;
17use crate::types::{
18    InterruptParams, JsonSchema, JsonValue, Message, SystemPrompt, ToolChoice, ToolResultBlock, ToolSpec, ToolUse,
19};
20
21macro_rules! stage_constructors {
22    ($stage:ident) => {
23        impl $stage {
24            /// An Input handler (`.Input`): transforms the context before the stage runs.
25            pub fn input<F, Fut>(handler: F) -> Middleware<Self>
26            where
27                F: Fn(<Self as MiddlewareStage>::Context) -> Fut + Send + Sync + 'static,
28                Fut: Future<Output = StageResult<<Self as MiddlewareStage>::Context>> + Send + 'static,
29            {
30                Middleware::input(handler)
31            }
32
33            /// An Output handler (`.Output`): transforms the result after the stage runs.
34            pub fn output<F, Fut>(handler: F) -> Middleware<Self>
35            where
36                F: Fn(<Self as MiddlewareStage>::Result) -> Fut + Send + Sync + 'static,
37                Fut: Future<Output = StageResult<<Self as MiddlewareStage>::Result>> + Send + 'static,
38            {
39                Middleware::output(handler)
40            }
41
42            /// A Wrap handler (the bare stage or `.Wrap`): gets the context and `next`.
43            pub fn wrap<F>(handler: F) -> Middleware<Self>
44            where
45                F: Fn(<Self as MiddlewareStage>::Context, MiddlewareNext<Self>) -> StageStream<Self>
46                    + Send
47                    + Sync
48                    + 'static,
49            {
50                Middleware::wrap(handler)
51            }
52        }
53    };
54}
55
56/// The model call (`InvokeModelStage`): rate-limit, cache, route or transform model inputs.
57///
58/// Hooks fire outside the chain: `BeforeModelCallEvent` before it, `AfterModelCallEvent` after,
59/// once per call even when a handler short-circuits or retries. Model state is not on the
60/// context; the agent commits the provider's writes after the whole chain succeeds.
61///
62/// ```
63/// use strands::Agent;
64/// use strands::middleware::InvokeModelStage;
65/// use strands::testing::MockModel;
66///
67/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
68/// let model = MockModel::new().with_turn("Hello");
69/// let mut agent = Agent::builder().model(model.clone()).printer(false).build()?;
70/// agent.add_middleware(InvokeModelStage::input(|mut context| async move {
71///     context.system_prompt = Some("Answer in French.".into());
72///     Ok(context)
73/// }));
74/// agent.invoke("Hi").await?;
75/// assert_eq!(model.requests()[0].system_prompt, Some("Answer in French.".into()));
76/// # Ok::<(), strands::Error>(())
77/// # }).unwrap();
78/// ```
79#[derive(Debug, Clone, Copy)]
80#[non_exhaustive]
81pub struct InvokeModelStage;
82
83impl private::Sealed for InvokeModelStage {
84    fn slot(registry: &MiddlewareRegistry) -> &StageRegistry<Self> {
85        registry.invoke_model()
86    }
87}
88
89impl MiddlewareStage for InvokeModelStage {
90    type Context = InvokeModelContext;
91    type Result = InvokeModelResult;
92    const NAME: &'static str = "invokeModel";
93}
94
95stage_constructors!(InvokeModelStage);
96
97/// One tool execution (`ExecuteToolStage`): add telemetry, validate inputs, mock or cache results.
98///
99/// Runs on the tool's task, inside `BeforeToolCallEvent` and `AfterToolCallEvent`.
100///
101/// ```
102/// use serde_json::json;
103/// use strands::middleware::{ExecuteToolResult, ExecuteToolStage, StageStream};
104/// use strands::types::{ToolResultBlock, ToolResultContent};
105///
106/// let mock = ExecuteToolStage::wrap(|context, next| {
107///     if context.tool_use.name != "weather" {
108///         return next.call(context);
109///     }
110///     let result = ToolResultBlock::success(context.tool_use.tool_use_id, vec![ToolResultContent::text("sunny")]);
111///     StageStream::from_result(Ok(ExecuteToolResult::new(result)))
112/// });
113/// # let _ = (mock, json!(null));
114/// ```
115#[derive(Debug, Clone, Copy)]
116#[non_exhaustive]
117pub struct ExecuteToolStage;
118
119impl private::Sealed for ExecuteToolStage {
120    fn slot(registry: &MiddlewareRegistry) -> &StageRegistry<Self> {
121        registry.execute_tool()
122    }
123}
124
125impl MiddlewareStage for ExecuteToolStage {
126    type Context = ExecuteToolContext;
127    type Result = ExecuteToolResult;
128    const NAME: &'static str = "executeTool";
129}
130
131stage_constructors!(ExecuteToolStage);
132
133/// What model-stage handlers receive (`InvokeModelContext`). Collections are copies of the
134/// agent's; `invocation_state` is shared with hooks, tools and the result.
135#[derive(Clone)]
136#[non_exhaustive]
137pub struct InvokeModelContext {
138    /// The agent, as tools see it (an escape hatch).
139    pub agent: ToolAgent,
140    /// The model this call invokes; initialized from the agent's and replaceable per call.
141    pub model: Arc<dyn Model>,
142    /// The messages to send.
143    pub messages: Vec<Message>,
144    /// The system prompt.
145    pub system_prompt: Option<SystemPrompt>,
146    /// The tool specs the model may use.
147    pub tool_specs: Vec<ToolSpec>,
148    /// How the model selects tools.
149    pub tool_choice: Option<ToolChoice>,
150    /// Per-invocation state, shared.
151    pub invocation_state: InvocationState,
152    /// The estimated input tokens of this call, when estimation succeeded.
153    pub projected_input_tokens: Option<u64>,
154    /// How many trailing blocks of the last user message are rebuilt on every call; producers
155    /// add to it.
156    pub dynamic_trailing_blocks: Option<usize>,
157    /// The schema this call must produce, set on the structured output retry.
158    pub structured_output_schema: Option<JsonSchema>,
159    /// Names of the tools this call defers, set by deferred tool loading and passed to the
160    /// provider in [`ModelRequest::deferred_tools`](crate::models::ModelRequest::deferred_tools).
161    pub deferred_tools: HashSet<String>,
162    /// The request this call belongs to.
163    pub invocation_context: Option<InvocationContext>,
164}
165
166impl fmt::Debug for InvokeModelContext {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        f.debug_struct("InvokeModelContext")
169            .field("model", &self.model.model_id())
170            .field("messages", &self.messages.len())
171            .field("tool_specs", &self.tool_specs.len())
172            .field("tool_choice", &self.tool_choice)
173            .finish_non_exhaustive()
174    }
175}
176
177/// What the model stage produces (`InvokeModelResult`).
178#[derive(Debug, Clone, PartialEq)]
179#[non_exhaustive]
180pub struct InvokeModelResult {
181    /// The aggregated model response.
182    pub result: StreamAggregatedResult,
183}
184
185impl InvokeModelResult {
186    /// Wraps an aggregated model response.
187    #[must_use]
188    pub fn new(result: StreamAggregatedResult) -> Self {
189        Self { result }
190    }
191}
192
193type InterruptFn = Arc<dyn Fn(&InterruptParams) -> Result<JsonValue, InterruptError> + Send + Sync>;
194
195/// What tool-stage handlers receive (`ExecuteToolContext`). `tool_use` is a copy of the model's
196/// request; `invocation_state` is shared.
197#[derive(Clone)]
198#[non_exhaustive]
199pub struct ExecuteToolContext {
200    /// The agent, as tools see it (an escape hatch).
201    pub agent: ToolAgent,
202    /// The tool that runs, or `None` when the name is not registered.
203    pub tool: Option<Arc<dyn Tool>>,
204    /// The tool use request.
205    pub tool_use: ToolUse,
206    /// Per-invocation state, shared.
207    pub invocation_state: InvocationState,
208    cancel_signal: CancelSignal,
209    interrupt: InterruptFn,
210}
211
212impl ExecuteToolContext {
213    pub(crate) fn new(
214        agent: ToolAgent,
215        tool: Option<Arc<dyn Tool>>,
216        tool_use: ToolUse,
217        invocation_state: InvocationState,
218        cancel_signal: CancelSignal,
219    ) -> Self {
220        let interrupt = middleware_interrupt(
221            agent.interrupt_state().clone(),
222            format!("middleware:executeTool:{}", tool_use.tool_use_id),
223            None,
224        );
225        Self {
226            agent,
227            tool,
228            tool_use,
229            invocation_state,
230            cancel_signal,
231            interrupt,
232        }
233    }
234
235    pub(crate) fn with_interrupt(mut self, interrupt: InterruptFn) -> Self {
236        self.interrupt = interrupt;
237        self
238    }
239
240    /// The executor's cancellation signal for this call; observe it, it cannot be replaced.
241    #[must_use]
242    pub fn cancel_signal(&self) -> &CancelSignal {
243        &self.cancel_signal
244    }
245
246    /// Requests a human-in-the-loop interrupt (`interrupt`).
247    ///
248    /// Returns the response on resume (or the preemptive `params.response`); otherwise the
249    /// interrupt, which `?` turns into [`MiddlewareError::Interrupt`](super::MiddlewareError) so
250    /// the agent stops with `StopReason::Interrupt` and the tool does not run. The id is
251    /// `middleware:executeTool:<toolUseId>:<name>`.
252    ///
253    /// # Errors
254    ///
255    /// The unanswered interrupt.
256    pub fn interrupt(&self, params: impl Into<InterruptParams>) -> Result<MiddlewareInterruptResult, InterruptError> {
257        (self.interrupt)(&params.into()).map(MiddlewareInterruptResult::new)
258    }
259}
260
261impl fmt::Debug for ExecuteToolContext {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        f.debug_struct("ExecuteToolContext")
264            .field("tool_use", &self.tool_use)
265            .field("tool", &self.tool.as_ref().map(|tool| tool.name().to_owned()))
266            .finish_non_exhaustive()
267    }
268}
269
270/// What the tool stage produces (`ExecuteToolResult`).
271#[derive(Debug, Clone, PartialEq)]
272#[non_exhaustive]
273pub struct ExecuteToolResult {
274    /// The tool result.
275    pub result: ToolResultBlock,
276}
277
278impl ExecuteToolResult {
279    /// Wraps a tool result.
280    #[must_use]
281    pub fn new(result: ToolResultBlock) -> Self {
282        Self { result }
283    }
284}
285
286/// What a middleware interrupt returns on resume (`MiddlewareInterruptResult`); an object so it
287/// can grow without breaking callers.
288#[derive(Debug, Clone, PartialEq)]
289#[non_exhaustive]
290pub struct MiddlewareInterruptResult {
291    /// The response the caller gave.
292    pub response: JsonValue,
293}
294
295impl MiddlewareInterruptResult {
296    /// Wraps a response.
297    #[must_use]
298    pub fn new(response: JsonValue) -> Self {
299        Self { response }
300    }
301}
302
303/// A non-mutating interrupt backed by `state`: prior responses are
304/// read from `prior` (a snapshot) or the live state, and a new interrupt stays local until the
305/// agent stops for it.
306pub(crate) fn middleware_interrupt(
307    state: InterruptState,
308    prefix: String,
309    prior: Option<IndexMap<String, Interrupt>>,
310) -> InterruptFn {
311    Arc::new(move |params: &InterruptParams| {
312        let id = format!("{prefix}:{}", params.name);
313        let existing = match &prior {
314            Some(prior) => prior.get(&id).and_then(|interrupt| interrupt.response.clone()),
315            None => state.response(&id),
316        };
317        if let Some(response) = existing.or_else(|| params.response.clone()) {
318            return Ok(response);
319        }
320        let mut interrupt = Interrupt::new(id, params.name.clone()).with_source(InterruptSource::Middleware);
321        interrupt.reason.clone_from(&params.reason);
322        Err(interrupt.into())
323    })
324}