> ## 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.

# Streaming

> How streamed responses pass through the PromptGuard proxy: buffered, scanned, then released

> [!NOTE]
>
> The proxy accepts `stream: true` and answers with Server-Sent Events, but it does not pass tokens through as the provider generates them. It reads the provider's whole stream, scans the completed text, and only then sends it to you. Time to first token is therefore the time to the full completion, plus the scan.

## How Streaming Works

1. Your request is sent to PromptGuard
2. PromptGuard scans the input. A blocked input gets an HTTP 403 before anything is forwarded, exactly as without streaming
3. If the input passes, the request is forwarded to the LLM provider with `stream: true`
4. PromptGuard reads the provider's stream to the end and holds it
5. In enforce mode, the completed text is scanned as output
6. If the output passes, the held SSE events are sent to you in one burst. If it is blocked, you receive a single error event and `[DONE]`, and none of the completion

In monitor mode step 5 is skipped, but the stream is still held until the provider finishes.

```mermaid theme={"system"}
sequenceDiagram
    participant App
    participant PG as PromptGuard
    participant LLM as LLM Provider
    App->>PG: Request (stream: true)
    PG->>PG: Input scan
    PG->>LLM: Forward request
    LLM-->>PG: Token 1 ... Token N, [DONE]
    PG->>PG: Output scan of the whole completion
    PG-->>App: All SSE events, then [DONE]
```

Why: a stream that is forwarded as it arrives cannot be recalled. If the violation is in token 400, tokens 1 to 399 have already reached your user. Holding the stream is what lets a blocked response deliver nothing.

## Using the OpenAI SDK

Your existing streaming code works unchanged: point the client at the proxy and add the `X-API-Key` header. Your provider key stays the client's API key.

```python Python theme={"system"}
import os
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"]},
)

stream = client.chat.completions.create(
    model="gpt-5-nano",
    messages=[{"role": "user", "content": "Explain quantum computing"}],
    stream=True
)

for chunk in stream:
    content = chunk.choices[0].delta.content
    if content is not None:
        print(content, end="", flush=True)
```

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

const openai = 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 },
});

const stream = await openai.chat.completions.create({
  model: 'gpt-5-nano',
  messages: [{ role: 'user', content: 'Explain quantum computing' }],
  stream: true
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content;
  if (content) {
    process.stdout.write(content);
  }
}
```

```bash cURL theme={"system"}
curl -N https://api.promptguard.co/api/v1/chat/completions \
  -H "X-API-Key: $PROMPTGUARD_API_KEY" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5-nano",
    "messages": [{"role": "user", "content": "Explain quantum computing"}],
    "stream": true
  }'
```

## Using the PromptGuard SDK

The Python `PromptGuard` client streams: `stream=True` returns an iterator of parsed SSE chunks as dicts. It sends only your PromptGuard key, so the request reaches the provider only if you have [stored a provider key](https://docs.promptguard.co/gateway/provider-keys.md) for it.

```python theme={"system"}
from promptguard import PromptGuard

pg = PromptGuard()  # reads PROMPTGUARD_API_KEY

stream = pg.chat.completions.create(
    model="gpt-5-nano",
    messages=[{"role": "user", "content": "Write a short story"}],
    stream=True,
)

for chunk in stream:
    if "error" in chunk:  # the output scan blocked the response
        print(f"Blocked: {chunk['error']['message']}")
        break
    choices = chunk.get("choices") or [{}]
    content = choices[0].get("delta", {}).get("content")
    if content:
        print(content, end="", flush=True)
```

The Node.js `PromptGuard` client does not stream: `stream: true` throws a `PromptGuardError` with code `streaming_not_supported`. In Node, stream with the OpenAI SDK pointed at the proxy, as above.

## Server-Sent Events (SSE)

When streaming, the API returns [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events). Each event contains a JSON chunk:

```
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" world"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]
```

## Framework Integration

### FastAPI (Python)

```python theme={"system"}
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import os
from openai import OpenAI

app = FastAPI()

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"]},
)

@app.post("/chat/stream")
async def stream_chat(message: str):
    def generate():
        stream = client.chat.completions.create(
            model="gpt-5-nano",
            messages=[{"role": "user", "content": message}],
            stream=True
        )
        for chunk in stream:
            content = chunk.choices[0].delta.content
            if content:
                yield f"data: {content}\n\n"
        yield "data: [DONE]\n\n"

    return StreamingResponse(generate(), media_type="text/event-stream")
```

### Express (Node.js)

```typescript theme={"system"}
import express from 'express';
import OpenAI from 'openai';

const app = express();
app.use(express.json());

const openai = 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 },
});

app.post('/chat/stream', async (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  const stream = await openai.chat.completions.create({
    model: 'gpt-5-nano',
    messages: [{ role: 'user', content: req.body.message }],
    stream: true
  });

  for await (const chunk of stream) {
    const content = chunk.choices[0]?.delta?.content;
    if (content) {
      res.write(`data: ${JSON.stringify({ content })}\n\n`);
    }
  }

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

### Next.js (React)

```typescript theme={"system"}
// app/api/chat/route.ts
import OpenAI from 'openai';

const openai = 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! },
});

export async function POST(req: Request) {
  const { message } = await req.json();

  const stream = await openai.chat.completions.create({
    model: 'gpt-5-nano',
    messages: [{ role: 'user', content: message }],
    stream: true
  });

  const encoder = new TextEncoder();
  const readable = new ReadableStream({
    async start(controller) {
      for await (const chunk of stream) {
        const content = chunk.choices[0]?.delta?.content;
        if (content) {
          controller.enqueue(encoder.encode(`data: ${JSON.stringify({ content })}\n\n`));
        }
      }
      controller.enqueue(encoder.encode('data: [DONE]\n\n'));
      controller.close();
    }
  });

  return new Response(readable, {
    headers: { 'Content-Type': 'text/event-stream' }
  });
}
```

## Error Handling During Streaming

A streamed request can be blocked at two points, and each arrives differently:

| Blocked at | What you receive | `type` / `code` |
| - | - | - |
| Input scan | HTTP 403 with a JSON error body, before any stream starts | `policy_violation` / `request_blocked` |
| Output scan | HTTP 200 `text/event-stream` carrying one `data: {"error": …}` event and `data: [DONE]`, with no completion | `content_filter` / `content_blocked` |

The OpenAI SDKs raise both as `APIError`, so one handler covers them:

```python Python theme={"system"}
import openai

try:
    stream = client.chat.completions.create(
        model="gpt-5-nano",
        messages=[{"role": "user", "content": prompt}],
        stream=True,
    )
    for chunk in stream:
        content = chunk.choices[0].delta.content if chunk.choices else None
        if content:
            print(content, end="")
except openai.APIError as e:
    if e.type == "policy_violation":
        print("\nRequest blocked by security policy")
    elif e.type == "content_filter":
        print("\nResponse blocked by security policy")
    else:
        raise
```

```typescript Node.js theme={"system"}
try {
  const stream = await openai.chat.completions.create({
    model: 'gpt-5-nano',
    messages: [{ role: 'user', content: prompt }],
    stream: true,
  });
  for await (const chunk of stream) {
    const content = chunk.choices[0]?.delta?.content;
    if (content) process.stdout.write(content);
  }
} catch (error) {
  if (error instanceof OpenAI.APIError && error.type === 'policy_violation') {
    console.log('\nRequest blocked by security policy');
  } else if (error instanceof OpenAI.APIError && error.type === 'content_filter') {
    console.log('\nResponse blocked by security policy');
  } else {
    throw error;
  }
}
```

Because the output is scanned before anything is sent, a blocked response never puts partial text on screen: the error is the first and only event.

## Streaming with auto-instrumentation

With [auto-instrumentation](https://docs.promptguard.co/integrations/auto-instrumentation.md) (`init()`), your client talks to the provider directly and only the input is scanned for a streamed call. `scan_responses` / `scanResponses` does not apply to 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 to scan.

To scan streamed output in your own code, collect the text as it arrives and scan it with the [Guard API](https://docs.promptguard.co/api-reference/guard.md) once the stream ends:

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

guard = GuardClient()  # reads PROMPTGUARD_API_KEY

parts = []
for chunk in stream:
    content = chunk.choices[0].delta.content if chunk.choices else None
    if content:
        parts.append(content)

decision = guard.scan(
    [{"role": "assistant", "content": "".join(parts)}],
    direction="output",
)
if decision.blocked:
    print(f"Output blocked: {decision.threat_type}")
```

If you show tokens to the user while collecting them, they have seen the text before the verdict arrives. Hold the text until the scan returns, or route the call through the proxy, which holds it for you.

## Performance

| | Through the proxy |
| - | - |
| Time to first token | Time to the provider's full completion, plus the input and output scans |
| Delivery after the first token | Immediate: the rest of the held stream follows in the same burst |
| Blocked output | One error event; no completion text is sent |

Streaming through the proxy therefore does not lower perceived latency the way it does against the provider directly: your user waits for the whole answer either way. Keep `stream: true` if your client code already handles SSE, since nothing else changes, but do not choose it for a faster first token. The scans' own cost depends on how often your traffic escalates past the deterministic layer; measure it with the [latency budgets](https://docs.promptguard.co/production/latency-budgets.md) guide.

## Next steps

> [card] [Streaming protection](https://docs.promptguard.co/cookbooks/streaming-protection.md)
>
> Three ways to protect a streamed response

> [card] [Latency budgets](https://docs.promptguard.co/production/latency-budgets.md)
>
> Per-detector budgets and how to keep the guard call fast

> [card] [Error handling](https://docs.promptguard.co/production/error-handling.md)
>
> Every error code the API returns and how to handle it


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