> ## Documentation Index
> Fetch the complete documentation index at: https://docs.promptguard.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Protect a streamed response

> Three ways to protect streamed LLM responses: through the proxy, with auto-instrumentation, or by scanning windows yourself, and what each one costs.

> [!NOTE]
>
> This cookbook compares the ways to protect a streamed response. They trade time to first token against how much unscanned text your user can see.

## Overview

| Approach | Input scanned | Output scanned | What the user sees before the verdict |
| - | - | - | - |
| [Through the proxy](#through-the-proxy) | Yes | Yes, the whole completion, in enforce mode | Nothing: the stream is held until the provider finishes and the scan passes |
| [Auto-instrumentation](#auto-instrumentation) | Yes | No, not for streamed calls | Every token, unscanned |
| [Vercel AI SDK wrapper](#vercel-ai-sdk) | Yes | Yes, a window at a time, with `scanResponses: true` in enforce mode | Nothing unscanned |
| [Window scanning in your code](#window-scanning-in-your-code) | Up to you | Each window, before you send it | Nothing unscanned, at one [Guard API](https://docs.promptguard.co/api-reference/guard.md) call per window |

## Through the proxy

Point your client at the proxy and every streamed response is held and scanned as a whole before any of it is sent. A blocked response arrives as a single error event, so no partial text reaches the user. The cost is time to first token: it equals the time to the full completion plus the scans. [Streaming](https://docs.promptguard.co/guides/streaming.md) explains the behaviour and the error shapes.

```python Python theme={"system"}
import os
import openai
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["OPENAI_API_KEY"],  # forwarded to OpenAI
    base_url="https://api.promptguard.co/api/v1",
    default_headers={"X-API-Key": os.environ["PROMPTGUARD_API_KEY"]},
)

try:
    stream = client.chat.completions.create(
        model="gpt-5-nano",
        messages=[{"role": "user", "content": "Write a short story about a lighthouse"}],
        stream=True,
    )
    for chunk in stream:
        content = chunk.choices[0].delta.content if chunk.choices else None
        if content:
            print(content, end="", flush=True)
except openai.APIError as e:
    if e.type in ("policy_violation", "content_filter"):
        print(f"\nBlocked by PromptGuard ({e.code})")
    else:
        raise
```

```typescript Node.js theme={"system"}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY, // forwarded to OpenAI
  baseURL: 'https://api.promptguard.co/api/v1',
  defaultHeaders: { 'X-API-Key': process.env.PROMPTGUARD_API_KEY },
});

try {
  const stream = await client.chat.completions.create({
    model: 'gpt-5-nano',
    messages: [{ role: 'user', content: 'Write a short story about a lighthouse' }],
    stream: true,
  });
  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
  }
} catch (error) {
  if (
    error instanceof OpenAI.APIError &&
    (error.type === 'policy_violation' || error.type === 'content_filter')
  ) {
    console.log(`\nBlocked by PromptGuard (${error.code})`);
  } else {
    throw error;
  }
}
```

## Auto-instrumentation

With `init()`, your client talks to the provider directly. For a streamed call PromptGuard scans the input before the request is sent; the output is not scanned. `scan_responses` / `scanResponses` has no effect on streams: the Node.js SDK skips the output scan for streaming calls on purpose, and the Python SDK finds no completion text on a stream object.

```python Python theme={"system"}
import promptguard
promptguard.init(mode="enforce")  # reads PROMPTGUARD_API_KEY

from openai import OpenAI
from promptguard import PromptGuardBlockedError

client = OpenAI()

try:
    stream = client.chat.completions.create(
        model="gpt-5-nano",
        messages=[{"role": "user", "content": "Write a short story about a lighthouse"}],
        stream=True,
    )
    for chunk in stream:
        content = chunk.choices[0].delta.content if chunk.choices else None
        if content:
            print(content, end="", flush=True)
except PromptGuardBlockedError as e:
    # Raised by create(), before the stream starts: the input was blocked
    print(f"Input blocked: {e.decision.threat_type}")
```

```typescript Node.js theme={"system"}
import { init, PromptGuardBlockedError } from 'promptguard-sdk';
import OpenAI from 'openai';

init({ mode: 'enforce' }); // reads PROMPTGUARD_API_KEY

const client = new OpenAI();

try {
  const stream = await client.chat.completions.create({
    model: 'gpt-5-nano',
    messages: [{ role: 'user', content: 'Write a poem' }],
    stream: true,
  });
  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
  }
} catch (error) {
  if (error instanceof PromptGuardBlockedError) {
    console.log(`Input blocked: ${error.decision.threatType}`);
  } else {
    throw error;
  }
}
```

## Vercel AI SDK

Wrap the model with `promptguard()`. With `scanResponses: true`, streamed text reaches the client only after it has been scanned, a window at a time. A blocked prompt reaches `onError` and the client gets an empty response. Blocked output ends the response body with an error on `ai` 6 and 7, without calling `onError`; on `ai` 5 it reaches `onError`, the body simply ends, and `finishReason` is `'error'`. The [Node.js SDK guide](https://docs.promptguard.co/guides/node-sdk.md#vercel-ai-sdk) has the full table.

```typescript theme={"system"}
import { promptguard } from 'promptguard-sdk/integrations/vercel-ai';
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

// Reads PROMPTGUARD_API_KEY from the environment.
const model = promptguard(openai('gpt-5-nano'), { scanResponses: true });

async function handler(req: Request) {
  const { prompt } = await req.json();

  const result = streamText({
    model,
    prompt,
    onError: ({ error }) => console.error(error), // blocked prompts (and, on ai 5, blocked output)
  });

  return result.toTextStreamResponse();
}
```

See the [Node.js SDK guide](https://docs.promptguard.co/guides/node-sdk.md#vercel-ai-sdk) for the options.

## Window scanning in your code

To show text sooner than the proxy does while still scanning everything you send, collect the stream into windows and scan each one with `GuardClient` before passing it on. Each window costs one Guard API call, and a window is scanned on its own, so a threat split across two windows can be missed. Larger windows miss less and delay more.

```python Python theme={"system"}
from openai import OpenAI
from promptguard import GuardClient

guard = GuardClient()  # reads PROMPTGUARD_API_KEY
client = OpenAI()

def scan_window(text: str) -> str | None:
    """The text to send, or None if the window is blocked."""
    decision = guard.scan(
        [{"role": "assistant", "content": text}],
        direction="output",
    )
    if decision.blocked:
        return None
    if decision.redacted and decision.redacted_messages:
        return decision.redacted_messages[0]["content"]
    return text

def secure_stream(messages: list, window: int = 200):
    stream = client.chat.completions.create(
        model="gpt-5-nano",
        messages=messages,
        stream=True,
    )
    buffer = ""
    for chunk in stream:
        buffer += (chunk.choices[0].delta.content if chunk.choices else None) or ""
        if len(buffer) >= window:
            safe = scan_window(buffer)
            if safe is None:
                yield "[CONTENT BLOCKED]"
                return
            yield safe
            buffer = ""
    if buffer:
        safe = scan_window(buffer)
        yield "[CONTENT BLOCKED]" if safe is None else safe

for safe_chunk in secure_stream([{"role": "user", "content": "Tell me a story"}]):
    print(safe_chunk, end="", flush=True)
```

```typescript Node.js theme={"system"}
import { GuardClient } from 'promptguard-sdk';
import OpenAI from 'openai';
import type { Response } from 'express';

const client = new OpenAI();
const guard = new GuardClient({ apiKey: process.env.PROMPTGUARD_API_KEY! });

async function scanWindow(text: string): Promise<string | null> {
  const decision = await guard.scan([{ role: 'assistant', content: text }], {
    direction: 'output',
  });
  if (decision.blocked) return null;
  return decision.redacted && decision.redactedMessages
    ? decision.redactedMessages[0].content
    : text;
}

export async function streamSSE(
  res: Response,
  messages: OpenAI.Chat.ChatCompletionMessageParam[],
  window = 200,
) {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');

  const stream = await client.chat.completions.create({
    model: 'gpt-5-nano',
    messages,
    stream: true,
  });

  let buffer = '';
  const flush = async (): Promise<boolean> => {
    const safe = await scanWindow(buffer);
    buffer = '';
    if (safe === null) {
      res.write('data: [BLOCKED]\n\n');
      res.end();
      return false;
    }
    res.write(`data: ${JSON.stringify({ content: safe })}\n\n`);
    return true;
  };

  for await (const chunk of stream) {
    buffer += chunk.choices[0]?.delta?.content ?? '';
    if (buffer.length >= window && !(await flush())) return;
  }
  if (buffer && !(await flush())) return;

  res.write('data: [DONE]\n\n');
  res.end();
}
```

## Choosing

1. **Nothing unscanned may reach the user, and the wait is acceptable**: stream through the proxy.
2. **Nothing unscanned may reach the user, and the first words must come sooner**: scan windows in your code, and accept a [Guard API](https://docs.promptguard.co/api-reference/guard.md) call per window and the cross-window gap.
3. **Only the input needs scanning**: auto-instrumentation.

## Next Steps

> [card] [Streaming Reference](https://docs.promptguard.co/guides/streaming.md)
>
> How the proxy handles streamed responses

> [card] [Error Handling](https://docs.promptguard.co/production/error-handling.md)
>
> Handle errors gracefully


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.