Skip to main content

strands/tools/executors/
sequential.rs

1//! Sequential tool execution.
2
3use tokio::sync::mpsc;
4use tokio::task::JoinSet;
5
6use super::executor::{
7    BatchOutcome, CallOutcome, ExecutorItem, Message, ToolBatch, ToolPipelineFn, channel_capacity,
8    ended_without_outcome, spawn_call, text_result,
9};
10use crate::models::BoxStream;
11
12/// Runs the tool calls of a turn one at a time, in order (`SequentialToolExecutor`).
13///
14/// The cancel signal is checked between calls, so calls that have not started end as
15/// `Tool execution cancelled`. An interrupt, a hook error or a tool-stage middleware error stops
16/// the batch at once; later calls do not run, and an error fails the invocation.
17#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
18#[non_exhaustive]
19pub struct SequentialToolExecutor;
20
21impl SequentialToolExecutor {
22    /// Creates the executor.
23    #[must_use]
24    pub fn new() -> Self {
25        Self
26    }
27}
28
29enum CallEnd<E> {
30    Event(E),
31    Outcome(CallOutcome),
32}
33
34pub(super) fn execute_sequential<E: Send + 'static>(
35    batch: ToolBatch,
36    pipeline: ToolPipelineFn<E>,
37) -> BoxStream<'static, ExecutorItem<E>> {
38    Box::pin(async_stream::stream! {
39        let ToolBatch { tool_uses, completed, cancel_signal } = batch;
40        let mut outcome = BatchOutcome {
41            completed: completed.clone(),
42            ..BatchOutcome::default()
43        };
44        for (index, tool_use) in tool_uses.into_iter().enumerate() {
45            if let Some(result) = completed.get(&tool_use.tool_use_id) {
46                outcome.results.push(result.clone());
47                continue;
48            }
49            let tool_use_id = tool_use.tool_use_id.clone();
50            let result = if cancel_signal.is_cancelled() {
51                text_result(&tool_use_id, "Tool execution cancelled")
52            } else {
53                let (sender, mut receiver) = mpsc::channel(channel_capacity(1));
54                let mut tasks = JoinSet::new();
55                spawn_call(&mut tasks, index, tool_use, &pipeline, &sender);
56                drop(sender);
57                let mut ended = None;
58                while ended.is_none() {
59                    let step = next_step(&mut receiver, &mut tasks, &tool_use_id).await;
60                    match step {
61                        CallEnd::Event(event) => yield ExecutorItem::Event(event),
62                        CallEnd::Outcome(call_outcome) => ended = Some(call_outcome),
63                    }
64                }
65                match ended {
66                    Some(CallOutcome::Result(result)) => result,
67                    Some(CallOutcome::Interrupts(raised)) => {
68                        outcome.interrupts.extend(raised);
69                        break;
70                    }
71                    Some(CallOutcome::Error(error) | CallOutcome::StageError(error)) => {
72                        outcome.error = Some(error);
73                        break;
74                    }
75                    None => text_result(&tool_use_id, "Tool execution interrupted"),
76                }
77            };
78            outcome.results.push(result.clone());
79            outcome.completed.insert(tool_use_id, result.clone());
80            yield ExecutorItem::Result(result);
81        }
82        yield ExecutorItem::Done(outcome);
83    })
84}
85
86/// The next event or the outcome of the running call.
87async fn next_step<E>(
88    receiver: &mut mpsc::Receiver<Message<E>>,
89    tasks: &mut JoinSet<()>,
90    tool_use_id: &str,
91) -> CallEnd<E> {
92    if let Ok(message) = receiver.try_recv() {
93        return from_message(message);
94    }
95    tokio::select! {
96        biased;
97        Some(message) = receiver.recv() => from_message(message),
98        Some(Err(error)) = tasks.join_next() => {
99            if let Ok(message) = receiver.try_recv() {
100                return from_message(message);
101            }
102            CallEnd::Outcome(CallOutcome::Result(ended_without_outcome(error, tool_use_id)))
103        }
104        else => CallEnd::Outcome(CallOutcome::Result(text_result(tool_use_id, "Tool execution interrupted"))),
105    }
106}
107
108fn from_message<E>(message: Message<E>) -> CallEnd<E> {
109    match message {
110        Message::Event(event) => CallEnd::Event(event),
111        Message::Done(_, outcome) => CallEnd::Outcome(*outcome),
112    }
113}