Catalog PyPI
PACKAGE EXPLORERView in registry

ai2070-l0

PyPI

Reliability layer for AI/LLM streaming with retry, guardrails, and observability

aianthropicfallbackguardrailslitellmllmobservabilityopenaireliabilityresilienceretrystreamingtimeout
Versions collected1
Direct dependencies12From release 0.21.1
Last observed21 Oct, 09:45 UTC

README

Version 0.21.1 documentation

Rename note: This project was previously called L0-Python. The package/repository is being renamed to reliable-ai-streams-py. Existing imports remain supported. Install: pip install reliable-ai-streams-py

L0 - Deterministic Streaming Execution Substrate (DSES) for AI

The missing reliability and observability layer for all AI streams.

L0: The Missing AI Reliability Substrate

PyPI version Python versions Types Included Asyncio Native 1800+ Tests Apache 2.0 License

LLMs produce high-value reasoning over a low-integrity transport layer. Streams stall, drop tokens, reorder events, violate timing guarantees, and expose no deterministic contract.

This breaks retries. It breaks supervision. It breaks reproducibility. It makes reliable AI systems impossible to build on top of raw provider streams.

L0 is the deterministic execution substrate that fixes the transport - with guardrails designed specifically for the streaming layer: stream-neutral, pattern-based, loop-safe, and timing-aware.

The result: production-grade, integrity-preserving, deterministic AI streams you can finally build real systems on.

It works with OpenAI and LiteLLM (100+ providers including Anthropic, Cohere, Bedrock, Vertex, Gemini). Supports tool calls and provides full observability.

pip install ai2070-l0

Also available in TypeScript: @ai-2070/l0 npm install @ai2070/l0 - native implementation with full lifecycle and event signature parity.

Production-grade reliability. Just pass your stream. L0'll take it from here.

L0 includes 1,800+ tests covering all major reliability features.

   Any AI Stream                    L0 Layer                         Your App
 ─────────────────    ┌──────────────────────────────────────┐    ─────────────
                      │                                      │
   OpenAI / LiteLLM   │   Retry · Fallback · Resume          │      Reliable
   Custom Streams  ──▶│   Guardrails · Timeouts · Consensus  │─────▶ Output
                      │   Full Observability                 │
                      │                                      │
                      └──────────────────────────────────────┘
 ─────────────────                                                ─────────────
                           L0 = Token-Level Reliability

Features

FeatureDescription
🔁 Smart RetriesModel-aware retries with fixed-jitter backoff. Automatic retries for zero-token output, network stalls, and provider overloads.
🌐 Network ProtectionAutomatic recovery from dropped streams, slow responses, 429/503 load shedding, DNS errors, and partial chunks.
🔀 Model FallbacksAutomatically fallback to secondary models (e.g., GPT-4o → GPT-4o-mini → Claude) with full retry logic.
💥 Zero-Token/Stall ProtectionDetects when model produces nothing or stalls mid-stream. Automatically retries or switches to fallbacks.
📍 Last-Known-Good Token Resumptioncontinue_from_last_good_token resumes from the last checkpoint on timeout or failure. No lost tokens.
🧠 Drift DetectionDetects repetition, stalls, and format drift before corruption propagates.
🧱 Structured OutputGuaranteed-valid JSON with Pydantic. Auto-corrects missing braces, commas, and markdown fences.
📋 Pydantic Validation ModelsAll L0 types available as Pydantic models for runtime validation, JSON serialization, and schema generation via l0.pydantic.
🩹 JSON Auto-HealingAutomatic correction of truncated or malformed JSON (missing braces, brackets, quotes), and repair of broken Markdown code fences.
🛡️ GuardrailsJSON, Markdown, and pattern validation with fast streaming checks. Delta-only checks run sync; full-content scans defer to async.
⚡ Race: Fastest-Model WinsRun multiple models or providers in parallel and return the fastest valid stream. Ideal for ultra-low-latency chat.
🌿 Parallel: Fan-Out / Fan-InStart multiple streams simultaneously and collect structured or summarized results. Perfect for agent-style multi-model workflows.
🧩 Consensus: Agreement Across ModelsCombine multiple model outputs using unanimous, majority, or best-match consensus. Guarantees high-confidence generation.
🔔 Lifecycle Callbackson_start, on_complete, on_error, on_event, on_violation, on_retry, on_fallback, on_tool_call - full observability into every stream phase.
📡 Streaming-First RuntimeThin, deterministic wrapper with unified event types (token, error, complete) for easy UIs.
📼 Central Event BusFull observability into every stream phase via on_event callback with 25+ structured event types.
🔌 Custom Adapters (BYOA)Bring your own adapter for any LLM provider. Built-in adapters for OpenAI and LiteLLM.
📦 Raw Chunk AccessAccess original provider chunks (e.g., OpenAI's ChatCompletionChunk) via stream.raw() for provider-specific processing.
⚡ Pure asyncioNo compatibility layers (no anyio/trio). Native Python async for full determinism and performance.
🔧 Own Retry LogicNo external dependencies (no tenacity). L0 controls all retry behavior for predictable execution.
📝 Type-SafeFull type hints with py.typed marker. Passes mypy strict mode.
📦 Minimal DependenciesOnly httpx, pydantic, orjson, typing-extensions, uuid6. No heavy abstractions.
🚀 Nvidia Blackwell-ReadyOptimized for 1000+ tokens/s streaming. Ready for next-gen GPU inference speeds.
🧪 Battle-Tested1,800+ unit tests and 100+ integration tests validating real streaming, retries, and advanced behavior.

Know what you're doing? Skip the tutorial

Quick Start

import asyncio
from openai import AsyncOpenAI
import l0

async def main():
    # Wrap the client once - L0 reliability is automatic
    client = l0.wrap(AsyncOpenAI())

    # Use normally - no lambdas needed!
    response = await client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Hello!"}],
        stream=True,
    )

    # Stream with L0 events
    async for event in response:
        if event.is_token:
            print(event.text, end="", flush=True)

    # Or read all at once
    text = await response.read()

asyncio.run(main())

With Configuration

import l0
from openai import AsyncOpenAI

# Configure once, use everywhere
client = l0.wrap(
    AsyncOpenAI(),
    guardrails=l0.Guardrails.recommended(),
    retry=l0.Retry(attempts=5),
    timeout=l0.Timeout(initial_token=10000, inter_token=30000),
    continue_from_last_good_token=True,  # Resume from checkpoint on failure
)

response = await client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}],
    stream=True,
)

See Also: API.md for all options, ADVANCED.md for full examples

With LiteLLM (100+ Providers)

import asyncio
import litellm
import l0

async def main():
    # For LiteLLM, use l0.run() with a factory function
    result = await l0.run(
        stream=lambda: litellm.acompletion(
            model="anthropic/claude-3-haiku-20240307",
            messages=[{"role": "user", "content": "Hello!"}],
            stream=True,
        ),
        guardrails=l0.Guardrails.recommended(),
    )

    # Read full text
    text = await result.read()
    print(text)

asyncio.run(main())

Structured Output with Pydantic

from pydantic import BaseModel
import l0

class UserProfile(BaseModel):
    name: str
    age: int
    occupation: str

result = await l0.structured(
    schema=UserProfile,
    stream=lambda: client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Generate a fictional person as JSON"}],
        stream=True,
    ),
    auto_correct=True,  # Fix trailing commas, missing braces, markdown fences
)

print(result.name)  # "Alice"
print(result.age)   # 32

Lifecycle Events

import l0

result = await l0.run(
    stream=lambda: client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        stream=True,
    ),
    on_stream_event=lambda event: (
        print(event.text, end="") if event.is_token else
        print(f"\nError: {event.error}") if event.is_error else
        print("\nDone!") if event.is_complete else None
    ),
)

Fallback Models & Providers

import l0

result = await l0.run(
    # Primary model
    stream=lambda: client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        stream=True,
    ),
    # Fallbacks: tried in order if primary fails
    fallbacks=[
        lambda: client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": prompt}],
            stream=True,
        ),
        lambda: litellm.acompletion(
            model="anthropic/claude-3-haiku-20240307",
            messages=[{"role": "user", "content": prompt}],
            stream=True,
        ),
    ],
    on_fallback=lambda index, reason: print(f"Switched to fallback {index}"),
)

Parallel Execution

import l0

prompts = ["Name a fruit", "Name a color", "Name an animal"]

result = await l0.parallel(
    tasks=[
        lambda p=p: l0.run(
            stream=lambda: client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[{"role": "user", "content": p}],
                stream=True,
            ),
        )
        for p in prompts
    ],
    concurrency=3,
)

for prompt, stream in zip(prompts, result.results):
    text = await stream.read()
    print(f"{prompt}: {text.strip()}")

Pydantic Validation Models

L0 provides Pydantic models for all its types, enabling runtime validation, JSON serialization, and schema generation:

from l0.pydantic import StateModel, RetryModel, DriftResultModel

# Validate external data
state = StateModel(content="Hello", token_count=5, completed=True)

# Serialize to JSON
json_data = state.model_dump_json()

# Generate JSON schema for documentation or APIs
schema = StateModel.model_json_schema()

All L0 types have corresponding Pydantic models: StateModel, RetryModel, TimeoutModel, ConsensusResultModel, DriftResultModel, MetricsSnapshotModel, and more.

Philosophy

  • No magic - Everything is explicit and predictable
  • Streaming-first - Built for real-time token delivery
  • Signals, not rewrites - Guardrails detect issues, don't modify output
  • Model-agnostic - Works with any provider via adapters
  • Pure asyncio - No compatibility layers, native Python async
  • Own retry logic - No tenacity, full control over behavior

Performance

Benchmarks on Apple M1 Max, Python 3.13, zero-delay mock streams (2000 tokens):

ScenarioTokens/sAvg DurationTTFT
Baseline (raw streaming)1,406,3901.42 ms0.02 ms
L0 Core (no features)596,0863.36 ms0.10 ms
L0 + JSON Guardrail557,5503.59 ms0.09 ms
L0 + All Guardrails547,9913.65 ms0.09 ms
L0 + Drift Detection114,93517.41 ms0.10 ms
L0 Full Stack114,89517.43 ms0.10 ms

Full stack = JSON + Markdown + zero-output guardrails + drift detection + checkpointing. See BENCHMARKS.md for details.

Documentation

GuideDescription
QUICKSTART.mdGet started in 5 minutes
ADVANCED.mdAdvanced usage and full examples
API.mdComplete API reference
GUARDRAILS.mdGuardrails and validation
STRUCTURED_OUTPUT.mdStructured output guide
CONSENSUS.mdMulti-generation consensus
DETERMINISTIC_LIFECYCLE.mdLifecycle specification and events
NETWORK_ERRORS.mdNetwork error handling
ERROR_HANDLING.mdError handling guide
CUSTOM_ADAPTERS.mdBuild your own adapters
DOCUMENT_WINDOWS.mdChunking and processing long documents
EVENT_SOURCING.mdRecord/replay, audit trails
MONITORING.mdOpenTelemetry and Sentry integrations
FORMATTING.mdContext, memory, output, and tool formatting
PARALLEL_OPERATIONS.mdParallel, race, batch, and pool operations
MULTIMODAL.mdImage, audio, video, and multimodal adapters
PERFORMANCE.mdPerformance tuning guide

Installation

# Basic installation
pip install ai2070-l0

# With OpenAI support
pip install ai2070-l0[openai]

# With LiteLLM (100+ providers)
pip install ai2070-l0[litellm]

# With OpenTelemetry
pip install ai2070-l0[otel]

# With Sentry
pip install ai2070-l0[sentry]

# Development (dev is a dependency-group, not a pip extra)
uv sync --group dev

Or with uv:

uv add ai2070-l0
uv add ai2070-l0 --extra openai
uv add ai2070-l0 --extra litellm

Dependencies

PackagePurpose
httpxHTTP client
pydanticSchema validation
orjsonFast JSON
uuid6UUIDv7 for stream IDs
typing-extensionsType hints

Optional Dependencies

ExtraPackages
openaiopenai>=2.0,<3.0
litellmlitellm>=1.40
otelopentelemetry-api, opentelemetry-sdk, opentelemetry-instrumentation-httpx
sentrysentry-sdk
observabilityotel + sentry combined
speeduvloop (Unix only)
devpytest, pytest-asyncio, pytest-cov, mypy, ruff

License

Apache-2.0

Downloads & popularity

Awaiting observations

No metric observations yet

Download counts and popularity will appear here as the collector receives them.

Versions 1

Collected releases
VersionPublishedDirect dependenciesOpen version
0.21.129 Jun 202612

Package advisories

0
No matching advisories collected

This describes our collected data; it is not a security assessment.

Repository

PENDING
ai-2070/l0

Shared repository data · GitHub

License detected in repository
Not collected

Metadata history

Meaningful changes
Current collected state Current

Observed since 21 Oct, 09:45 UTC

No superseded metadata states collected. Unchanged observations do not create new revisions.

Record identity

package:c4453ae69477121d84ca32950ee48ada3c581421a093c6ca6e4325fba2f927cf