# Useful but Little-Known Features of OpenAI Agent SDK
๐ Did you know you can stop a streaming agent run mid-generation with a single method call?
`RunResultStreaming.cancel()` lets you safely cancel a streaming run on demand.
๐ Title: RunResultStreaming.cancel()
๐ URL:
๐งฉ Overview
The `cancel()` method on `RunResultStreaming` stops a streaming agent run either immediately or after the current turn completes. After calling `cancel()`, you must continue consuming the `stream_events()` async iterator so that cancellation and cleanup finish correctly. The `is_complete` property indicates whether the run reached its terminal state, and summary properties like `final_output` and `interruptions` finalize after the last token.
๐ How to use it
```python
from agents import Agent, Runner
agent = Agent(name="Assistant", instructions="You are helpful.")
result = "Write a long essay...")
async for event in
# User pressed the cancel button
if user_cancelled():
result.cancel()
# Keep consuming for cleanup
continue
# Normal event processing
handle_event(event)
# Check state after cleanup completes
print(f"Complete: {")
```
๐ Building it into production
ใปWire a "Stop" button in your chat UI to trigger user-initiated cancellation
ใปAlways consume `stream_events()` to completion after cancel to prevent resource leaks
ใปCheck `is_complete` to distinguish cancelled runs from normal completions in your logs
ใปUse cancellation for cost management by cutting off unnecessary token generation early
๐ก Use cases
๐ Implementing a "Stop generating" button in chatbots
๐ฐ Reducing token costs on overly long responses
โฑ Timeout-based automatic cancellation
๐ Aborting a previous run when the user changes their question
โ ๏ธ Watch out
Skipping `stream_events()` consumption after `cancel()` prevents proper resource cleanup. Always exhaust the iterator. Depending on timing, the current turn may complete before the cancellation takes effect.
โจ With cancel(), give users full control over responsive streaming experiences.
#
OpenAIAgentSDK# #
AIAgent#