How to stream an LLM answer a guardrail may still block: five approaches compared
To stream an answer a guardrail may still change, either check each chunk before it is sent, or send it at once and replace it when the check fails. The first costs latency; the second lets unchecked text reach the screen.
Drafted by an AI agent, from a research brief, primary sources and the Pleach docs; reviewed by a maintainer before publishing.
No @pleach/* package is on npm yet. Each name holds a 0.0.1 placeholder until its first release, so the code here describes the source, not an install that works today. Package status
To stream an answer a guardrail may still block, you choose where the check sits: before each chunk is sent, which costs latency, or after, which lets unchecked text reach the screen until a correction replaces it. No setting removes that trade. Every approach below picks a point on it. The differences are in chunk size, how the late signal is delivered, and what the client has to do when the check fails.
Microsoft's own docs put the choice plainly: use the default mode when "content must be evaluated before your application displays it", and the asynchronous mode when your app "can stop displaying content and remove or replace content that was already displayed" (Azure OpenAI content streaming). For related patterns, see approving a tool call before and after it runs and re-sending a chat message without running the turn twice.
The approaches side by side
| Property | Azure OpenAI default | Azure OpenAI async filter | NeMo Guardrails output rails | Guardrails AI streaming | Post-hoc correction | Buffer until done |
|---|---|---|---|---|---|---|
| Time to first token | Delayed by buffering and evaluation | No filter latency on tokens | stream_first: True: low. False: plus rail time per chunk | After the first sentence is validated | Same as raw model | Full turn |
| Granularity of check | Buffered chunks | Annotations in up to ~1,000-character increments | 200-token chunks, 50-token overlap (defaults) | One sentence (default) | Whole turn | Whole turn |
| UX on failure | Stream stops with an error | Stream stops; app removes or replaces shown text | JSON error object; stream ends | error_spans_in_output() lists failed ranges | Shown text swapped for corrected text | Answer appears once, already checked |
| Client complexity | Low | High: track offsets, redact | Medium: handle the error object | Medium | Medium: replace, drop stale events | Low, plus a pending indicator |
These setups differ. Azure filters a hosted model's output. NeMo and Guardrails AI are libraries you run around any model. Post-hoc correction and buffering are patterns, not products. Compare the trade-offs, not the brands.
How does Azure OpenAI filter streamed output?
By default it buffers completion content and evaluates it before returning it. The docs say content "arrives in buffered content chunks rather than token by token", and a violation returns a guardrail error (source).
The Asynchronous Filter drops the buffer. Tokens arrive one by one, and filters run in parallel. Microsoft frames it as removing "content-filtering latency from token delivery" in exchange for delayed filtering results.
The filtering signal has a shape. Annotation messages carry content_filter_offsets with check_offset, start_offset and end_offset. check_offset marks how much text is fully moderated and "never decreases". A violation ends the stream with finish_reason: "content_filter". Microsoft's comparison table lists the signal as arriving "in up to ~1,000-character increments". Async mode requires API version 2024-02-01 or later.
How do NeMo Guardrails output rails handle streaming?
They check the stream in token chunks, and one flag decides whether the client sees a chunk before or after its check. The settings live under rails.output.streaming (NeMo Guardrails output rail streaming):
| Key | Default | Meaning |
|---|---|---|
enabled | False | Must be True to use stream_async() with output rails |
chunk_size | 200 | Tokens per chunk the rails check |
context_size | 50 | Tokens carried between chunks for continuity |
stream_first | True | Send the chunk before the rails run on it |
With stream_first: True, "the client receives each chunk of tokens before output rails process that chunk." That is the low-latency setting. With False, rails run first and the client receives only chunks that pass. Time to first token grows by the rail execution time per chunk.
When a rail blocks mid-stream, the stream yields a JSON error object of the form {"error": {...}} and ends. The docs ship a low-latency preset (chunk_size 50, context_size 20, stream_first true) and a safety-first preset (300, 75, false).
How does Guardrails AI validate a stream?
Per sentence, by default. You pass stream=True to the guard call, and it returns "a generator that will yield GuardResult objects as they are processed" (Guardrails AI streaming).
Validators "wait until they have accumulated a sentence's worth of content from the LLM before running validation." Each sentence's result is emitted when its check finishes. So the first visible text arrives after the first sentence is validated, not after the first token.
For text that failed, guard.error_spans_in_output() gives "an up to date list of all ranges of text in the output so far that have failed validation." A client can use those ranges to mark or replace text.
What about post-hoc correction and buffering?
These are the two ends of the trade, and both work with any model or filter.
Post-hoc correction streams the raw model output, runs the guard on the finished turn, and sends a replacement event if the guard changes anything. Time to first token matches the raw model. The guard sees the whole answer, so it can catch claims that only make sense in full context. The cost is that the uncorrected text is on screen until the replacement lands. The client also has to tell a current correction from a stale one left over from an earlier turn.
Buffer until done holds the whole answer until every guard has run, then shows it once. Nothing unchecked reaches the screen. The cost is the full turn's latency, with an empty answer area in the meantime.
OpenAI's guardrails cookbook names the axis these sit on: guardrail design "is a trade-off between accuracy, latency, and cost." It describes running guardrails "asynchronously along with your main LLM call" to cut latency (OpenAI cookbook).
When to use each
- Shown text must be checked first, and you use Azure OpenAI: default mode, or
stream: false. - Latency matters most and your UI can redact: Azure's Asynchronous Filter, or NeMo with
stream_first: True. - You run your own rails and can't show blocked text: NeMo with
stream_first: False, and tunechunk_sizefor latency. - Your validators are expensive or sentence-shaped: Guardrails AI streaming with its sentence chunking.
- The guard needs the whole answer: post-hoc correction if brief exposure is acceptable, buffer until done if it isn't.
How Pleach does it
Pleach's fabrication guard needs the whole turn, so it uses post-hoc correction by default and offers buffer-until-done as an option.
The correction event
applyFabricationGuard runs after synthesis. It removes tool calls the model invented, paragraphs that reference tools that failed or never ran, and similar signals. The fabrication detection page lists them.
Each message.delta reaches the client as it is produced. The guard acts on the finished turn, so its result arrives later as a content.correction, and it can arrive after the terminal message.complete. In the typical case, the model claims it called fetch_document, no such call landed, and the guard fires reason: "phantom_tool_reference". The troubleshooting page notes the swap is not a bug.
The payload, per stream events:
| Field | Meaning |
|---|---|
correctedContent | The authoritative final text |
reason | A member of CONTENT_CORRECTION_REASONS |
materializerPreviousLen | Optional |
contentClass | Optional. "COMMIT" or "PREVIEW" |
sourceMessageId | Optional. The id of the turn the corrected content was produced for |
producingTurnVerified | Optional. true when the runtime proved the current user turn produced the content |
messageId | Optional. The id of the turn's assistant message |
Treat correctedContent as the whole body. The renderer replaces the last assistant message wholesale for that messageId. It does not append. messageId names the stream; sourceMessageId names the producer.
Dropping stale corrections
The core clients (useChat, useHarness, useSessionMessageStream and collectStream) apply two checks, and both must pass:
- Once the client knows the turn's assistant id, a correction naming another
messageIdis dropped. - When
sourceMessageIddoes not match the active turn's user message id andproducingTurnVerifiedis nottrue, the correction is dropped too.
Fold one turn sequence per reducer. A stream that merges several turns without those boundaries is not supported.
Holding the answer
The buffer-until-done option is holdAnswerUntilTurnComplete, off by default:
useChat({ api: "/api/chat", holdAnswerUntilTurnComplete: true });
useHarness({ holdAnswerUntilTurnComplete: true });
useSessionMessageStream({ runtime, sessionId, onEvent, holdAnswerUntilTurnComplete: true });The reply stays out of view until the turn ends, then appears once, already corrected. The hold releases on turn.completed, an error event, or the stream ending, throwing or being stopped. message.complete does not release it, because a correction can still follow. Reasoning, tool calls, tool progress and interrupts stay live. Render a pending indicator from status (useChat) or isStreaming (useHarness).
With useSessionMessageStream, events still reach onEvent, so paint from ctx.visibleText, not raw message.delta payloads. onAnswerReleased(ctx) fires exactly once per user turn. collectStream needs no option; its text already has corrections applied. A client that folds events itself can wrap its reducer with createHeldStreamMessageReducer(true) from @pleach/core.
The hold covers turns that run to completion; label an answer painted after a Stop as a partial.
The react page documents the hook options. Package status is on packages.
Key takeaways
- The check sits before or after the send. Before costs time to first token; after lets unchecked text reach the screen.
- Defaults differ. Azure buffers by default; NeMo's
stream_firstdefaults toTrue, which sends before checking. - Granularity sets latency. Azure async signals within ~1,000 characters, NeMo checks 200-token chunks, Guardrails AI checks sentences.
- A send-first design needs a client that can retract. Key the replacement on a message id and drop corrections from earlier turns.
- Buffering is the only zero-exposure option for whole-answer guards. Its cost is an empty answer area until the turn ends.
References
- Microsoft Learn, "Content streaming in Azure OpenAI." https://learn.microsoft.com/en-us/azure/foundry/openai/concepts/content-streaming
- NVIDIA, "NeMo Guardrails: Output rail streaming configuration." https://docs.nvidia.com/nemo/guardrails/latest/configure-guardrails/yaml-schema/streaming/output-rail-streaming
- Guardrails AI, "Streaming." https://guardrailsai.com/guardrails/docs/concepts/streaming
- OpenAI Cookbook, "How to implement LLM guardrails." https://developers.openai.com/cookbook/examples/how_to_use_guardrails
Frequently asked
How do you stream an LLM response when an output guardrail may block it?
Pick where the check sits relative to the send. Check each chunk before sending it and blocked text never reaches the client, at the cost of time to first token. Send each chunk first and check it in parallel, and the client must remove or replace text when a late signal arrives. Holding the whole answer until the turn ends is the simplest safe option and the slowest.
What is the Azure OpenAI asynchronous content filter?
It is a streaming mode where content filters run asynchronously and tokens are returned without buffering. Microsoft's docs describe it as trading lower latency for delayed filtering signals, which arrive as annotation messages during the stream. Microsoft recommends it for applications that can remove or replace displayed content when a signal arrives. The default mode buffers content and evaluates it before returning it in chunks.
What does stream_first do in NeMo Guardrails?
stream_first controls whether the client receives a chunk before output rails check it. It defaults to True, which sends each chunk to the client before the rails process it, for lower latency. With False, rails run on each chunk first and the client receives only chunks that pass, while time to first token grows by the rail execution time per chunk. Chunks default to 200 tokens.
How does Guardrails AI validate a streamed response?
Pass stream=True to the guard call and it returns a generator of GuardResult objects. Validators buffer content by a chunk strategy, by default one sentence, and run validation on each sentence before emitting its result. guard.error_spans_in_output() lists the ranges of text so far that failed validation, so a client can mark or replace them.
How does Pleach handle a guard that rewrites a streamed answer?
Pleach streams first and corrects after. applyFabricationGuard rewrites a synthesized turn before it is persisted, and the client receives a content.correction whose correctedContent replaces the assistant message wholesale. The React hooks apply corrections by default. Setting holdAnswerUntilTurnComplete to true keeps the answer out of view until the turn ends, then shows it once, already corrected.