sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[FEATURE] Add support of CancellationToken

Open osdemah opened this issue 1 year ago • 5 comments

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

  1. stop/cancel API for the AI app
  2. complex multi-agent systems where the orchestrator agent can decide to stop the child agents

Alternatives Solutions

No response

Additional Context

No response

osdemah avatar May 22 '25 15:05 osdemah

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

zastrowm avatar May 28 '25 13:05 zastrowm

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

jer96 avatar Jun 19 '25 18:06 jer96

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 avatar Mar 10 '26 13:03 pgrayy

@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.

tahitimoon avatar Mar 18 '26 07:03 tahitimoon

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.

pgrayy avatar Mar 19 '26 19:03 pgrayy