Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

pyrit.registry

Registry module for PyRIT class and instance registries.

Functions

discover_in_directory

discover_in_directory(directory: Path, base_class: type[T], recursive: bool = True) → Iterator[tuple[str, Path, type[T]]]

Discover all subclasses of base_class in a directory by loading Python files.

This function walks a directory, loads Python files dynamically, and yields any classes that are subclasses of the specified base_class.

ParameterTypeDescription
directoryPathThe directory to search for Python files.
base_classtype[T]The base class to filter subclasses of.
recursiveboolWhether to recursively search subdirectories. Defaults to True. Defaults to True.

discover_in_package

discover_in_package(package_path: Path, package_name: str, base_class: type[T], recursive: bool = True, name_builder: Optional[Callable[[str, str], str]] = None, _prefix: str = '') → Iterator[tuple[str, type[T]]]

Discover all subclasses using pkgutil.iter_modules on a package.

This function uses Python’s package infrastructure to discover modules, making it suitable for discovering classes in installed packages.

ParameterTypeDescription
package_pathPathThe filesystem path to the package directory.
package_namestrThe dotted module name of the package (e.g., “pyrit.scenario.scenarios”).
base_classtype[T]The base class to filter subclasses of.
recursiveboolWhether to recursively search subpackages. Defaults to True. Defaults to True.
name_builderOptional[Callable[[str, str], str]]Optional callable to build the registry name from (prefix, module_name). Defaults to returning just the module_name. Defaults to None.
_prefixstrInternal parameter to track the current subdirectory prefix. Defaults to ''.

discover_subclasses_in_loaded_modules

discover_subclasses_in_loaded_modules(base_class: type[T], exclude_module_prefixes: Optional[tuple[str, ...]] = None) → Iterator[tuple[str, type[T]]]

Discover subclasses of a base class from already-loaded modules.

This is useful for discovering user-defined classes that were loaded via initialization scripts or dynamic imports.

ParameterTypeDescription
base_classtype[T]The base class to filter subclasses of.
exclude_module_prefixesOptional[tuple[str, ...]]Module prefixes to exclude from search. Defaults to common system modules. Defaults to None.

BaseClassRegistry

Bases: ABC, RegistryProtocol[MetadataT], Generic[T, MetadataT]

Abstract base class for registries that store classes (Type[T]).

This class implements RegistryProtocol and provides the common infrastructure for class registries including:

Subclasses must implement:

Constructor Parameters:

ParameterTypeDescription
lazy_discoveryboolIf True, discovery is deferred until first access. If False, discovery runs immediately in constructor. Defaults to True.

Methods:

create_instance

create_instance(name: str, kwargs: object = {}) → T

Create an instance of a registered class.

ParameterTypeDescription
namestrThe registry name of the class.
**kwargsobjectKeyword arguments to pass to the factory or constructor. Defaults to {}.

Returns:

Raises:

get_class

get_class(name: str) → type[T]

Get a registered class by name.

ParameterTypeDescription
namestrThe registry name (snake_case identifier).

Returns:

Raises:

get_entry

get_entry(name: str) → Optional[ClassEntry[T]]

Get the full ClassEntry for a registered class.

This is useful when you need access to factory or default_kwargs.

ParameterTypeDescription
namestrThe registry name.

Returns:

get_names

get_names() → list[str]

Get a sorted list of all registered names.

These are the snake_case registry keys (e.g., “encoding”, “self_ask_refusal”), not the actual class names (e.g., “EncodingScenario”, “SelfAskRefusalScorer”).

Returns:

get_registry_singleton

get_registry_singleton() → BaseClassRegistry[T, MetadataT]

Get the singleton instance of this registry.

Creates the instance on first call with default parameters.

Returns:

list_metadata

list_metadata(include_filters: Optional[dict[str, object]] = None, exclude_filters: Optional[dict[str, object]] = None) → list[MetadataT]

List metadata for all registered classes, optionally filtered.

Supports filtering on any metadata property:

ParameterTypeDescription
include_filtersOptional[dict[str, object]]Optional dict of filters that items must match. Keys are metadata property names, values are the filter criteria. All filters must match (AND logic). Defaults to None.
exclude_filtersOptional[dict[str, object]]Optional dict of filters that items must NOT match. Keys are metadata property names, values are the filter criteria. Any matching filter excludes the item. Defaults to None.

Returns:

register

register(name: Optional[str] = None, factory: Optional[Callable[..., T]] = None, default_kwargs: Optional[dict[str, object]] = None, description: Optional[str] = None) → None

Register a class with the registry.

ParameterTypeDescription
clstype[T]The class to register (Type[T], not an instance).
nameOptional[str]Optional custom registry name. If not provided, derived from class name. Defaults to None.
factoryOptional[Callable[..., T]]Optional callable for creating instances with custom logic. Defaults to None.
default_kwargsOptional[dict[str, object]]Default keyword arguments for instance creation. Defaults to None.
descriptionOptional[str]Optional description override. Defaults to None.

reset_instance

reset_instance() → None

Reset the singleton instance.

Useful for testing or when re-discovery is needed.

BaseInstanceRegistry

Bases: ABC, RegistryProtocol[MetadataT], Generic[T, MetadataT]

Abstract base class for registries that store pre-configured instances.

This class implements RegistryProtocol. Unlike BaseClassRegistry which stores Type[T] and supports lazy discovery, instance registries store already-instantiated objects that are registered explicitly (typically during initialization).

Methods:

get

get(name: str) → Optional[T]

Get a registered instance by name.

ParameterTypeDescription
namestrThe registry name of the instance.

Returns:

get_all_instances

get_all_instances() → list[RegistryEntry[T]]

Get all registered entries sorted by name.

Returns:

get_by_tag

get_by_tag(tag: str, value: Optional[str] = None) → list[RegistryEntry[T]]

Get all entries that have a given tag, optionally matching a specific value.

ParameterTypeDescription
tagstrThe tag key to match.
valueOptional[str]If provided, only entries whose tag value equals this are returned. If None, any entry that has the tag key is returned regardless of value. Defaults to None.

Returns:

get_entry

get_entry(name: str) → Optional[RegistryEntry[T]]

Get a full registry entry by name, including tags.

ParameterTypeDescription
namestrThe registry name of the entry.

Returns:

get_names

get_names() → list[str]

Get a sorted list of all registered names.

Returns:

get_registry_singleton

get_registry_singleton() → BaseInstanceRegistry[T, MetadataT]

Get the singleton instance of this registry.

Creates the instance on first call with default parameters.

Returns:

list_metadata

list_metadata(include_filters: Optional[dict[str, object]] = None, exclude_filters: Optional[dict[str, object]] = None) → list[MetadataT]

List metadata for all registered instances, optionally filtered.

Supports filtering on any metadata property:

ParameterTypeDescription
include_filtersOptional[dict[str, object]]Optional dict of filters that items must match. Keys are metadata property names, values are the filter criteria. All filters must match (AND logic). Defaults to None.
exclude_filtersOptional[dict[str, object]]Optional dict of filters that items must NOT match. Keys are metadata property names, values are the filter criteria. Any matching filter excludes the item. Defaults to None.

Returns:

register

register(instance: T, name: str, tags: Optional[Union[dict[str, str], list[str]]] = None) → None

Register an instance.

ParameterTypeDescription
instanceTThe pre-configured instance to register.
namestrThe registry name for this instance.
tagsOptional[Union[dict[str, str], list[str]]]Optional tags for categorisation. Accepts a dict[str, str] or a list[str] (each string becomes a key with value ""). Defaults to None.

reset_instance

reset_instance() → None

Reset the singleton instance.

Useful for testing or reinitializing the registry.

ClassEntry

Bases: Generic[T]

Internal wrapper for a registered class.

This holds the class itself (Type[T]) along with optional factory and default parameters for creating instances.

Note: This is an internal implementation detail. Users interact with registries via get_class(), create_instance(), and list_metadata().

Constructor Parameters:

ParameterTypeDescription
registered_classtype[T]The actual Python class (Type[T]).
factoryOptional[Callable[..., T]]Optional callable that creates an instance. Defaults to None.
default_kwargsOptional[dict[str, object]]Default keyword arguments for instantiation. Defaults to None.
descriptionOptional[str]Optional description override. Defaults to None.

Methods:

create_instance

create_instance(kwargs: object = {}) → T

Create an instance of the registered class.

ParameterTypeDescription
**kwargsobjectAdditional keyword arguments. These override default_kwargs. Defaults to {}.

Returns:

InitializerMetadata

Bases: ClassRegistryEntry

Metadata describing a registered PyRITInitializer class.

Use get_class() to get the actual class.

InitializerRegistry

Bases: BaseClassRegistry['PyRITInitializer', InitializerMetadata]

Registry for discovering and managing available initializers.

This class discovers all PyRITInitializer subclasses from the pyrit/setup/initializers directory structure.

Initializers are identified by their filename (e.g., “objective_target”, “simple”). The directory structure is used for organization but not exposed to users.

Constructor Parameters:

ParameterTypeDescription
discovery_pathOptional[Path]The path to discover initializers from. If None, defaults to pyrit/setup/initializers (discovers all). To discover only scenarios, pass pyrit/setup/initializers/scenarios. Defaults to None.
lazy_discoveryboolIf True, discovery is deferred until first access. Defaults to False for backwards compatibility. Defaults to False.

Methods:

get_registry_singleton

get_registry_singleton() → InitializerRegistry

Get the singleton instance of the InitializerRegistry.

Returns:

resolve_initializer_paths

resolve_initializer_paths(initializer_names: list[str]) → list[Path]

Resolve initializer names to their file paths.

ParameterTypeDescription
initializer_nameslist[str]List of initializer names to resolve.

Returns:

Raises:

resolve_script_paths

resolve_script_paths(script_paths: list[str]) → list[Path]

Resolve and validate custom script paths.

ParameterTypeDescription
script_pathslist[str]List of script path strings to resolve.

Returns:

Raises:

RegistryEntry

Bases: Generic[T]

A wrapper around a registered instance, holding its name, tags, and the instance itself.

Tags are always stored as dict[str, str]. When callers pass a plain list[str], each string is normalized to a key with an empty-string value.

RegistryProtocol

Bases: Protocol[MetadataT]

Protocol defining the common interface for all registries.

Both class registries (BaseClassRegistry) and instance registries (BaseInstanceRegistry) implement this interface, enabling code that works with either registry type.

Methods:

get_names

get_names() → list[str]

Get a sorted list of all registered names.

get_registry_singleton

get_registry_singleton() → RegistryProtocol[MetadataT]

Get the singleton instance of this registry.

list_metadata

list_metadata(include_filters: Optional[dict[str, Any]] = None, exclude_filters: Optional[dict[str, Any]] = None) → list[MetadataT]

List metadata for all registered items, optionally filtered.

ParameterTypeDescription
include_filtersOptional[dict[str, Any]]Optional dict of filters that items must match. Keys are metadata property names, values are the filter criteria. All filters must match (AND logic). Defaults to None.
exclude_filtersOptional[dict[str, Any]]Optional dict of filters that items must NOT match. Keys are metadata property names, values are the filter criteria. Any matching filter excludes the item. Defaults to None.

Returns:

reset_instance

reset_instance() → None

Reset the singleton instance.

ScenarioMetadata

Bases: ClassRegistryEntry

Metadata describing a registered Scenario class.

Use get_class() to get the actual class.

ScenarioRegistry

Bases: BaseClassRegistry['Scenario', ScenarioMetadata]

Registry for discovering and managing available scenario classes.

This class discovers all Scenario subclasses from:

  1. Built-in scenarios in pyrit.scenario.scenarios module

  2. User-defined scenarios from initialization scripts (set via globals)

Scenarios are identified by their simple name (e.g., “encoding”, “foundry”).

Constructor Parameters:

ParameterTypeDescription
lazy_discoveryboolIf True, discovery is deferred until first access. Defaults to True for performance. Defaults to True.

Methods:

discover_user_scenarios

discover_user_scenarios() → None

Discover user-defined scenarios from global variables.

After initialization scripts are executed, they may define Scenario subclasses and store them in globals. This method searches for such classes.

User scenarios will override built-in scenarios with the same name.

get_registry_singleton

get_registry_singleton() → ScenarioRegistry

Get the singleton instance of the ScenarioRegistry.

Returns:

ScorerRegistry

Bases: BaseInstanceRegistry['Scorer', ComponentIdentifier]

Registry for managing available scorer instances.

This registry stores pre-configured Scorer instances (not classes). Scorers are registered explicitly via initializers after being instantiated with their required parameters (e.g., chat_target).

Scorers are identified by their snake_case name derived from the class name, or a custom name provided during registration.

Methods:

get_instance_by_name

get_instance_by_name(name: str) → Optional[Scorer]

Get a registered scorer instance by name.

Note: This returns an already-instantiated scorer, not a class.

ParameterTypeDescription
namestrThe registry name of the scorer.

Returns:

get_registry_singleton

get_registry_singleton() → ScorerRegistry

Get the singleton instance of the ScorerRegistry.

Returns:

register_instance

register_instance(scorer: Scorer, name: Optional[str] = None, tags: Optional[Union[dict[str, str], list[str]]] = None) → None

Register a scorer instance.

Note: Unlike ScenarioRegistry and InitializerRegistry which register classes, ScorerRegistry registers pre-configured instances.

ParameterTypeDescription
scorerScorerThe pre-configured scorer instance (not a class).
nameOptional[str]Optional custom registry name. If not provided, derived from the scorer’s unique identifier. Defaults to None.
tagsOptional[Union[dict[str, str], list[str]]]Optional tags for categorisation. Accepts a dict[str, str] or a list[str] (each string becomes a key with value ""). Defaults to None.

TargetRegistry

Bases: BaseInstanceRegistry['PromptTarget', ComponentIdentifier]

Registry for managing available prompt target instances.

This registry stores pre-configured PromptTarget instances (not classes). Targets are registered explicitly via initializers after being instantiated with their required parameters (e.g., endpoint, API keys).

Targets are identified by their snake_case name derived from the class name, or a custom name provided during registration.

Methods:

get_instance_by_name

get_instance_by_name(name: str) → Optional[PromptTarget]

Get a registered target instance by name.

Note: This returns an already-instantiated target, not a class.

ParameterTypeDescription
namestrThe registry name of the target.

Returns:

get_registry_singleton

get_registry_singleton() → TargetRegistry

Get the singleton instance of the TargetRegistry.

Returns:

register_instance

register_instance(target: PromptTarget, name: Optional[str] = None, tags: Optional[Union[dict[str, str], list[str]]] = None) → None

Register a target instance.

Note: Unlike ScenarioRegistry and InitializerRegistry which register classes, TargetRegistry registers pre-configured instances.

ParameterTypeDescription
targetPromptTargetThe pre-configured target instance (not a class).
nameOptional[str]Optional custom registry name. If not provided, derived from class name with identifier hash appended (e.g., OpenAIChatTarget -> openai_chat_abc123). Defaults to None.
tagsOptional[Union[dict[str, str], list[str]]]Optional tags for categorization. Accepts a dict[str, str] or a list[str] (each string becomes a key with value ""). Defaults to None.