Skip to main content
ai-query provides a cancellation system inspired by JavaScript’s 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 an AbortSignal.

Methods

abort

Abort the signal, optionally with a reason.

Properties

signal

The signal controlled by this controller.

AbortSignal

A signal that can be checked for abort status.

Properties

aborted

True if abort() has been called.

reason

The abort reason, if provided.

Methods

throw_if_aborted

Raise AbortError if the signal is aborted.

timeout (static)

Create a signal that auto-aborts after the specified timeout.

wait

Wait until the signal is aborted. Useful for racing tasks.

add_listener

Add a callback to be called when aborted.

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

  1. Always handle AbortError - Wrap operations in try/except when using signals.
  2. Use timeout for safety - Prevent runaway operations with AbortSignal.timeout().
  3. Share signals across related operations - One abort cancels all.
  4. Clean up resources - Use try/finally to clean up when aborted.