Skip to content

Registry

Registry for managing GuardrailSpec instances and maintaining a catalog of guardrails.

This module provides the in-memory registry that acts as the authoritative catalog for all available guardrail specifications. The registry supports registration, lookup, removal, and metadata inspection for guardrails, enabling extensibility and dynamic discovery across your application.

default_spec_registry module-attribute

default_spec_registry = GuardrailRegistry()

Global default registry for guardrail specifications.

This instance should be used for registration and lookup unless a custom registry is explicitly required.

Metadata dataclass

Metadata snapshot for a guardrail specification.

This container bundles descriptive and structural details about a guardrail for inspection, discovery, or documentation.

Attributes:

Name Type Description
name str

Unique identifier for the guardrail.

description str

Explanation of what the guardrail checks.

media_type str

MIME type (e.g. "text/plain") the guardrail applies to.

config_schema dict[str, Any] | None

JSON schema for the guardrail's config model.

metadata dict[str, Any] | None

Additional metadata (e.g., engine type).

Source code in src/guardrails/registry.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
@dataclass(frozen=True, slots=True)
class Metadata:
    """Metadata snapshot for a guardrail specification.

    This container bundles descriptive and structural details about a guardrail
    for inspection, discovery, or documentation.

    Attributes:
        name (str): Unique identifier for the guardrail.
        description (str): Explanation of what the guardrail checks.
        media_type (str): MIME type (e.g. "text/plain") the guardrail applies to.
        config_schema (dict[str, Any] | None): JSON schema for the guardrail's config model.
        metadata (dict[str, Any] | None): Additional metadata (e.g., engine type).
    """

    name: str
    description: str
    media_type: str
    config_schema: dict[str, Any] | None
    metadata: dict[str, Any] | None = None

GuardrailRegistry

Central registry for all registered guardrail specifications.

This class provides methods to register, remove, and look up :class:GuardrailSpec objects by name. It supports dynamic extension of available guardrails and powers discovery and validation throughout the package.

Typical usage
registry = GuardrailRegistry()
registry.register(...)
spec = registry.get("my_guardrail")
all_specs = registry.get_all()
Source code in src/guardrails/registry.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
class GuardrailRegistry:
    """Central registry for all registered guardrail specifications.

    This class provides methods to register, remove, and look up
    :class:`GuardrailSpec` objects by name. It supports dynamic extension
    of available guardrails and powers discovery and validation
    throughout the package.

    Typical usage:
        ```python
        registry = GuardrailRegistry()
        registry.register(...)
        spec = registry.get("my_guardrail")
        all_specs = registry.get_all()
        ```
    """

    def __init__(self) -> None:
        """Initialize an empty registry of guardrail specifications."""
        self._guardrailspecs: dict[str, GuardrailSpec[Any, Any, Any]] = {}
        self._logger = logging.getLogger(__name__ + ".GuardrailSpecRegistry")

    def register(
        self,
        name: str,
        check_fn: CheckFn[TContext, TIn, Any],
        description: str,
        media_type: str,
        *,
        metadata: GuardrailSpecMetadata | None = None,
    ) -> None:
        """Register a new guardrail specification.

        This adds a :class:`GuardrailSpec` to the registry, inferring the required
        context and configuration models from the function signature.

        Args:
            name (str): Unique identifier for the guardrail.
            check_fn (CheckFn): Function that implements the guardrail logic.
            description (str): Human-readable description for docs and discovery.
            media_type (str): MIME type this guardrail operates on.
            metadata (GuardrailSpecMetadata, optional): Additional details for UIs or tooling.

        Raises:
            ValueError: If `media_type` is not a valid MIME type, or if `name`
                is already registered.

        Example:
            ```python
            registry.register(
                name="keyword_filter",
                check_fn=keywords,
                description="Triggers if text contains banned keywords.",
                media_type="text/plain",
            )
            ```
        """
        if name in self._guardrailspecs:
            existing = self._guardrailspecs[name]
            self._logger.error("Duplicate registration attempted for '%s'", name)
            msg = (
                f"Guardrail name '{name}' already bound to {existing.check_fn.__qualname__}. "
                "Pick a distinct name or rename the function."
            )
            raise ValueError(msg)

        if isinstance(media_type, str) and not MIME_RE.match(media_type):
            msg = f"Invalid media-type '{media_type}'"
            raise ValueError(msg)

        resolved_ctx = _resolve_ctx_requirements(check_fn)
        resolved_config_schema = _resolve_config_schema(check_fn)

        _name = name or check_fn.__name__
        guardrailspec = GuardrailSpec(
            name=_name,
            description=description,
            media_type=media_type,
            config_schema=resolved_config_schema,
            check_fn=check_fn,
            ctx_requirements=resolved_ctx,
            metadata=metadata or GuardrailSpecMetadata(),
        )

        self._guardrailspecs[guardrailspec.name] = guardrailspec
        self._logger.debug("Registered guardrail spec '%s'", guardrailspec.name)

    def remove(self, name: str) -> None:
        """Remove a registered guardrail specification by name.

        Args:
            name (str): The guardrail name to remove.

        Raises:
            KeyError: If `name` is not present in the registry.
        """
        if name in self._guardrailspecs:
            del self._guardrailspecs[name]
            return
        msg = f"Guardrail spec '{name}' not found."
        raise KeyError(msg)

    def get(self, name: str) -> GuardrailSpec[Any, Any, Any]:
        """Retrieve a registered guardrail specification by name.

        Args:
            name (str): The name passed to :meth:`register`.

        Returns:
            GuardrailSpec: The registered guardrail specification.

        Raises:
            KeyError: If nothing is registered under `name`.
        """
        if name in self._guardrailspecs:
            return self._guardrailspecs[name]
        self._logger.warning("Attempted lookup of unknown guardrail '%s'", name)
        msg = f"Guardrail spec '{name}' not found."
        raise KeyError(msg)

    def get_all(self) -> list[GuardrailSpec[Any, Any, Any]]:
        """Return a list of all registered guardrail specifications.

        Returns:
            list[GuardrailSpec]: All registered specs, in registration order.
        """
        return list(self._guardrailspecs.values())

    def get_all_metadata(self) -> list[Metadata]:
        """Return summary metadata for all registered guardrail specifications.

        This provides lightweight, serializable descriptions of all guardrails,
        suitable for documentation, UI display, or catalog listing.

        Returns:
            list[Metadata]: List of metadata entries for each registered spec.
        """
        return [
            Metadata(
                name=d.name,
                description=d.description,
                media_type=d.media_type,
                config_schema=d.schema(),
                metadata=d.metadata.model_dump() if d.metadata else {},
            )
            for d in self._guardrailspecs.values()
        ]

__init__

__init__() -> None

Initialize an empty registry of guardrail specifications.

Source code in src/guardrails/registry.py
129
130
131
132
def __init__(self) -> None:
    """Initialize an empty registry of guardrail specifications."""
    self._guardrailspecs: dict[str, GuardrailSpec[Any, Any, Any]] = {}
    self._logger = logging.getLogger(__name__ + ".GuardrailSpecRegistry")

register

register(
    name: str,
    check_fn: CheckFn[TContext, TIn, Any],
    description: str,
    media_type: str,
    *,
    metadata: GuardrailSpecMetadata | None = None,
) -> None

Register a new guardrail specification.

This adds a :class:GuardrailSpec to the registry, inferring the required context and configuration models from the function signature.

Parameters:

Name Type Description Default
name str

Unique identifier for the guardrail.

required
check_fn CheckFn

Function that implements the guardrail logic.

required
description str

Human-readable description for docs and discovery.

required
media_type str

MIME type this guardrail operates on.

required
metadata GuardrailSpecMetadata

Additional details for UIs or tooling.

None

Raises:

Type Description
ValueError

If media_type is not a valid MIME type, or if name is already registered.

Example
registry.register(
    name="keyword_filter",
    check_fn=keywords,
    description="Triggers if text contains banned keywords.",
    media_type="text/plain",
)
Source code in src/guardrails/registry.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def register(
    self,
    name: str,
    check_fn: CheckFn[TContext, TIn, Any],
    description: str,
    media_type: str,
    *,
    metadata: GuardrailSpecMetadata | None = None,
) -> None:
    """Register a new guardrail specification.

    This adds a :class:`GuardrailSpec` to the registry, inferring the required
    context and configuration models from the function signature.

    Args:
        name (str): Unique identifier for the guardrail.
        check_fn (CheckFn): Function that implements the guardrail logic.
        description (str): Human-readable description for docs and discovery.
        media_type (str): MIME type this guardrail operates on.
        metadata (GuardrailSpecMetadata, optional): Additional details for UIs or tooling.

    Raises:
        ValueError: If `media_type` is not a valid MIME type, or if `name`
            is already registered.

    Example:
        ```python
        registry.register(
            name="keyword_filter",
            check_fn=keywords,
            description="Triggers if text contains banned keywords.",
            media_type="text/plain",
        )
        ```
    """
    if name in self._guardrailspecs:
        existing = self._guardrailspecs[name]
        self._logger.error("Duplicate registration attempted for '%s'", name)
        msg = (
            f"Guardrail name '{name}' already bound to {existing.check_fn.__qualname__}. "
            "Pick a distinct name or rename the function."
        )
        raise ValueError(msg)

    if isinstance(media_type, str) and not MIME_RE.match(media_type):
        msg = f"Invalid media-type '{media_type}'"
        raise ValueError(msg)

    resolved_ctx = _resolve_ctx_requirements(check_fn)
    resolved_config_schema = _resolve_config_schema(check_fn)

    _name = name or check_fn.__name__
    guardrailspec = GuardrailSpec(
        name=_name,
        description=description,
        media_type=media_type,
        config_schema=resolved_config_schema,
        check_fn=check_fn,
        ctx_requirements=resolved_ctx,
        metadata=metadata or GuardrailSpecMetadata(),
    )

    self._guardrailspecs[guardrailspec.name] = guardrailspec
    self._logger.debug("Registered guardrail spec '%s'", guardrailspec.name)

remove

remove(name: str) -> None

Remove a registered guardrail specification by name.

Parameters:

Name Type Description Default
name str

The guardrail name to remove.

required

Raises:

Type Description
KeyError

If name is not present in the registry.

Source code in src/guardrails/registry.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def remove(self, name: str) -> None:
    """Remove a registered guardrail specification by name.

    Args:
        name (str): The guardrail name to remove.

    Raises:
        KeyError: If `name` is not present in the registry.
    """
    if name in self._guardrailspecs:
        del self._guardrailspecs[name]
        return
    msg = f"Guardrail spec '{name}' not found."
    raise KeyError(msg)

get

get(name: str) -> GuardrailSpec[Any, Any, Any]

Retrieve a registered guardrail specification by name.

Parameters:

Name Type Description Default
name str

The name passed to :meth:register.

required

Returns:

Name Type Description
GuardrailSpec GuardrailSpec[Any, Any, Any]

The registered guardrail specification.

Raises:

Type Description
KeyError

If nothing is registered under name.

Source code in src/guardrails/registry.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def get(self, name: str) -> GuardrailSpec[Any, Any, Any]:
    """Retrieve a registered guardrail specification by name.

    Args:
        name (str): The name passed to :meth:`register`.

    Returns:
        GuardrailSpec: The registered guardrail specification.

    Raises:
        KeyError: If nothing is registered under `name`.
    """
    if name in self._guardrailspecs:
        return self._guardrailspecs[name]
    self._logger.warning("Attempted lookup of unknown guardrail '%s'", name)
    msg = f"Guardrail spec '{name}' not found."
    raise KeyError(msg)

get_all

get_all() -> list[GuardrailSpec[Any, Any, Any]]

Return a list of all registered guardrail specifications.

Returns:

Type Description
list[GuardrailSpec[Any, Any, Any]]

list[GuardrailSpec]: All registered specs, in registration order.

Source code in src/guardrails/registry.py
232
233
234
235
236
237
238
def get_all(self) -> list[GuardrailSpec[Any, Any, Any]]:
    """Return a list of all registered guardrail specifications.

    Returns:
        list[GuardrailSpec]: All registered specs, in registration order.
    """
    return list(self._guardrailspecs.values())

get_all_metadata

get_all_metadata() -> list[Metadata]

Return summary metadata for all registered guardrail specifications.

This provides lightweight, serializable descriptions of all guardrails, suitable for documentation, UI display, or catalog listing.

Returns:

Type Description
list[Metadata]

list[Metadata]: List of metadata entries for each registered spec.

Source code in src/guardrails/registry.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def get_all_metadata(self) -> list[Metadata]:
    """Return summary metadata for all registered guardrail specifications.

    This provides lightweight, serializable descriptions of all guardrails,
    suitable for documentation, UI display, or catalog listing.

    Returns:
        list[Metadata]: List of metadata entries for each registered spec.
    """
    return [
        Metadata(
            name=d.name,
            description=d.description,
            media_type=d.media_type,
            config_schema=d.schema(),
            metadata=d.metadata.model_dump() if d.metadata else {},
        )
        for d in self._guardrailspecs.values()
    ]