Repository navigation
How to gracefully stop an Agent mid-execution via message, allowing cleanup? #598
Replies: 2 comments
|
Calling agent.cancel() from the request that receives the stop message is the supported path. The method is documented as thread safe and can be called from another request handler. By default the loop stops at the next safe point: during model streaming, before a tool runs, during an MCP tool, or after a tool returns and before the next model call. Pass after_current_tools=True when the tool batch already requested should be allowed to finish. The result then has stop_reason "cancelled", and an optional message argument becomes the final assistant text. That call does not give the model a cleanup turn, and a plain Python tool that is already polling a subprocess keeps running until the tool function returns. After the invocation finishes the SDK clears the cancel flag, so the same agent can be invoked again with a short cleanup prompt against the messages it already has. A tool that starts a subprocess has to watch the cancel signal itself if you need that process stopped before the tool returns. |
Uh oh!
There was an error while loading. Please reload this page.
Hi!
I'm using the Strands to manage an agent workflow in my backend app.
Situation:
What I want:
Question:
Is there a recommended way to influence an agent mid-execution—e.g., by sending it a stop signal/message that it will process on its next agent loop?
If so, could you show a code example of the best practice for handling this?
All reactions