[FEATURE] Add support of CancellationToken
Problem Statement
As we're refactoring and adding asyncio support, it'd be great to add support of a "CancellationToken" throughout the SDK. This allows for convenient support of features like adding a stop/cancel button to the AI app. Sample implementation in autogen can be found here.
Proposed Solution
- requirement for this feature is to have asyncio support.
- Add CancellationToken to the agent entrypoint and pass it throughout the sdk (sample reference).
- Link the futures to the token.
Use Case
- stop/cancel API for the AI app
- complex multi-agent systems where the orchestrator agent can decide to stop the child agents
Alternatives Solutions
No response
Additional Context
No response
We will be exploring this as part of the async iterator support.
At first glance I think a lot of cancellation use cases can be solved by async iterators - e.g. just stop yielding - but where async iterators are not used (tool calls for instance) I think a cancellation-token would come into play.
Including this in #129 for design/exploration
Adding a comment in relation to #218 as the A2A protocol supports the notion of cancelling requests which may be relevant in the development of this feature. https://google-a2a.github.io/A2A/latest/specification/#74-taskscancel
New Agent.cancel() method has been added as part of https://github.com/strands-agents/sdk-python/pull/1772. The remaining work is to document.
@pgrayy
https://github.com/strands-agents/sdk-python/pull/1772 This is a really cool feature.
I tested it as soon as the new version was released.
However, I noticed an issue with the token usage statistics when a request is canceled.
I did a quick test and found that after cancellation, the reported token count is inaccurate. It doesn’t include the size of each prompt, and it also misses the tokens that have already been generated. Right now, it seems to be counting only a very small portion of the total.
Normal output without interruption Total: 12087 Input: 11699 Output: 388
Interrupted near the end of output Total: 35 Input: 0 Output: 35
Accurate token statistics would be very helpful for billing-related applications.
Docs are released at https://strandsagents.com/docs/user-guide/concepts/agents/agent-loop/#cancellation.
@tahitimoon this is expected behavior and is documented. Models will send their usage payloads at the end of stream. Consequently, if a user cancels mid stream, they miss out on the usage event.