AbortController and AbortSignal. This works with all async operations: generate_text, stream_text, embed, embed_many, and Agent.chat/Agent.stream.
Abort actively cancels in-flight provider requests, streaming reads, retry sleeps, embeddings, and tool calls when they are running in cancellable asyncio code. CPU-bound synchronous tools cannot be interrupted mid-function; they should periodically check the signal or run in a cancellable worker.
Quick Start
AbortController
Creates and controls anAbortSignal.
Methods
abort
Properties
signal
AbortSignal
A signal that can be checked for abort status.Properties
aborted
abort() has been called.
reason
Methods
throw_if_aborted
AbortError if the signal is aborted.
timeout (static)
wait
add_listener
AbortError
Exception raised when an operation is aborted.Usage Examples
Abort generate_text
Abort stream_text
Abort Agent.chat
Abort Agent.stream
Abort embed_many
Timeout Helper
Multiple Operations with Same Signal
User-Initiated Abort (WebSocket)
Best Practices
- Always handle AbortError - Wrap operations in try/except when using signals.
-
Use timeout for safety - Prevent runaway operations with
AbortSignal.timeout(). - Share signals across related operations - One abort cancels all.
- Clean up resources - Use try/finally to clean up when aborted.