@ai2070/l0

中文文档
0.26.1发布于 2026/06/29Apache-2.0TypeScriptESM + CJS零依赖近 30 天下载 1.4万

L0: The Missing Reliability Substrate for AI

此软件包已被标记为弃用

Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

原始使用文档
文档目录18 节
  1. The missing reliability and observability layer for all AI …
  2. Features
  3. Quick Start
  4. With Vercel AI SDK: Minimal Usage
  5. Vercel AI SDK: With Reliability
  6. With OpenAI SDK
  7. With Mastra AI
  8. Structured Output with Zod
  9. Lifecycle Events
  10. Fallback Models & Providers
  11. Parallel Execution
  12. Pipe: Streaming Pipelines
  13. Philosophy
  14. Zod Validation Schemas
  15. Performance
  16. Documentation
  17. Support
  18. License

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

L0 - Deterministic Streaming Execution Substrate (DSES) for AI

The missing reliability and observability layer for all AI streams.

L0: The Missing AI Reliability Substrate

npm version minzipped size install size Types Included CI status 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, Vercel AI SDK, Mastra AI, and custom adapters. Supports multimodal streams, tool calls, and provides full deterministic replay.

npm install @ai2070/l0

Also available in Python: @ai-2070/reliable-ai-streams-py uv add reliable-ai-streams-py - native implementation with full lifecycle and event signature parity.

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

L0 includes 3,000+ tests covering all major reliability features.

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

Upcoming versions:

  • 1.0.0 - API freeze

Features

FeatureDescription
🔁 Smart RetriesModel-aware retries with fixed-jitter backoff. Automatic retries for zero-token output, network stalls, SSE disconnects, and provider overloads.
🌐 Network ProtectionAutomatic recovery from dropped streams, slow responses, backgrounding, 429/503 load shedding, DNS errors, and partial chunks.
🔀 Model FallbacksAutomatically fallback to secondary models (e.g., 4o → 4o-mini → Claude/Gemini) 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 ResumptionWhen a stream interrupts, L0 resumes generation from the last structurally valid token (Opt-in).
🧠 Drift DetectionDetects tone shifts, duplicated sentences, entropy spikes, markdown collapse, and meta-AI patterns before corruption.
🧱 Structured OutputGuaranteed-valid JSON with Zod (v3/v4), Effect Schema, or JSON Schema. Auto-corrects missing braces, commas, and markdown fences.
🩹 JSON Auto-Healing + Markdown Fence RepairAutomatic correction of truncated or malformed JSON (missing braces, brackets, quotes), and repair of broken Markdown code fences. Ensures clean extraction of structured data from noisy LLM output.
🛡️ GuardrailsJSON, Markdown, LaTeX, and pattern validation with fast/slow path execution. Delta-only checks run sync; full-content scans defer to async to never block streaming.
⚡ Race: Fastest-Model WinsRun multiple models or providers in parallel and return the fastest valid stream. Ideal for ultra-low-latency chat and high-availability systems.
🌿 Parallel: Fan-Out / Fan-InStart multiple streams simultaneously and collect structured or summarized results. Perfect for agent-style multi-model workflows.
🔗 Pipe: Streaming PipelinesCompose multiple streaming steps (e.g., summarize → refine → translate) with safe state passing and guardrails between each stage.
🧩 Consensus: Agreement Across ModelsCombine multiple model outputs using unanimous, weighted, or best-match consensus. Guarantees high-confidence generation for safety-critical tasks.
📄 Document WindowsBuilt-in chunking (token, paragraph, sentence, character). Ideal for long documents, transcripts, or multi-page processing.
🎨 Formatting HelpersExtract JSON/code from markdown fences, strip thinking tags, normalize whitespace, and clean LLM output for downstream processing.
📊 MonitoringBuilt-in integrations with OpenTelemetry and Sentry for metrics, tracing, and error tracking.
🔔 Lifecycle CallbacksonStart, onToken, onEvent, onCheckpoint, onViolation, onDrift, onTimeout, onRetry, onFallback, onResume, onToolCall, onAbort, onError, onComplete - full observability into every stream phase.
📡 Streaming-First RuntimeThin, deterministic wrapper over streamText() with unified event types (token, error, complete) for easy UIs.
📼 Atomic Event LogsRecord every token, retry, fallback, and guardrail check as immutable events. Full audit trail for debugging and compliance.
🔄 Byte-for-Byte ReplaysDeterministically replay any recorded stream to reproduce exact output. Perfect for testing, and time-travel debugging.
⛔ Safety-First DefaultsContinuation off by default. Structured objects never resumed. No silent corruption. Integrity always preserved.
⚡ Tiny & Explicit21KB gzipped core. Tree-shakeable with subpath exports (/core, /structured, /consensus, /parallel, /window). No frameworks, no heavy abstractions.
🔌 Custom Adapters (BYOA)Bring your own adapter for any LLM provider. Built-in adapters for Vercel AI SDK, OpenAI, and Mastra.
🖼️ Multimodal SupportBuild adapters for image/audio/video generation (FLUX.2, Stable Diffusion, Veo 3, CSM). Progress tracking, data events, and state management for non-text outputs.
🚀 Nvidia Blackwell-ReadyOptimized for 1000+ tokens/s streaming. Ready for next-gen GPU inference speeds.
🧪 Battle-Tested3,000+ unit tests and 250+ integration tests validating real streaming, retries, and advanced behavior.

Know what you're doing? Skip the tutorial

Quick Start

With Vercel AI SDK: Minimal Usage

import { l0, recommendedGuardrails, recommendedRetry } from "@ai2070/l0";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

const result = await l0({
  // Primary model stream
  stream: () =>
    streamText({
      model: openai("gpt-5-mini"),
      prompt,
    }),
});

// Read the stream
for await (const event of result.stream) {
  if (event.type === "token") process.stdout.write(event.value);
}

Vercel AI SDK: With Reliability

import { l0, recommendedGuardrails, recommendedRetry } from "@ai2070/l0";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

const result = await l0({
  stream: () => streamText({ model: openai("gpt-4o"), prompt }),
  fallbackStreams: [() => streamText({ model: openai("gpt-4o-mini"), prompt })],

  // Optional: Content-agnostic, text-based guardrails
  guardrails: recommendedGuardrails,

  // Optional: Retry configuration, default as follows
  retry: {
    attempts: 3, // LLM errors only
    maxRetries: 6, // Total (LLM + network)
    baseDelay: 1000,
    maxDelay: 10000,
    backoff: "fixed-jitter", // "exponential" | "linear" | "fixed" | "full-jitter"
  },
  // Or use presets:
  // minimalRetry       // { attempts: 2, maxRetries: 4, backoff: "linear" }
  // recommendedRetry   // { attempts: 3, maxRetries: 6, backoff: "fixed-jitter" }
  // strictRetry        // { attempts: 3, maxRetries: 6, backoff: "full-jitter" }
  // exponentialRetry   // { attempts: 4, maxRetries: 8, backoff: "exponential" }

  // Optional: Timeout configuration, default as follows
  timeout: {
    initialToken: 5000, // 5s to first token
    interToken: 10000, // 10s between tokens
  },

  onError: (error, willRetry) => console.log(`Error: ${error.message}`),
});

for await (const event of result.stream) {
  if (event.type === "token") process.stdout.write(event.value);
}

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

With OpenAI SDK

import OpenAI from "openai";
import { l0, openaiStream, recommendedGuardrails } from "@ai2070/l0";

const openai = new OpenAI();

const result = await l0({
  stream: openaiStream(openai, {
    model: "gpt-4o",
    messages: [{ role: "user", content: "Generate a haiku about coding" }],
  }),
  guardrails: recommendedGuardrails,
});

for await (const event of result.stream) {
  if (event.type === "token") process.stdout.write(event.value);
}

With Mastra AI

import { Agent } from "@mastra/core/agent";
import { l0, mastraStream, recommendedGuardrails } from "@ai2070/l0";

const agent = new Agent({
  name: "haiku-writer",
  instructions: "You are a poet who writes haikus",
  model: "openai/gpt-4o",
});

const result = await l0({
  stream: mastraStream(agent, "Generate a haiku about coding"),
  guardrails: recommendedGuardrails,
});

for await (const event of result.stream) {
  if (event.type === "token") process.stdout.write(event.value);
}

Structured Output with Zod

import { structured } from "@ai2070/l0";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";

const schema = z.object({
  name: z.string(),
  age: z.number(),
  occupation: z.string(),
});

const result = await structured({
  schema,
  stream: () =>
    streamText({
      model: openai("gpt-4o-mini"),
      prompt:
        "Generate a fictional person as JSON with name, age, and occupation",
    }),
  autoCorrect: true, // Fix trailing commas, missing braces, markdown fences
});

console.log(result.data); // { name: "Alice", age: 32, occupation: "Engineer" }

Lifecycle Events

import { l0 } from "@ai2070/l0";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

const result = await l0({
  stream: () => streamText({ model: openai("gpt-4o"), prompt }),

  onEvent: (event) => {
    if (event.type === "token") process.stdout.write(event.value || "");
    if (event.type === "error") console.error("Error:", event.error);
    if (event.type === "complete") console.log("\nDone!");
  },
});

for await (const _ of result.stream) {
  // Events already handled by onEvent
}

Fallback Models & Providers

import { l0 } from "@ai2070/l0";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";
import { anthropic } from "@ai-sdk/anthropic";

const result = await l0({
  // Primary model
  stream: () => streamText({ model: openai("gpt-4o"), prompt }),

  // Fallbacks: tried in order if primary fails (supports both model and provider fallbacks)
  fallbackStreams: [
    () => streamText({ model: openai("gpt-4o-mini"), prompt }),
    () => streamText({ model: anthropic("claude-sonnet-4-20250514"), prompt }),
  ],

  onFallback: (index, reason) => console.log(`Switched to fallback ${index}`),
});

Parallel Execution

import { parallel } from "@ai2070/l0";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

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

const results = await parallel(
  prompts.map((prompt) => ({
    stream: () => streamText({ model: openai("gpt-4o-mini"), prompt }),
  })),
  { concurrency: 3 },
);

results.results.forEach((r, i) => {
  console.log(`${prompts[i]}: ${r?.state.content.trim()}`);
});

Pipe: Streaming Pipelines

import { pipe } from "@ai2070/l0";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

const result = await pipe(
  [
    {
      name: "summarize",
      fn: (input) => ({
        stream: () =>
          streamText({
            model: openai("gpt-4o"),
            prompt: `Summarize: ${input}`,
          }),
      }),
    },
    {
      name: "translate",
      fn: (summary) => ({
        stream: () =>
          streamText({
            model: openai("gpt-4o"),
            prompt: `Translate to French: ${summary}`,
          }),
      }),
    },
  ],
  longDocument,
);

console.log(result.output); // French translation of summary

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 model
  • Zero dependencies - Only (optional) peer dependency is the Vercel AI SDK, the OpenAI SDK, or Mastra AI

Bundle sizes (minified):

ImportSizeGzippedDescription
@ai2070/l0 (full)191KB56KBEverything
@ai2070/l0/core71KB21KBRuntime + retry + errors
@ai2070/l0/structured61KB18KBStructured output
@ai2070/l0/consensus72KB21KBMulti-model consensus
@ai2070/l0/parallel58KB17KBParallel/race operations
@ai2070/l0/window62KB18KBDocument chunking
@ai2070/l0/guardrails18KB6KBValidation rules
@ai2070/l0/monitoring27KB7KBOTel/Sentry
@ai2070/l0/drift4KB2KBDrift detection
@ai2070/l0/zod12KB4KBZod 4 validation schemas

Dependency-free. Tree-shakeable subpath exports for minimal bundles.

Most applications should simply use import { l0 } from "@ai2070/l0". Only optimize imports if you're targeting edge runtimes or strict bundle constraints.

Zod Validation Schemas

L0 exports Zod 4 schemas for runtime validation of all L0 types:

import {
  L0StateSchema,
  L0EventSchema,
  GuardrailViolationSchema,
} from "@ai2070/l0/zod";

// Validate runtime data
const state = L0StateSchema.parse(unknownData);

// Type-safe validation
const result = L0EventSchema.safeParse(event);
if (result.success) {
  console.log(result.data.type);
}

Schemas are available for all core types: L0State, L0Event, L0Telemetry, RetryOptions, GuardrailViolation, ConsensusResult, PipelineResult, and more.

Performance

Benchmarks on Apple M1 Max, Node.js 24, zero-delay mock streams (2000 tokens):

ScenarioTokens/sAvg DurationTTFT
Baseline (raw streaming)4,459,0210.45 ms0.00 ms
L0 Core (no features)1,068,6831.87 ms0.04 ms
L0 + JSON Guardrail615,0313.28 ms0.20 ms
L0 + All Guardrails337,1745.93 ms0.08 ms
L0 + Drift Detection609,5463.37 ms0.07 ms
L0 Full Stack259,4787.73 ms0.08 ms

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

Documentation

GuideDescription
ADVANCED.mdAdvanced usage
QUICKSTART.md5-minute getting started
API.mdComplete API reference
GUARDRAILS.mdGuardrails and validation
STRUCTURED_OUTPUT.mdStructured output guide
CONSENSUS.mdMulti-generation consensus
DOCUMENT_WINDOWS.mdDocument chunking guide
NETWORK_ERRORS.mdNetwork error handling
ERROR_HANDLING.mdError handling guide
PERFORMANCE.mdPerformance tuning
INTERCEPTORS_AND_PARALLEL.mdInterceptors and parallel ops
MONITORING.mdTelemetry and metrics
EVENT_SOURCING.mdRecord/replay, audit trails
FORMATTING.mdFormatting helpers
CUSTOM_ADAPTERS.mdBuild your own adapters
MULTIMODAL.mdImage/audio/video support
DETERMINISTIC_LIFECYCLE.mdLifecycle specification

Support

L0 is developed and maintained independently. If your company depends on L0 or wants to support ongoing development (including the Python version, website docs, and future tooling), feel free to reach out:

[email protected]


License

Apache-2.0

版本与发布记录

@ai2070/l0 共发布 29 个版本,首次发布于 2025/12/01;过去 12 个月发布了 29 个版本。

版本发布日期距今
0.26.1latest2026/06/294 个月前
0.26.02026/06/274 个月前
0.25.02026/04/306 个月前
0.24.42026/04/306 个月前
0.24.32026/04/296 个月前
0.24.22026/04/296 个月前

关于 @ai2070/l0 的常见问题

@ai2070/l0 是什么?

L0: The Missing Reliability Substrate for AI注意:该包已被作者标记为弃用——Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

如何安装 @ai2070/l0?

在项目目录运行 npm install @ai2070/l0,或使用 pnpm add / yarn add / bun add。

@ai2070/l0 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ai2070/l0 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@ai2070/l0 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@ai2070/l0 可以商用吗?

@ai2070/l0 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@ai2070/l0 的下载量有多少?

根据 npm 官方下载统计,@ai2070/l0 在 2026/10/05 – 2026/11/03 这 30 天内被下载 13,950 次,日均约 465 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ai2070/l0 还在维护吗?

最新版本 0.26.1 发布于 2026/06/29(4 个月前);至今共发布 29 个版本,其中过去 12 个月发布了 29 个;首次发布于 2025/12/01。作者已将其标记为弃用,新项目建议寻找替代方案。