Skip to content

docs: guardrails example leaves wrapStream unimplemented #21209

Description

@roshcompanylabs

Description

Two things about the guardrails example in Language Model Middleware — one trivial, one not. Both verified against [email protected] / @ai-sdk/[email protected].

Disclosure: I maintain an MIT library that does streaming redaction, so I have an interest here. The suggestion below is deliberately self-contained — it has no dependency on it and you can drop it straight into the docs.

1. None of the middleware examples compile

Copied verbatim from the page:

import type { LanguageModelV4Middleware } from '@ai-sdk/provider';

export const yourGuardrailMiddleware: LanguageModelV4Middleware = {
  wrapGenerate: async ({ doGenerate }) => { /* ... */ },
};
error TS2741: Property 'specificationVersion' is missing in type
'{ wrapGenerate: ... }' but required in type 'LanguageModelV4Middleware'.

specificationVersion: 'v4' is a required readonly field. All five middleware examples on the page omit it, and the field is not mentioned anywhere on the page.

2. wrapStream is left unimplemented

  // here you would implement the guardrail logic for streaming
  // Note: streaming guardrails are difficult to implement, because
  // you do not know the full content of the stream until it's finished.

The note is right, and I think it understates the problem. A reader who moves the wrapGenerate .replace() into a wrapStream transform gets something that looks like it works and silently does not — in two different ways.

A match split across deltas is never seen.

delta 1:  "...your card is 4111 11"
delta 2:  "11 1111 1111, charge it."

Per-delta .replace() matches neither half, so the card reaches the reader. At typical delta sizes that is most values, not an edge case.

Worse: a variable-length secret gets cut in half. This one is not fixed by buffering.

If you hold a fixed window and filter what falls out of it, the window often ends inside a still-growing value. An API key matches as soon as it is long enough, so the filter masks the part it has and streams the rest in clear:

out: "your key is <REDACTED>uvwxyz123456"

That is worse than no filter, because the output looks redacted.

The property that makes it tractable

Not a bigger buffer — a rule:

Never act on a match that could still grow, and never emit text you have not scanned in its final form.

Concretely: hold from the start of any match that runs past your release point, rather than from a fixed offset. The testable property is

for any input and any chunking, the streamed output is byte-identical to filtering the whole string at once

which is machine-checkable by replaying the same input at every delta size.

Suggested replacement

Self-contained, no dependencies. Compiles clean; runtime results below.

import type {
  LanguageModelV4Middleware,
  LanguageModelV4StreamPart,
} from '@ai-sdk/provider';

/**
 * Streaming guardrail middleware.
 *
 * The rule: never act on a match that could still be growing, and never emit
 * text that has not been scanned in its final form.
 */
export const yourGuardrailMiddleware: LanguageModelV4Middleware = {
  specificationVersion: 'v4',

  wrapStream: async ({ doStream }) => {
    const { stream, ...rest } = await doStream();

    const BAD = /badword|sk-[A-Za-z0-9]{8,}|\b\d(?:[ -]?\d){12,18}\b/g;
    // Fallback hold, for text that does not look like a match yet.
    const HOLD = 32;

    // One buffer per text id: a stream may carry several text blocks at once,
    // which is what the `id` on each part is for. A single shared buffer
    // attributes text to the wrong block.
    const buffers = new Map<string, string>();

    function release(
      controller: TransformStreamDefaultController<LanguageModelV4StreamPart>,
      id: string,
      final: boolean,
    ) {
      let buffer = buffers.get(id) ?? '';
      if (!buffer) {
        if (final) buffers.delete(id);
        return;
      }

      let cut = final ? buffer.length : Math.max(0, buffer.length - HOLD);

      if (!final) {
        // A match running past the cut may still be growing — hold from where
        // it starts. This is what a fixed window alone cannot do, and why a
        // long key does not get masked in half.
        BAD.lastIndex = 0;
        let m: RegExpExecArray | null;
        while ((m = BAD.exec(buffer)) !== null) {
          if (m.index + m[0].length > cut) cut = Math.min(cut, m.index);
        }

        // Never cut inside a surrogate pair: slicing by UTF-16 code unit
        // splits an emoji and emits a lone surrogate.
        if (cut > 0 && cut < buffer.length) {
          const hi = buffer.charCodeAt(cut - 1);
          const lo = buffer.charCodeAt(cut);
          if (hi >= 0xd800 && hi <= 0xdbff && lo >= 0xdc00 && lo <= 0xdfff) cut--;
        }
      }

      if (cut <= 0) return;

      const safe = buffer.slice(0, cut).replace(BAD, '<REDACTED>');
      buffer = buffer.slice(cut);
      if (final) buffers.delete(id);
      else buffers.set(id, buffer);
      if (safe) controller.enqueue({ type: 'text-delta', id, delta: safe });
    }

    const transform = new TransformStream<
      LanguageModelV4StreamPart,
      LanguageModelV4StreamPart
    >({
      transform(chunk, controller) {
        if (chunk.type !== 'text-delta') {
          // Flush before the terminator, or `text-end` arrives ahead of the
          // text it is meant to end.
          if (chunk.type === 'text-end') release(controller, chunk.id, true);
          controller.enqueue(chunk);
          return;
        }
        buffers.set(chunk.id, (buffers.get(chunk.id) ?? '') + chunk.delta);
        release(controller, chunk.id, false);
      },

      flush(controller) {
        for (const id of [...buffers.keys()]) release(controller, id, true);
      },
    });

    return { stream: stream.pipeThrough(transform), ...rest };
  },
};

Checked with MockLanguageModelV4 + simulateReadableStream at delta sizes 1, 2, 3, 5, 9, 17, 40 and 200:

case result
card split across deltas caught at every size
sk- key, variable length caught at every size
key longer than the hold window caught at every size
banned word caught at every size
clean prose / emoji / CJK byte-identical at every size
two interleaved text blocks each block's text stays with its own id

Two caveats worth stating next to it, because a half-understood guardrail is the dangerous kind:

  • This holds text only while it looks like a match. A value whose prefix does not match the pattern at all (a PEM block, where only the header is distinctive) needs the region to be held from its opening marker instead.
  • HOLD still matters where nothing matches yet; it is simply no longer the only thing standing between a split secret and the reader.
  • One buffer per text id, since a stream can carry more than one text block at a time.

Offer

Happy to send this as a PR against the middleware docs page — the specificationVersion fix across the examples, the wrapStream implementation and the caveats. Equally happy to leave it here if you would rather word it yourselves.

Reproduction

1. The compile error — three steps

npm i [email protected] @ai-sdk/[email protected] typescript

Save the guardrails example from the docs page verbatim as docs-example.ts:

import type { LanguageModelV4Middleware } from '@ai-sdk/provider';

export const yourGuardrailMiddleware: LanguageModelV4Middleware = {
  wrapGenerate: async ({ doGenerate }) => {
    const result = await doGenerate();
    const content = result.content.map(part =>
      part.type === 'text'
        ? { ...part, text: part.text.replace(/badword/g, '<REDACTED>') }
        : part,
    );
    return { ...result, content };
  },
};
npx tsc --noEmit --strict docs-example.ts
docs-example.ts(4,14): error TS2741: Property 'specificationVersion' is missing
in type '{ wrapGenerate: ... }' but required in type 'LanguageModelV4Middleware'.

The same applies to the other four middleware examples on that page — none of them declares specificationVersion, and the field is not mentioned anywhere on the page.

2. The streaming failure — runnable

import { streamText, wrapLanguageModel } from 'ai';
import { MockLanguageModelV4, simulateReadableStream } from 'ai/test';

// A naive port of the wrapGenerate example into wrapStream.
const naive = {
  specificationVersion: 'v4' as const,
  wrapStream: async ({ doStream }: any) => {
    const { stream, ...rest } = await doStream();
    const t = new TransformStream({
      transform(chunk: any, c: any) {
        if (chunk.type === 'text-delta') {
          c.enqueue({ ...chunk, delta: chunk.delta.replace(/\b\d(?:[ -]?\d){12,18}\b/g, '<REDACTED>') });
        } else c.enqueue(chunk);
      },
    });
    return { stream: stream.pipeThrough(t), ...rest };
  },
};

const TEXT = 'Your card is 4111 1111 1111 1111, charge it.';
const parts: any[] = [{ type: 'text-start', id: '1' }];
for (let i = 0; i < TEXT.length; i += 6) {
  parts.push({ type: 'text-delta', id: '1', delta: TEXT.slice(i, i + 6) });
}
parts.push({ type: 'text-end', id: '1' });
parts.push({ type: 'finish', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 } });

const model = new MockLanguageModelV4({
  doStream: async () => ({ stream: simulateReadableStream({ chunks: parts }) }),
});

let out = '';
for await (const t of streamText({ model: wrapLanguageModel({ model, middleware: naive }), prompt: 'x' }).textStream) {
  out += t;
}
console.log(out);

Expected: the card is redacted.
Actual: Your card is 4111 1111 1111 1111, charge it. — the card passes through untouched at every delta size, because no single delta contains the whole match.

The implementation suggested in the description was checked the same way at delta sizes 1, 2, 3, 5, 9, 17, 40 and 200, plus a variable-length sk- key, a key longer than the hold window, emoji, CJK, and two interleaved text blocks.

AI SDK Version

- ai: 7.0.107
- @ai-sdk/provider: 4.0.17
- typescript: 5.6
- node: 20.20.2

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. ai-sdk-factory commented on Sep 20, 2026

    @ai-sdk-factory
    Contributor

    Identify issue type

    Identified as Documentation
    Confidence: High

    Rationale

    The requested changes concern correcting and completing code snippets and guidance on an existing documentation page, rather than changing AI SDK runtime behavior.

    Evidence

    • Middleware code copied verbatim from the documentation fails TypeScript compilation because all five snippets omit the required specificationVersion: 'v4' field.
    • The guardrails documentation leaves wrapStream as a placeholder and does not explain or implement safe handling of matches split across stream deltas.
    • The reporter offers a replacement documentation snippet and caveats for the middleware page.
  2. ai-sdk-factory commented on Sep 20, 2026

    @ai-sdk-factory
    Contributor

    Identify documentation type

    • Identified as Fix
    • Confidence: High

    Rationale

    The issue primarily corrects and completes existing middleware documentation. It fixes non-compiling examples and replaces an unsafe placeholder in an already documented guardrails example; it does not introduce coverage for a new provider or integration.

    Evidence

    • All five existing middleware examples reportedly omit the required specificationVersion: 'v4' field and fail TypeScript compilation.
    • The existing guardrails example explicitly leaves wrapStream unimplemented.
    • The proposed change supplies a self-contained streaming implementation and clarifying caveats for the same documentation page.
    • The request concerns documentation examples and guidance rather than missing runtime provider or integration support.
  3. ai-sdk-factory commented on Sep 20, 2026

    @ai-sdk-factory
    Contributor

    Documentation fix

    Created documentation fix and opened PR: #21210

    Summary

    Added specificationVersion: 'v4' to all five middleware examples and implemented per-text-block buffered streaming redaction with guidance about latency, memory use, split matches, and unbounded patterns.

    Testing

    pnpm check, pnpm type-check:full, pnpm validate:docs, docs tests, MDX generation, formatting, and focused snippet/runtime checks passed. The docs-site type-check reached MDX generation but failed on an unrelated existing LayoutProps error in app/[lang]/layout.tsx.

  4. ai-sdk-factory commented on Sep 20, 2026

    @ai-sdk-factory
    Contributor

    Documentation fix

    Created documentation fix and opened PR: #21211

    Summary

    Added specificationVersion: 'v3' to all five middleware examples and implemented per-text-block buffered streaming redaction with guidance about latency, memory use, split matches, and unbounded patterns.

    Testing

    pnpm check and pnpm type-check:full passed. A direct file-targeted formatter invocation was unsupported, but the repository-wide formatting and lint check passed.

  5. ai-sdk-factory commented on Sep 20, 2026

    @ai-sdk-factory
    Contributor

    Documentation fix

    Created documentation fix and opened PR: #21212

    Summary

    Updated the middleware documentation and guardrail example to use V2 content results, buffer each text block independently until text-end, redact complete text, and document the latency, memory, and variable-length-pattern tradeoffs.

    Testing

    pnpm check, pnpm type-check:full, and pnpm --filter @example/ai-core type-check passed. A focused runtime probe passed all 25 tested chunk sizes and interleaved text blocks.

  6. added 3 commits that reference this issue on Sep 22, 2026
    2801737
    87b77af
    e944b5d
  7. ninadphalak commented on Sep 23, 2026

    @ninadphalak

    Late to this, but the outcome here turned out to matter beyond the docs page.

    I have been collecting implementations of this same failure across projects that share no code, and the text Vercel merged on Sep 22 is now the clearest public statement of the constraint I have found anywhere: that an incremental implementation must retain every possible incomplete match, and that a fixed-size buffer alone is not safe for unbounded variable-length patterns. Four other projects shipped a filter that violates exactly that, independently, before anyone wrote it down.

    Write-up with the four and the invariant they all lack: https://doi.org/10.5281/zenodo.22909585

    @roshcompanylabs, the Vercel entry in it credits your report rather than presenting the docs change as independent, since it was your issue that produced it. Disclosure, as ever: I maintain a harness in this area.

  8. roshcompanylabs commented on Sep 23, 2026

    @roshcompanylabs
    ContributorAuthor

    Thanks — and you are right to file this entry as the weaker kind of evidence. A vendor accepting a problem when it is put to them is not the same as four teams hitting it independently, and the report is better for saying so.

    Your first open question is the one I can close, so: measured against an unfiltered stream of the same shape, nine runs after three warmup, median reported. Characters held before the first byte is released:

    assistant reply, no sensitive values     16
    reply with an email, card and phone      21
    markdown with a fenced code block         8
    Japanese reply                            0
    

    Added CPU is 2–10 µs per chunk. So the delay is structural rather than computational, and a single millisecond figure would not transfer between machines or token rates — it is those characters divided by the rate the model emits them. At 4 characters per chunk and 20 ms between chunks that is 80 ms for ordinary prose, 100 ms for a reply carrying PII, and nothing on Japanese. The structural numbers were identical across three runs.

    Harness: https://github.com/roshcompanylabs/llm-stream-guardrails/blob/main/bench/latency.mjs — npm run latency. Every measured run asserts the streamed output matches the batch result, so it cannot report a fast number for a broken build.

    One note on your corpus advice, since it cost me something: "a script written without spaces, since a tail bounded by word delimiters grows without limit there" is exactly right, and I shipped that bug. Japanese held the entire response and emitted nothing until the stream ended — safe, lossless, and not streaming. It reads as a tail in a latency table and it is a different defect.

  9. ninadphalak commented on Sep 28, 2026

    @ninadphalak

    One follow-up in case it helps anyone writing middleware like this: the split test is now a small package, so a guardrail can be checked with one assertion. It tries the whole input and every single cut, and names the smallest split that breaks the filter.

    npm i -D chunk-invariance (no runtime dependencies; also on PyPI): https://www.npmjs.com/package/chunk-invariance

  10. roshcompanylabs commented on Sep 28, 2026

    @roshcompanylabs
    ContributorAuthor

    Ran it against the filter I maintain — 15 inputs, 1,477 splits, invariant throughout.
    Wrote the result up as an issue on your repo rather than at length here, since this one is
    closed and belongs to Vercel: ninadphalak/LLM-Shield-Proxy#143

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions