Home · Developers · Guides · AI Streaming System

Intelligence

AI Streaming System

SSE token streaming contract

The AI Streaming System provides enhanced streaming capabilities for AI provider responses, including token counting, progress callbacks, cancellation, and state management.

Overview

The streaming system enhances the basic streaming functionality provided by AI providers with additional middleware capabilities:

  • Token Counting: Real-time token counting during streaming
  • Progress Callbacks: Callbacks for streaming progress updates
  • Cancellation: Ability to cancel in-progress streaming operations
  • State Management: Tracking of streaming state (idle, connecting, streaming, paused, completed, error, cancelled)
  • Statistics: Collection of streaming statistics (tokens per second, characters per second)
  • Chunked Streaming: Support for chunked streaming of large responses

Architecture

Provider Stream
     ↓
StreamingMiddleware
     ↓
Enhanced Stream (StreamingToken)
     ↓
StreamingAggregator (optional)
     ↓
Complete Response

Components

StreamingMiddleware

The main middleware component that enhances provider streams with additional capabilities.

from novacoder.ai.streaming import StreamingMiddleware, StreamingConfig

# Create middleware with custom configuration
config = StreamingConfig(
    enable_token_counting=True,
    enable_progress_callbacks=True,
    chunk_size=1,
    timeout=30.0,
    max_retries=3,
    enable_cancellation=True,
    enable_pause_resume=False
)

middleware = StreamingMiddleware(config)

StreamingToken

Enhanced token with metadata:

@dataclass
class StreamingToken:
    content: str
    token_index: int
    timestamp: datetime
    metadata: dict[str, Any]

StreamingConfig

Configuration for streaming operations:

@dataclass
class StreamingConfig:
    enable_token_counting: bool = True
    enable_progress_callbacks: bool = False
    chunk_size: int = 1
    timeout: float = 30.0
    max_retries: int = 3
    enable_cancellation: bool = True
    enable_pause_resume: bool = False

StreamingStats

Statistics for streaming operations:

@dataclass
class StreamingStats:
    total_tokens: int
    total_characters: int
    start_time: datetime
    end_time: datetime | None
    tokens_per_second: float
    characters_per_second: float
    error_count: int

Usage Examples

Basic Streaming Enhancement

from novacoder.ai.streaming import StreamingMiddleware
from novacoder.ai.provider import ChatMessage
import asyncio

async def stream_with_enhancement():
    middleware = StreamingMiddleware()
    
    # Get base stream from provider
    provider = manager.load("openai")
    messages = [ChatMessage(role="user", content="Hello")]
    base_stream = provider.stream(messages)
    
    # Enhance the stream
    enhanced_stream = middleware.enhance_stream(base_stream, messages)
    
    # Process enhanced tokens
    async for token in enhanced_stream:
        print(f"Token {token.token_index}: {token.content}")
        print(f"Rate: {middleware.get_stats().tokens_per_second:.2f} tokens/sec")

Progress Callbacks

def progress_callback(token: StreamingToken):
    print(f"Progress: {token.token_index} tokens")

def completion_callback(stats: StreamingStats):
    print(f"Completed: {stats.total_tokens} tokens in {stats.tokens_per_second:.2f} tokens/sec")

middleware = StreamingMiddleware(StreamingConfig(enable_progress_callbacks=True))
middleware.set_progress_callback(progress_callback)
middleware.set_completion_callback(completion_callback)

Cancellation

async def stream_with_cancellation():
    middleware = StreamingMiddleware(StreamingConfig(enable_cancellation=True))
    
    # Start streaming
    enhanced_stream = middleware.enhance_stream(base_stream, messages)
    
    # Cancel after some time
    asyncio.create_task(cancel_after_delay(middleware, 5.0))
    
    async for token in enhanced_stream:
        if middleware.get_state() == StreamingState.CANCELLED:
            print("Stream was cancelled")
            break
        print(token.content)

async def cancel_after_delay(middleware, delay):
    await asyncio.sleep(delay)
    middleware.cancel()

Pause/Resume

async def stream_with_pause_resume():
    config = StreamingConfig(enable_pause_resume=True)
    middleware = StreamingMiddleware(config)
    
    enhanced_stream = middleware.enhance_stream(base_stream, messages)
    
    async for token in enhanced_stream:
        print(token.content)
        
        # Pause after 10 tokens
        if token.token_index == 10:
            middleware.pause()
            await asyncio.sleep(2.0)
            middleware.resume()

Streaming Aggregation

from novacoder.ai.streaming import StreamingAggregator

async def aggregate_stream():
    middleware = StreamingMiddleware()
    aggregator = StreamingAggregator()
    
    enhanced_stream = middleware.enhance_stream(base_stream, messages)
    
    # Aggregate tokens into complete response
    complete_response = await aggregator.aggregate(enhanced_stream)
    print(f"Complete response: {complete_response}")
    
    # Get partial response during streaming
    partial = aggregator.get_partial()
    print(f"Partial so far: {partial}")

Integration with Providers

The streaming middleware works with any provider that implements the stream method:

from novacoder.ai.manager import ProviderManager

manager = ProviderManager()
provider = manager.load("openai")

# Use middleware with any provider
middleware = StreamingMiddleware()
enhanced_stream = middleware.enhance_stream(
    provider.stream(messages),
    messages
)

State Management

The streaming middleware tracks the current state:

from novacoder.ai.streaming import StreamingState

state = middleware.get_state()
# StreamingState.IDLE, CONNECTING, STREAMING, PAUSED, COMPLETED, ERROR, CANCELLED

Statistics

Access streaming statistics:

stats = middleware.get_stats()
print(f"Total tokens: {stats.total_tokens}")
print(f"Tokens per second: {stats.tokens_per_second:.2f}")
print(f"Characters per second: {stats.characters_per_second:.2f}")
print(f"Error count: {stats.error_count}")

Error Handling

The streaming middleware includes error callbacks:

def error_callback(error: Exception):
    print(f"Streaming error: {error}")

middleware.set_error_callback(error_callback)

Best Practices

  1. Enable Cancellation: Always enable cancellation for long-running streams
  2. Use Progress Callbacks: For UI applications, use progress callbacks to update the interface
  3. Monitor Statistics: Track streaming statistics to detect performance issues
  4. Handle Timeouts: Set appropriate timeout values based on expected response sizes
  5. Use Aggregation: Use StreamingAggregator when you need the complete response

Performance Considerations

  • Token Counting: Adds minimal overhead to streaming operations
  • Progress Callbacks: May impact performance if callback logic is heavy
  • Chunk Size: Larger chunk sizes can improve performance but reduce granularity
  • Memory Usage: Streaming uses constant memory regardless of response size

Configuration

Configure streaming behavior:

# High-performance configuration
config = StreamingConfig(
    enable_token_counting=False,  # Disable for maximum performance
    enable_progress_callbacks=False,
    chunk_size=10,  # Larger chunks
    timeout=60.0,
    enable_cancellation=True
)

# Feature-rich configuration
config = StreamingConfig(
    enable_token_counting=True,
    enable_progress_callbacks=True,
    chunk_size=1,  # Token-level granularity
    timeout=30.0,
    enable_cancellation=True,
    enable_pause_resume=True
)

Integration with AIService

The streaming system is integrated into the AIService for seamless use:

from novacoder.ai.service import AIService
from novacoder.ai.provider import ChatMessage

ai_service = AIService()
ai_service.initialize()

# Stream with circuit breaker protection
messages = [ChatMessage(role="user", content="Hello")]
async for token in ai_service.stream_chat(messages, task="chat"):
    print(token)

The stream_chat() method includes:

  • Circuit Breaker Protection: Checks circuit breaker state before streaming
  • Error Handling: Records failures and attempts recovery
  • Fallback Support: Automatically switches to fallback providers on failure

API Endpoints

GET /api/stream

Stream AI tokens as server-sent events (EventSource compatible).

Query Parameters:

  • message: The message to send
  • provider: The AI provider to use (optional)
  • model: The model to use (optional)

Response: Server-sent events with token chunks

POST /api/stream

Stream AI tokens as server-sent events with JSON payload.

Request Body:

{
  "message": "Hello",
  "provider": "openai",
  "model": "gpt-4"
}

Response: Server-sent events with token chunks

GET /api/ai/stream-metrics

Sanitized streaming telemetry (no prompt/response content, no credentials).

Response:

{
  "success": true,
  "data": {
    "sample_count": 7,
    "ttft_ms":  {"p50": 5400.6, "p95": 11562.3, "p99": 11562.3, "mean": 5930.5},
    "total_ms": {"p50": 13134.4, "p95": 76166.7, "mean": null},
    "prompt_ms_mean": 1.4,
    "tok_per_s_mean": 5.4,
    "errors": 0,
    "cancellations": 1,
    "recent": [ {"source": "agent", "ttft_ms": 718.4, "tokens": 17, "cancelled": true, ...} ]
  }
}

Ring buffer holds the last 500 requests. source is agent (default /api/stream path) or stream (direct provider path); prompt_ms is server-side message assembly, on this stack it is ~1 ms, so ttft_ms − prompt_ms is provider prefill+queueing.

Performance Notes (2026-10)

  • Provider clients are pooled. AIProvider._client_ctx(timeout) yields a shared httpx.AsyncClient, use it instead of async with httpx.AsyncClient(...) in provider code so TCP/TLS is not re-established per request.
  • Ollama requests hit /api/chat (native chat template) with a sticky fallback to /api/generate on 404; keep_alive=-1 keeps the model resident.
  • History context sent to the model is bounded (_HISTORY_CONTEXT_MESSAGES = 4 in routes_ai_2.py); _chat_history itself is capped at 500 entries.
  • Frontend renders are rAF-batched, Chat.tsx, AiPanel.tsx, Runtime.tsx coalesce token events into ≤1 React render per frame.
  • Ollama -np 1: one inference slot, concurrent requests serialize. Never run two bench_chat.py instances at once; queueing inflates TTFT.
  • Adaptive concurrency gate (ai/concurrency.py::AdaptiveLimiter): AIService.chat/stream_chat and RuntimeService.stream share one FIFO slot gate bounded by model.max_concurrent_streams (default 4). The effective limit sheds 4→2→1 under CPU/memory pressure (psutil, non-blocking) and recovers automatically. Wait time is recorded into stream-metrics.queue (inflight, queued, effective_limit, wait_ms_p50/p95). The slot is held per provider attempt, retry backoff never starves the gate.
  • Rolling history digest: the 12 turns just beyond the 4-message context window are injected as a compact system digest (_HISTORY_DIGEST_TURNS/_HISTORY_DIGEST_CHARS in routes_ai_2.py), older context is compressed, not dropped.
  • Benchmark: .venv/bin/python scripts/bench_chat.py --runs 2 --out reports/ai-chat-performance/run.json. System bench (boot/parallel/API-under-load/RSS): .venv/bin/python scripts/bench_system.py. Regression scanner: .venv/bin/python -m scan --only chat_performance. Audits: backups/reports_archive_2026-10-13/ai-chat-performance/33…35 (archived; consolidated into reports/NOVACODER_MASTER_DEVELOPMENT_ROADMAP.md).

Source: wiki/ai-streaming.md · rendered 2026-11-10