Types: Python
Type definitions, Protocols, and result types for Guardrails.
This module provides core types for implementing Guardrails, including:
- The
GuardrailResultdataclass, representing the outcome of a guardrail check. - The
CheckFnProtocol, 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.
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.
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 | |
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 | |
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. Implementations may include a 'checked_text' field containing the processed/validated text when applicable. Defaults to an empty dict. |
Source code in src/guardrails/types.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | |
__post_init__
__post_init__() -> None
Validate required fields and consistency.
Source code in src/guardrails/types.py
74 75 76 77 78 | |