Skip to main content

strands/background_tasks/
mod.rs

1//! Background tool execution.
2//!
3//! With [`AgentConfig::background_tasks`](crate::AgentConfig::background_tasks) set, tool calls
4//! can run detached from the turn that requested them. The model selects background execution
5//! per call through a `_background_execution` property added to each eligible tool's schema
6//! (the `agentic` policy, by default for every tool), or a tool always or never runs in the
7//! background. A detached call returns a dispatch acknowledgement at once; its result is
8//! delivered later as a synthetic `manage_background_task` `get` call, before the next
9//! model call or at the end of the invocation. By default the invocation waits for its tasks.
10//!
11//! ```
12//! use strands::Agent;
13//! use strands::background_tasks::BackgroundTasksConfig;
14//! use strands::testing::MockModel;
15//!
16//! let agent = Agent::builder()
17//!     .model(MockModel::new())
18//!     .background_tasks(BackgroundTasksConfig {
19//!         always: Some(vec!["slow_report".into()]),
20//!         max_concurrency: Some(2),
21//!         ..Default::default()
22//!     })
23//!     .printer(false)
24//!     .build()?;
25//! # let _ = agent;
26//! # Ok::<(), strands::Error>(())
27//! ```
28
29mod engine;
30mod manager;
31mod plugin;
32mod types;
33
34use std::time::Duration;
35
36pub(crate) use engine::panic_message;
37pub(crate) use manager::{RunFailure, RunFn, ToolRun};
38pub(crate) use plugin::{BackgroundTasks, BackgroundTasksPlugin, Route};
39
40/// Background tool execution settings (`BackgroundTasksConfig`). Tools are named by
41/// [`Tool::name`](crate::Tool::name); `*` matches every tool without an exact entry.
42#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
43pub struct BackgroundTasksConfig {
44    /// Wait for background work before an invocation returns. Defaults to `true`.
45    pub wait_for_completion: Option<bool>,
46    /// Tools whose execution mode the model selects. Defaults to `["*"]` unless `always` or
47    /// `never` holds `*`.
48    pub agentic: Option<Vec<String>>,
49    /// Tools that always run in the background.
50    pub always: Option<Vec<String>>,
51    /// Tools that never run in the background.
52    pub never: Option<Vec<String>>,
53    /// The most background tasks running at once. Defaults to 4.
54    pub max_concurrency: Option<usize>,
55    /// The timeout of one execution, in whole milliseconds. Defaults to none.
56    pub timeout: Option<Duration>,
57    /// Name of the tool the model calls to list, get or cancel background tasks
58    /// (`manageToolName`). Must not match another tool on the agent. The name is written into
59    /// conversation history, so keep it stable across a saved session. Defaults to
60    /// `manage_background_task`.
61    #[builder(into)]
62    pub manage_tool_name: Option<String>,
63}
64
65crate::types::toggle_from_config!(BackgroundTasksConfig);
66
67#[cfg(test)]
68mod tests;