Skip to main content

strands/tools/executors/
concurrent.rs

1//! Concurrent tool execution.
2
3use std::collections::HashMap;
4
5use indexmap::IndexMap;
6use tokio::sync::mpsc;
7use tokio::task::JoinSet;
8
9use super::executor::{
10    BatchOutcome, CallOutcome, ExecutorItem, Message, ToolBatch, ToolPipelineFn, channel_capacity,
11    ended_without_outcome, failure_result, spawn_call, text_result,
12};
13use crate::models::BoxStream;
14
15/// Runs the tool calls of a turn concurrently, each on its own task (`ConcurrentToolExecutor`).
16///
17/// Events of different calls interleave; each call's events keep their order. When a call raises
18/// an interrupt, its siblings still finish before the agent stops; when a hook fails, the calls
19/// still running are aborted and the invocation fails. A tool-stage middleware error is that
20/// call's error result, without `AfterToolCallEvent`. A tool that panics becomes an error result
21/// with the panic message, and dropping the agent stream aborts calls in flight.
22#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
23#[non_exhaustive]
24pub struct ConcurrentToolExecutor;
25
26impl ConcurrentToolExecutor {
27    /// Creates the executor.
28    #[must_use]
29    pub fn new() -> Self {
30        Self
31    }
32}
33
34pub(super) fn execute_concurrent<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, .. } = batch;
40        let (sender, mut receiver) = mpsc::channel(channel_capacity(tool_uses.len()));
41        let mut tasks = JoinSet::new();
42        let mut task_index = HashMap::new();
43        for (index, tool_use) in tool_uses.iter().enumerate() {
44            if completed.contains_key(&tool_use.tool_use_id) {
45                continue;
46            }
47            let id = spawn_call(&mut tasks, index, tool_use.clone(), &pipeline, &sender);
48            task_index.insert(id, index);
49        }
50        drop(sender);
51
52        let mut results: IndexMap<String, _> = completed;
53        let mut interrupts = Vec::new();
54        let mut error = None;
55        let mut running = task_index.len();
56        while running > 0 && error.is_none() {
57            tokio::select! {
58                biased;
59                Some(message) = receiver.recv() => match message {
60                    Message::Event(event) => yield ExecutorItem::Event(event),
61                    Message::Done(index, outcome) => {
62                        running -= 1;
63                        match *outcome {
64                            CallOutcome::Result(result) => {
65                                results.insert(tool_uses[index].tool_use_id.clone(), result.clone());
66                                yield ExecutorItem::Result(result);
67                            }
68                            CallOutcome::StageError(failure) => {
69                                let result = failure_result(&tool_uses[index].tool_use_id, failure);
70                                results.insert(tool_uses[index].tool_use_id.clone(), result.clone());
71                                yield ExecutorItem::Result(result);
72                            }
73                            CallOutcome::Interrupts(raised) => interrupts.extend(raised),
74                            CallOutcome::Error(failure) => error = Some(failure),
75                        }
76                    }
77                },
78                Some(joined) = tasks.join_next_with_id() => {
79                    let Err(failure) = joined else { continue };
80                    let Some(index) = task_index.get(&failure.id()).copied() else { continue };
81                    running -= 1;
82                    let tool_use_id = &tool_uses[index].tool_use_id;
83                    let result = ended_without_outcome(failure, tool_use_id);
84                    results.insert(tool_use_id.clone(), result.clone());
85                    yield ExecutorItem::Result(result);
86                }
87                else => break,
88            }
89        }
90        drop(tasks);
91
92        let ordered = tool_uses
93            .iter()
94            .map(|tool_use| {
95                results
96                    .get(&tool_use.tool_use_id)
97                    .cloned()
98                    .unwrap_or_else(|| text_result(&tool_use.tool_use_id, "Tool execution interrupted"))
99            })
100            .collect();
101        yield ExecutorItem::Done(BatchOutcome {
102            results: ordered,
103            completed: results,
104            interrupts,
105            error,
106        });
107    })
108}