Skip to content

Types: Python

Type definitions, Protocols, and result types for Guardrails.

This module provides core types for implementing Guardrails, including:

  • The GuardrailResult dataclass, representing the outcome of a guardrail check.
  • The CheckFn Protocol, a callable interface for all guardrail functions.

CheckFn module-attribute

CheckFn = Callable[
    [TContext, TIn, TCfg], MaybeAwaitableResult
]

Type alias for a guardrail function.

A guardrail function accepts a context object, input data, and a configuration object, returning either a GuardrailResult or an awaitable resolving to GuardrailResult.

Parameters:

Name Type Description Default
TContext TypeVar

The context type (often includes resources used by a guardrail).

required
TIn TypeVar

The input data to validate or check.

required
TCfg TypeVar

The configuration type, usually a Pydantic model.

required

Returns: GuardrailResult or Awaitable[GuardrailResult]: The outcome of the guardrail check. The result must include 'checked_text' in the info dict.

GuardrailLLMContextProto

Bases: Protocol

Protocol for context types providing an OpenAI client.

Classes implementing this protocol must expose an OpenAI client via the guardrail_llm attribute. For conversation-aware guardrails (like prompt injection detection), they can also access conversation_history containing the full conversation history and incremental tracking methods.

Attributes:

Name Type Description
guardrail_llm AsyncOpenAI | OpenAI

The OpenAI client used by the guardrail.

conversation_history list

Full conversation history for conversation-aware guardrails.

Source code in src/guardrails/types.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@runtime_checkable
class GuardrailLLMContextProto(Protocol):
    """Protocol for context types providing an OpenAI client.

    Classes implementing this protocol must expose an OpenAI client
    via the `guardrail_llm` attribute. For conversation-aware guardrails
    (like prompt injection detection), they can also access `conversation_history` containing
    the full conversation history and incremental tracking methods.

    Attributes:
        guardrail_llm (AsyncOpenAI | OpenAI): The OpenAI client used by the guardrail.
        conversation_history (list, optional): Full conversation history for conversation-aware guardrails.
    """

    guardrail_llm: AsyncOpenAI | OpenAI | AsyncAzureOpenAI | AzureOpenAI

    def get_conversation_history(self) -> list | None:
        """Get conversation history if available, None otherwise."""
        return getattr(self, "conversation_history", None)

    def get_injection_last_checked_index(self) -> int:
        """Get the last checked index for incremental prompt injection detection checking."""
        return getattr(self, "injection_last_checked_index", 0)

    def update_injection_last_checked_index(self, new_index: int) -> None:
        """Update the last checked index for incremental prompt injection detection checking."""
        if hasattr(self, "_client"):
            getattr(self, "_client")._injection_last_checked_index = new_index

get_conversation_history

get_conversation_history() -> list | None

Get conversation history if available, None otherwise.

Source code in src/guardrails/types.py
46
47
48
def get_conversation_history(self) -> list | None:
    """Get conversation history if available, None otherwise."""
    return getattr(self, "conversation_history", None)

get_injection_last_checked_index

get_injection_last_checked_index() -> int

Get the last checked index for incremental prompt injection detection checking.

Source code in src/guardrails/types.py
50
51
52
def get_injection_last_checked_index(self) -> int:
    """Get the last checked index for incremental prompt injection detection checking."""
    return getattr(self, "injection_last_checked_index", 0)

update_injection_last_checked_index

update_injection_last_checked_index(new_index: int) -> None

Update the last checked index for incremental prompt injection detection checking.

Source code in src/guardrails/types.py
54
55
56
57
def update_injection_last_checked_index(self, new_index: int) -> None:
    """Update the last checked index for incremental prompt injection detection checking."""
    if hasattr(self, "_client"):
        getattr(self, "_client")._injection_last_checked_index = new_index

GuardrailResult dataclass

Result returned from a guardrail check.

This dataclass encapsulates the outcome of a guardrail function, including whether a tripwire was triggered, execution failure status, and any supplementary metadata.

Attributes:

Name Type Description
tripwire_triggered bool

True if the guardrail identified a critical failure.

execution_failed bool

True if the guardrail failed to execute properly.

original_exception Exception | None

The original exception if execution failed.

info dict[str, Any]

Additional structured data about the check result, such as error details, matched patterns, or diagnostic messages. Must include 'checked_text' field containing the processed/validated text. Defaults to an empty dict.

Source code in src/guardrails/types.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
@dataclass(frozen=True, slots=True)
class GuardrailResult:
    """Result returned from a guardrail check.

    This dataclass encapsulates the outcome of a guardrail function,
    including whether a tripwire was triggered, execution failure status,
    and any supplementary metadata.

    Attributes:
        tripwire_triggered (bool): True if the guardrail identified a critical failure.
        execution_failed (bool): True if the guardrail failed to execute properly.
        original_exception (Exception | None): The original exception if execution failed.
        info (dict[str, Any]): Additional structured data about the check result,
            such as error details, matched patterns, or diagnostic messages.
            Must include 'checked_text' field containing the processed/validated text.
            Defaults to an empty dict.
    """

    tripwire_triggered: bool
    execution_failed: bool = False
    original_exception: Exception | None = None
    info: dict[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Validate required fields and consistency."""
        if "checked_text" not in self.info:
            raise ValueError("GuardrailResult.info must contain 'checked_text' field")

        # Ensure consistency: if execution_failed=True, original_exception should be present
        if self.execution_failed and self.original_exception is None:
            raise ValueError(
                "When execution_failed=True, original_exception must be provided"
            )

__post_init__

__post_init__() -> None

Validate required fields and consistency.

Source code in src/guardrails/types.py
83
84
85
86
87
88
89
90
91
92
def __post_init__(self) -> None:
    """Validate required fields and consistency."""
    if "checked_text" not in self.info:
        raise ValueError("GuardrailResult.info must contain 'checked_text' field")

    # Ensure consistency: if execution_failed=True, original_exception should be present
    if self.execution_failed and self.original_exception is None:
        raise ValueError(
            "When execution_failed=True, original_exception must be provided"
        )