Skip to content

Run tools in the background

Use background tasks when a tool takes time and the agent has other work it can do. The tool runs in the background, the agent receives a task ID, and its loop continues.

Background tasks are disabled by default in the SDK. Enable them with the background_tasksbackgroundTasks option on Agent. Strands harness enables them by default and always runs its subagent tool in the background.

The model decides whether to call a tool. An always policy controls how a tool call executes; it does not cause the call itself.

1 · DISPATCH 2 · CONTINUE 3 · DELIVERY requests a tool call queues the tool receipt with task ID next model call tool runs result ready delivers the result Model Agent Background task

Tool executors order the foreground tool calls in one model response. Background tasks use a separate queue, so the loop continues before those calls finish. Direct calls through agent.tool always execute in the foreground, even for a tool with an always policy.

This example simulates a slow report query. It always runs build_report in the background and keeps other tools in the foreground. Configure a model provider before running it; these examples use the default Amazon Bedrock provider.

import asyncio
from strands import Agent, tool
@tool
async def build_report(region: str) -> str:
"""Build an example sales report for a region."""
await asyncio.sleep(1)
return f"Example report for {region}: revenue grew 12%."
async def main() -> None:
agent = Agent(
tools=[build_report],
background_tasks={
"always": [build_report],
"never": ["*"],
"max_concurrency": 2,
"timeout": 30,
},
)
result = await agent.invoke_async(
"Build the north region report. While it runs, outline three "
"questions to ask about sales growth. Then summarize the report."
)
print(result)
asyncio.run(main())

Set background_tasks=TruebackgroundTasks: true to let the model choose background execution for all compatible tools. Pass a BackgroundTasksConfig object to choose tools, limits, and delivery behavior. Every option is optional; the defaults apply when you pass Truetrue or an empty object.

OptionDefaultMeaning
agentic["*"] (see note below)The model chooses foreground or background execution for matching tools.
always[]Matching tools run in the background.
never[]Matching tools run in the foreground.
wait_for_completionwaitForCompletionTruetrueWait for outstanding tasks before returning.
max_concurrencymaxConcurrency4Maximum simultaneous executions; a positive integer.
timeoutNo limitPer-execution limit: seconds in Python, milliseconds in TypeScript.
manage_tool_namemanageToolNamestrands_manage_background_taskManagement tool name.

Each policy accepts tool instances, registered tool names, or the wildcard "*". Exact matches take precedence over a wildcard. For example, always containing build_report plus never containing "*" backgrounds only the report tool. Putting the same selector in two policies is an error.

Tools eligible for model-selected execution

Section titled “Tools eligible for model-selected execution”

For an agentic tool, the SDK adds an optional _background_execution boolean to the schema shown to the model. For example, the model might request build_report with these arguments:

{ "region": "north", "_background_execution": true }

The SDK queues the call and removes the flag. Your tool receives:

{ "region": "north" }

Don’t declare _background_execution on your own tools.

Adding the flag requires an object input schema without a top-level $ref, allOf, anyOf, oneOf, not, if, then, or else. Naming an incompatible tool in agentic is an error; a wildcard match leaves it in the foreground.

Some tools always stay in the foreground: the background-task management tool, structured-output tools, context-management tools, and agents configured with delegate=Truedelegate: true. Don’t name them in agentic or always. The SDK rejects that configuration, or returns an error result for the call.

Tasks beyond the concurrency limit wait in submission order. With two execution slots and a four-second timeout:

2 SLOTS · TIMEOUT: 4 SECONDS Task A Task B Task C 0s 2s 4s 5s TIME working Completed; C can start working Timed out queued working Done C finishes after 3 seconds of execution. Its 2 seconds in the queue do not count.

A timeout produces failed with a timeout error. Python accepts any positive number of seconds; TypeScript requires a whole number of milliseconds no larger than 2_147_483_647.

These limits apply to one agent’s background work. Tools still share the host process and its resources. Use asynchronous I/O for waiting operations; CPU-bound JavaScript still blocks the event loop.

A task waits for a slot, runs, and reaches an outcome. An interrupt pauses it without holding a slot; supplying all responses queues a new attempt.

UNFINISHED TERMINAL SLOT OPENS INTERRUPT ALL RESPONSES CANCEL ANY queued Waiting for a slot working Tool executing input_required Paused; slot released completed Tool succeeded failed Error or timeout cancelled Cancellation recorded After all responses, the tool is queued to restart with a fresh timeout.

completed, failed, and cancelled are terminal states. Their outcomes stay listed until delivery.

The default management tool, strands_manage_background_task, lets the model or your application list, inspect, and cancel tasks.

modetask_idtaskIdResponse content
listNot required.A tasks array of task IDs, tool names, and statuses.
getRequired.Task metadata followed by available tool output.
cancelRequired.The task ID and resulting status.

Use the ID from the dispatch receipt or list. A get does not consume automatic delivery. After delivery, get or cancel for that ID returns an error result.

Task metadata includes task_idtaskId, tool_use_idtoolUseId, tool_nametoolName, status, and creation and update timestamps. The task ID identifies the background work and differs from the original tool-use ID.

The SDK delivers ready results before model calls; the model does not need to poll.

StageWhat you receive
DispatchA receipt with the task ID, tool name, and current status.
DeliveryA management-tool call with mode: "get", then a result with a metadata block first and the tool’s original output blocks after it, including images.
After deliveryThe task leaves the management tool’s list. Its result remains in conversation history, subject to normal context management.

By default, an invocation waits for outstanding tasks after the agent finishes its turn, then delivers their results and continues.

The management tool’s name must be unique on the agent and remain stable for the life of a saved session: it is written into conversation history.

Failed tasks include an error with a type and message:

Error typeCause
tool_errortoolErrorA tool error result, including an exception raised by the tool.
execution_errorexecutionErrorAn exception escaping the tool executor, such as a middleware failure.
timeoutThe execution exceeded its time limit.

Check the task’s status and error: a successful management-tool get can describe a failed task.

Set wait_for_completionwaitForCompletion to Falsefalse for detached execution. The invocation returns when the agent finishes its turn, even with work outstanding. Ready results are still delivered during the invocation.

Task completion does not start another invocation. Invoke the same agent again, either with a new user request or with await agent.invoke_async([])await agent.invoke([]). An empty invocation adds no user message. It delivers any ready results, then calls the model, whether or not a result was ready. Wait for the previous invocation to finish before starting another.

Keep the process alive while tasks run. In an asynchronous Python application, also keep the event loop the tool started on: closing that loop cancels the task.

List, inspect, and cancel from your application

Section titled “List, inspect, and cancel from your application”

This example starts a slow tool, inspects the tracked tasks, and cancels unfinished work. Direct management calls do not invoke the model. Setting

record_direct_tool_call=FalserecordDirectToolCall: false

also keeps those calls out of the conversation.

import asyncio
from strands import Agent, tool
@tool
async def build_report(region: str) -> str:
"""Build an example report after a simulated slow query."""
await asyncio.sleep(10)
return f"Example report for {region}: revenue grew 12%."
async def main() -> None:
agent = Agent(
tools=[build_report],
system_prompt="Report cancelled tasks without retrying them.",
background_tasks={
"always": [build_report],
"never": ["*"],
"wait_for_completion": False,
},
)
await agent.invoke_async(
"Start the north region report and tell me it has started."
)
manage = agent.tool.strands_manage_background_task
listing = manage(mode="list", record_direct_tool_call=False)
tasks = listing["content"][0]["json"]["tasks"]
for task in tasks:
print(manage(
mode="get",
task_id=task["task_id"],
record_direct_tool_call=False,
))
if task["status"] in {"queued", "working", "input_required"}:
manage(
mode="cancel",
task_id=task["task_id"],
record_direct_tool_call=False,
)
# Deliver any recorded outcomes to the agent.
print(await agent.invoke_async([]))
asyncio.run(main())

The task may finish before inspection, so an empty list is valid. Direct management calls with recording disabled are also allowed while an invocation is running. In Python, they are not allowed while the agent is paused on an interrupt; respond to the interrupt first.

Choose whether to stop one task, all background work, or just the current invocation:

ActionWhat stops
Management tool with mode: "cancel" and a task IDThat task.
agent.cancel()The current invocation; background tasks keep running.
agent.cancel(cancel_background_tasks=True)agent.cancel({ cancelBackgroundTasks: true })The current invocation and all queued, working, or input-required tasks.

Cancellation records cancelled and signals the tool to stop. A blocking function or external operation may still continue. Tools must check tool_context.cancel_signalcontext.cancelSignal or pass it to libraries that support cancellation. The signal is a threading.EventAbortSignal.

On an idle agent, plain agent.cancel() cancels the next invocation in Python and has no effect in TypeScript. Cancelling background tasks leaves the next invocation alone. If an invocation was only waiting for background tasks, cancellation returns its existing turn result; outstanding results arrive on the next invocation. See cancellation for the full contract.

A background tool can request input through tool_context.interrupt()context.interrupt(); execution middleware can also interrupt. Follow the interrupt and resume flow to supply a response for each interrupt.

The state diagram shows the pause and retry. The tool runs again from the beginning with earlier responses available. Put irreversible side effects after approval, or make them safe to repeat.

Where the interrupt originatesBehavior
A before-tool hookApproval happens in the foreground, before the task is submitted.
A child agent wrapped with Agent.as_tool()Agent.asTool(), or the subagent toolThe interrupt does not reach the parent. The task fails with an execution_errorexecutionError naming the interrupt. Keep the agent tool in the foreground if its child needs approval.

Background tools use tool execution middleware and lifecycle hooks:

What to observeWhere
DispatchThe before-tool hook.
Tool completionThe after-tool hook, with the actual result rather than the dispatch receipt.
Task status and finished resultsThe management tool. It cannot stream progress or send messages to running tasks.

Progress events are separate from the invocation’s event stream. In Python they go to the agent’s callback handler; in TypeScript they fire ToolStreamUpdateEvent hooks. These callbacks can overlap, so account for concurrent updates to shared application state.

A session manager or snapshot saves task metadata and undelivered results as part of agent state. A task update does not itself trigger a durable write.

Saved task stateAfter restoration
completed, failed, or cancelledThe saved outcome remains available for delivery.
queued, working, or input_requiredThe task becomes failed. The SDK does not resume its function or restart an external job.

For work that must survive a process restart, have your tool submit to a durable service and return that service’s job ID.

Loading a snapshot is rejected while the agent tracks any background tasks, including terminal but undelivered tasks. Finish or cancel the work and deliver its outcomes before loading another snapshot.