Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Guardrails ai Guardrails Guard Use Streaming

From Leeroopedia
Knowledge Sources
Domains Streaming, Validation
Last Updated 2026-02-14 00:00 GMT

Overview

Concrete method for configuring a Guard with validators for streaming validation provided by the guardrails package.

Description

This is the same Guard.use method used for non-streaming validation, but applied in the context of streaming. The validator instance attached via .use() should support streaming through its _chunking_function method. The same fluent API pattern applies: validators are attached with a target (on="output") and registered in the Guard's validator map.

Usage

Use Guard().use(validator) exactly as for non-streaming, but be aware that for streaming calls, validators with string output will use their _chunking_function to determine validation boundaries.

Code Reference

Source Location

  • Repository: guardrails
  • File: guardrails/guard.py
  • Lines: L907-940

Signature

def use(
    self,
    validator: UseValidatorSpec,
    *args,
    on: str = "output",
    **kwargs,
) -> "Guard":
    """Use a validator to validate either of the following:
    - The output of an LLM request
    - The message history

    Args:
        validator: The validator to use. Either the class or an instance.
        on: The part of the LLM request to validate. Defaults to "output".
    """

Import

from guardrails import Guard

I/O Contract

Inputs

Name Type Required Description
validator UseValidatorSpec Yes A Validator instance (should implement _chunking_function for streaming)
on str No Validation target: "output" (default)

Outputs

Name Type Description
self Guard Returns the Guard instance (fluent chaining)

Usage Examples

Streaming Guard Setup

from guardrails import Guard
from guardrails.hub import ToxicLanguage

# Same .use() API as non-streaming
guard = Guard().use(ToxicLanguage(on_fail="fix"))

# The difference is in how it's called (stream=True)
stream = guard(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Tell me a story."}],
    stream=True,
)
for chunk in stream:
    print(chunk.validated_output, end="", flush=True)

Related Pages

Implements Principle

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment