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 object registries.

Functions

allows_credential_updates

allows_credential_updates(entry: RegistryEntry[Any]) → bool

Check whether an entry’s credentials can be updated in place through the API.

ParameterTypeDescription
entryRegistryEntry[Any]The entry.

Returns:

creator_metadata

creator_metadata(name: str, requested_private: bool | None, private_references: Mapping[str, str]) → dict[str, Any]

Decide whether a component created by the caller in scope is private, and record its creator.

A component is shared unless the request makes it private. A component built on the caller’s private entries is always private, so a shared component never uses one. With no caller in scope, such as server setup, a component is shared and has no owner.

ParameterTypeDescription
namestrThe new component’s name, for errors.
requested_privatebool | NoneThe visibility the request asked for, or None for the default.
private_referencesMapping[str, str]The private entries the component was built on, from record_private_references.

Returns:

Raises:

credential_update_metadata

credential_update_metadata(allowed: bool) → dict[str, Any]

Return the entry metadata that decides whether a target’s credentials can be updated through the API.

Pass it to register with the target, for example from an initializer that registers a shared target whose token expires: registry.instances.register(target, name=..., metadata=credential_update_metadata( allowed=True)). Anyone signed in can then update the shared target’s API key or request headers.

ParameterTypeDescription
allowedboolWhether the target’s credentials can be updated.

Returns:

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. Members are inspected statically, with dynamic lookup limited to exports declared in the module’s __all__.

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.

get_class_saveability

get_class_saveability(registry: Registry[Any, Any], type_name: str) → tuple[tuple[str, ...], str | None]

Return the auth modes a saved entry of a registered class can use, or why none can.

This is the class-level answer, before any of the entry’s values are known; the values are checked when it’s saved.

ParameterTypeDescription
registryRegistry[Any, Any]The registry the class is registered in.
type_namestrThe name the class is registered under.

Returns:

get_entry_owner

get_entry_owner(entry: RegistryEntry[Any]) → str | None

Return the principal that created an entry.

ParameterTypeDescription
entryRegistryEntry[Any]The entry.

Returns:

get_lazy_dir

get_lazy_dir(module_globals: dict[str, Any], exports: Mapping[str, LazyExport]) → list[str]

Return package attributes and unresolved public exports.

ParameterTypeDescription
module_globalsdict[str, Any]The package globals.
exportsMapping[str, LazyExport]Public names and their implementation locations.

Returns:

is_private_entry

is_private_entry(entry: RegistryEntry[Any]) → bool

Check whether only an entry’s owner can see and use it.

ParameterTypeDescription
entryRegistryEntry[Any]The entry.

Returns:

is_visible_to_caller

is_visible_to_caller(entry: RegistryEntry[Any]) → bool

Apply the access rule: a private entry is visible only to its owner; every other entry to everyone.

The caller is the one in scope (pyrit.auth.get_caller_principal). Work with no caller in scope sees no private entries.

ParameterTypeDescription
entryRegistryEntry[Any]The entry.

Returns:

owner_metadata

owner_metadata(owner: str | None, private: bool) → dict[str, Any]

Return the entry metadata that records who created an entry and whether it is private.

ParameterTypeDescription
ownerstr | NoneThe creating caller principal, or None for an entry without one.
privateboolWhether only the owner can see and use the entry. Requires an owner.

Returns:

Raises:

prepare_saved_params_async

prepare_saved_params_async(registry: InstanceHoldingRegistry[Any, Any], type_name: str, params: Mapping[str, Any], auth_mode: str | None = None) → dict[str, Any]

Turn off the server values an entry to save would read, then refuse what it still can’t hold.

ParameterTypeDescription
registryInstanceHoldingRegistry[Any, Any]The registry the entry’s class is registered in.
type_namestrThe name the class is registered under.
clstypeThe class the entry is built from.
paramsMapping[str, Any]The entry’s constructor parameters.
auth_modestr | NoneA target’s auth mode from its create request, or None for converters and scorers. Defaults to None.

Returns:

Raises:

record_private_references

record_private_references() → Generator[dict[str, str], None, None]

Collect the private entries looked up by name or identifier in this context.

A component built from references inside the scope uses a private entry when the mapping is nonempty, so it must be private too (see creator_metadata). The access rule hides every other owner’s private entries, so each one recorded is the caller’s own.

resolve_lazy_export

resolve_lazy_export(name: str, module_name: str, module_globals: dict[str, Any], exports: Mapping[str, LazyExport]) → Any

Resolve and cache one package export.

ParameterTypeDescription
namestrPublic attribute requested from the package.
module_namestrPackage name used in an AttributeError.
module_globalsdict[str, Any]Package globals where the resolved value is cached.
exportsMapping[str, LazyExport]Public names and their implementation locations.

Returns:

Raises:

resolve_scenario_preset_run_request

resolve_scenario_preset_run_request(preset: ScenarioPreset, launch: ScenarioLaunchConfiguration | LaunchScenarioSuiteRequest | ScenarioSuiteReadinessRequest) → RunScenarioRequest

Combine a preset with the target and execution fields it deliberately omits.

Returns:

save_then_register_async

save_then_register_async(kind: RegistryRecipeKind, name: str, recipe: ComponentRecipe, register: Callable[[dict[str, Any]], object], source: str | None = None) → None

Save an entry’s recipe, then register the entry as saved.

The recipe is written only if no saved entry of the kind has the name, so of two saves under one name only one succeeds. If registering then fails, the recipe this save wrote is deleted again. A save that’s cancelled finishes, or is undone, before the cancellation is passed on, so the saved recipes and the registry agree.

ParameterTypeDescription
kindRegistryRecipeKindThe kind of entry.
namestrThe entry’s name.
recipeComponentRecipeHow restore rebuilds the entry.
registerCallable[[dict[str, Any]], object]Registers the built entry with the metadata it’s given.
sourcestr | NoneLocal directory or Azure Blob URI holding the saved entries. Defaults to registry_recipes under the PyRIT configuration directory.

Raises:

AttackRegistry

Bases: Registry['AttackStrategy[Any, Any]', RegistryMetadata]

Discover concrete AttackStrategy classes and build configured attacks.

Uses constructor metadata and the shared resolver. objective_target accepts a registered target name or a live target. Typed configuration objects pass through unchanged. Discovery and metadata do not construct attacks.

This registry stores classes, not live attacks or attack technique factories.

Examples:

Methods:

validate_constructor_parameters

validate_constructor_parameters(attack_class: type[AttackStrategy[Any, Any]], params: dict[str, Any]) → None

Validate attack-owned constraints with constructor defaults, without constructing an attack.

Execution targets and scorers stay deferred. Validation must not use them.

Raises:

AttackTechniqueMetadata

Bases: RegistryMetadata

Shared metadata type for the inherited, empty technique class catalog.

AttackTechniqueRegistry

Bases: Registry['AttackTechniqueFactory', AttackTechniqueMetadata]

Registry that holds reusable AttackTechniqueFactory instances.

Scenarios and initializers register self-describing AttackTechniqueFactory instances; scenarios retrieve them via get_factories / get_factories_or_raise and call factory.create() with the scenario’s objective target and scorer.

It is a Registry: pre-configured factories live under the instances property (register, get, get_all_instances, get_by_tag, …), a DefaultInstanceRegistry. Attack classes come from AttackRegistry; this registry has no separate class catalog.

cache_scenario_technique_class refreshes scenario selection enums when registered factories change. It does not create or cache attack instances.

Constructor Parameters:

ParameterTypeDescription
lazy_discoveryboolIf True, class discovery is deferred until first access. If False, discovery runs immediately. The buildable catalog is empty either way; the flag is accepted for parity with other registries. Defaults to True.

Examples:

Methods:

build_technique_class_from_factories

build_technique_class_from_factories(class_name: str, factories: list[AttackTechniqueFactory], default_tags: set[str] | None = None, default_names: set[str] | None = None) → type[ScenarioTechnique]

Build a ScenarioTechnique enum subclass dynamically from technique factories.

Creates an enum class with:

The catalog’s default — what runs when the caller selects nothing — is defined by exactly one of default_tags or default_names (or neither). Both build the synthetic DEFAULT aggregate and are recorded on the class, returned by ScenarioTechnique.default(). When neither is given, or the chosen set matches no pool technique (e.g. a custom initializer registers no light-tagged factory), the default falls back to ALL. The default is chosen per-scenario, so the same technique can be the default for one scenario and not another.

ParameterTypeDescription
class_namestrName for the generated enum class.
factorieslist[AttackTechniqueFactory]The technique factories that form this scenario’s pool of enum members. Callers pre-filter this list to shape the pool.
default_tagsset[str] | NoneTags whose union defines the scenario’s DEFAULT aggregate — every pool technique carrying any of these tags is the default (e.g. {"light"}). Mutually exclusive with default_names. Defaults to None.
default_namesset[str] | NoneExact technique names that form the scenario’s DEFAULT aggregate. Names not present in the pool are ignored, so a scenario can list its intended default set even when some of those techniques are filtered out. Mutually exclusive with default_tags. Defaults to None.

Returns:

Raises:

cache_scenario_technique_class

cache_scenario_technique_class(builder: Callable[[], type[ScenarioTechnique]]) → _CachedScenarioTechniqueClass

Cache a scenario’s selectable technique enum until registered factories change.

Reuse the same enum class while the registry is unchanged. After registration, removal, or registry reset, the next call builds a new selection enum. Existing scenarios keep their old enum reference. Only the latest result is cached.

ParameterTypeDescription
builderCallable[[], type[ScenarioTechnique]]The scenario’s enum function.

Returns:

create_factory

create_factory(name: str, attack_type: str, params: dict[str, Any] | None = None, request_converters: list[str] | None = None, response_converters: list[str] | None = None, strict_json: bool = False, factory_kwargs: Any = {}) → AttackTechniqueFactory

Resolve basic registry inputs into a factory without creating an attack.

Attack types come from AttackRegistry; converters and the adversarial target reference existing instances. Seeds, scoring configurations, and conversation configurations remain available through Python factories. Strict GUI creation with request converters also selects user and assistant history for replay conversion; simulation generation is unchanged.

Returns:

Raises:

edit_factory

edit_factory(source: AttackTechniqueFactory, changes: TechniqueChanges) → AttackTechniqueFactory

Resolve a partial external edit and validate a private factory copy without registration.

Adding request converters selects both user and assistant history for replay.

Returns:

Raises:

get_constructor_parameters

get_constructor_parameters(factory: AttackTechniqueFactory) → list[Parameter]

Describe factory-owned constructor inputs while leaving execution inputs deferred.

Returns:

get_editable_parameters

get_editable_parameters(factory: AttackTechniqueFactory) → list[Parameter]

Select constructor inputs whose source values have a lossless external representation.

Returns:

get_editable_settings

get_editable_settings(factory: AttackTechniqueFactory) → dict[str, Any]

Project supported factory fields onto registered names without reconstructing source state.

Returns:

get_factories

get_factories() → dict[str, AttackTechniqueFactory]

Return all registered factories as a name→factory dict.

Callers filter the result in-place using factory properties (e.g. factory.uses_adversarial or factory.technique_tags).

Returns:

get_factories_or_raise

get_factories_or_raise() → dict[str, AttackTechniqueFactory]

Return all registered factories, raising if the registry is empty.

Use this from any code path that needs the registry to be populated (scenario technique builders, scenario initialization) so an empty registry surfaces a single, descriptive error instead of silently producing empty technique enums or empty attack lists.

Returns:

Raises:

register_from_factories

register_from_factories(factories: list[AttackTechniqueFactory]) → None

Register a list of factories under their name.

Per-name idempotent: existing entries are not overwritten.

ParameterTypeDescription
factorieslist[AttackTechniqueFactory]Self-describing factories to register. Each factory’s name and technique_tags properties are used directly.

Raises:

register_technique

register_technique(name: str, factory: AttackTechniqueFactory, tags: dict[str, str] | list[str] | None = None) → None

Register an attack technique factory.

ParameterTypeDescription
namestrThe registry name for this technique.
factoryAttackTechniqueFactoryThe factory that produces attack techniques.
tagsdict[str, str] | list[str] | NoneOptional tags for categorisation. Accepts a dict[str, str] or a list[str] (each string becomes a key with value ""). Defaults to None.

validate_scenario_pools

validate_scenario_pools(factories: dict[str, AttackTechniqueFactory]) → None

Build affected selection catalogs against a candidate pool without changing caches or storage.

Scenario builders retain their own filtering and local-factory precedence. Fixed catalogs do not use the revision-aware decorator and are not rebuilt.

Raises:

ConverterMetadata

Bases: RegistryMetadata

Metadata describing a registered Converter class.

Carries the derived parameters build contract (the same list the resolver consumes to build an instance) and, via class_attributes on the base, the converter’s class-level supported input/output types. Presentation facts — the supported types and whether the converter is LLM-based — are projected from those rather than stored, so the entry can never drift from the class or the contract.

Use ConverterRegistry.get_class() to get the actual class or create_instance() to build a configured instance.

ConverterRegistry

Bases: InstanceHoldingRegistry['Converter', ConverterMetadata]

Registry that discovers, builds, and holds Converter instances.

Discovers all concrete Converter subclasses exported from pyrit.converter (keyed by their exact class name, e.g. "Base64Converter") as registered buildable classes. Pre-configured instances registered via initializers or the backend are held under the instances property.

Building a converter resolves its arguments through the shared resolver, so LLM converters can be constructed by passing a converter_target that names a target in the TargetRegistry.

Constructor Parameters:

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

DefaultInstanceRegistry

Bases: Generic[T]

Concrete InstanceRegistry implementation assigned to .instances.

Holds named, pre-configured instances with tags and derived metadata. It owns no singleton lifecycle — the registry that exposes it via .instances owns that.

Type Parameters:

ParameterTypeDescription
TThe type of instances held (must provide get_identifier()).

Constructor Parameters:

ParameterTypeDescription
instance_typetype[T] | Callable[[], type[T]] | NoneOptional expected element type. When set, register raises TypeError for any instance that is not of this type, so a registry scoped to one component kind (e.g. a target registry) cannot silently hold a different kind (e.g. a scorer). May be the class itself or a zero-argument callable returning it; the callable form lets owners defer importing the type so a registry’s lazy discovery is preserved. It is resolved once, on the first register call, and cached. Defaults to None.
reserved_namesset[str] | frozenset[str] | NoneNames that cannot be registered in this container. Defaults to None.
entry_kindstrWhat an entry is, such as "target", for messages. Defaults to "entry".

Methods:

add_tags

add_tags(name: str, tags: dict[str, str] | list[str]) → None

Add tags to an existing entry.

ParameterTypeDescription
namestrThe registry name of the entry to tag.
tagsdict[str, str] | list[str]Tags to add.

Raises:

find_dependents_of_tag

find_dependents_of_tag(tag: str) → list[RegistryEntry[T]]

Find entries whose children depend on entries with the given tag.

Scans each entry’s ComponentIdentifier tree and checks whether any child’s eval_hash matches the eval_hash of an entry that carries tag. Entries that themselves carry tag are excluded.

This enables automatic dependency detection: for example, tagging base refusal scorers with "refusal" lets you discover all wrapper scorers (inverters, composites) that embed a refusal scorer without any explicit depends_on declaration.

ParameterTypeDescription
tagstrThe tag key that identifies the “base” entries.

Returns:

get

get(name: str) → T | None

Get a registered instance by name.

ParameterTypeDescription
namestrThe registry name of the instance.

Returns:

get_all_instances

get_all_instances() → list[RegistryEntry[T]]

Get the entries the caller in scope may see, sorted by name.

Returns:

get_all_instances_of_every_owner

get_all_instances_of_every_owner() → list[RegistryEntry[T]]

Get every entry, including other callers’ private ones, sorted by name.

Only for internal bookkeeping that must see every entry, such as releasing files or checking names for conflicts. Never use it to find a component for a caller.

Returns:

get_by_tag

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

Get entries that carry a given tag, optionally matching a value.

ParameterTypeDescription
tagstrThe tag key to match.
valuestr | NoneIf provided, only entries whose tag value equals this are returned. If None, any entry with the tag key matches. Defaults to None.

Returns:

get_entry

get_entry(name: str) → RegistryEntry[T] | None

Get the full entry (including tags) by name.

Every lookup by name goes through here, and a private entry is returned only to its owner.

ParameterTypeDescription
namestrThe registry name of the entry.

Returns:

get_names

get_names() → list[str]

Get a sorted list of the instance names the caller in scope may see.

Returns:

list_metadata

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

List metadata for the instances the caller in scope can see, optionally filtered.

ParameterTypeDescription
include_filtersdict[str, object] | NoneFilters items must match. Defaults to None.
exclude_filtersdict[str, object] | NoneFilters items must not match. Defaults to None.

Returns:

query_by_tags

query_by_tags(query: TagQuery) → list[RegistryEntry[T]]

Get entries whose tag keys satisfy a composable TagQuery.

Where get_by_tag matches a single key (optionally a value), this evaluates an arbitrary AND / OR / exclude predicate built with TagQuery (e.g. TagQuery.all("core") & TagQuery.any_of("fast", "cheap")). Matching is on the tag keys only; tag values are not considered.

ParameterTypeDescription
queryTagQueryThe predicate to evaluate against each entry’s tag keys.

Returns:

register

register(instance: T, name: str | None = None, tags: dict[str, str] | list[str] | None = None, metadata: dict[str, Any] | None = None, replace: bool = False) → None

Register a pre-configured instance.

An entry registered while the server’s startup scripts run is marked as configuration (see registration_origin).

ParameterTypeDescription
instanceTThe instance to register.
namestr | NoneThe registry name. Defaults to the instance’s identifier unique_name.
tagsdict[str, str] | list[str] | NoneOptional tags for categorization. Defaults to None.
metadatadict[str, Any] | NoneOptional per-entry metadata. Defaults to None.
replaceboolWhether to replace an existing entry with the same name. Defaults to False.

Raises:

unregister

unregister(name: str, expected_entry: RegistryEntry[T] | None = None) → T | None

Remove a registered instance by name.

ParameterTypeDescription
namestrThe registry name of the instance.
expected_entryRegistryEntry[T] | NoneWhen supplied, remove the name only if it still refers to this exact registry entry. Holding the entry, such as one from get_all_instances_of_every_owner, allows removing it whoever owns it. Defaults to None.

Returns:

validate_name_available

validate_name_available(name: str) → None

Validate that a registry name can be used.

Names are global, so a name another caller’s private entry holds is taken too. The error doesn’t say whose entry holds it.

ParameterTypeDescription
namestrThe proposed registry name.

Raises:

InitializerMetadata

Bases: RegistryMetadata

Metadata describing a registered PyRITInitializer class.

Use get_class() to get the actual class.

InitializerRegistry

Bases: ParamBagRegistry['PyRITInitializer', InitializerMetadata]

Registry for discovering and managing available initializers.

Discovers all PyRITInitializer subclasses from the pyrit/setup/initializers directory structure via a filesystem scan (so _discover is overridden rather than supplying _base_type / _discovery_package). Initializers are identified by their suffix-stripped snake_case class name (e.g., "objective_target", "technique"); the directory structure is used for organization but not exposed to users.

Constructor Parameters:

ParameterTypeDescription
discovery_pathPath | NoneThe path to discover initializers from. If None, defaults to pyrit/setup/initializers (discovers all).
lazy_discoveryboolIf True, discovery is deferred until first access. Defaults to False for backwards compatibility.

Examples:

Methods:

configure_custom_scripts_source

configure_custom_scripts_source(source: str | None) → None

Configure the local directory or Azure Blob source for custom initializers.

create_and_configure

create_and_configure(name: str, initializer_params: dict[str, Any] | None = None) → PyRITInitializer

Build and parameterize an initializer in one call.

Parallels ScenarioRegistry.create_and_initialize_async (which takes scenario_params): the registry — not the caller — owns the build → set-params → validate lifecycle. Unlike scenarios, initialize_async is invoked later by the PyRIT init flow, so this stops at configure and returns a configured, not-yet-initialized instance.

ParameterTypeDescription
namestrThe registry name of the initializer (e.g. "objective_target").
initializer_paramsdict[str, Any] | NoneDeclared parameters to set before initialization. Coerced to self.params via set_params_from_args and validated against supported_parameters(). Omitted inputs use declared defaults. Defaults to None.

Returns:

Raises:

create_from_script_paths

create_from_script_paths(script_paths: Sequence[str | Path], strict: bool = False) → list[PyRITInitializer]

Load initializer instances from external Python script files.

The registry owns turning script files into initializers: each .py file is imported and every PyRITInitializer subclass defined in that file (imported ones are ignored) is instantiated. Instances are returned in load order, ready for the caller to validate and initialize; they are not added to the class catalog.

ParameterTypeDescription
script_pathsSequence[str | Path]Python (.py) file paths to load initializers from. Relative paths resolve against the current working directory.
strictboolRaise rather than skip a class whose constructor fails. Defaults to False.

Returns:

Raises:

is_builtin

is_builtin(name: str) → bool

Return True if name was registered during built-in discovery.

list_stored_initializer_sources

list_stored_initializer_sources() → tuple[str, list[tuple[str, str, str]]]

Return the configured source and its stored custom initializer scripts.

register_from_content

register_from_content(name: str, script_content: str) → str

Register an initializer from uploaded Python source code.

Writes script_content to a managed directory, loads it as a module, discovers the first concrete PyRITInitializer subclass, and registers it under name.

ParameterTypeDescription
namestrRegistry name for the new initializer.
script_contentstrPython source code that defines a PyRITInitializer subclass.

Returns:

Raises:

register_stored_initializers

register_stored_initializers(strict: bool = False) → None

Register custom initializers from the configured storage source.

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:

unregister_and_cleanup

unregister_and_cleanup(name: str) → None

Unregister a custom initializer and clean up its script file.

Built-in initializers cannot be removed. For custom initializers added via register_from_content, the saved script file is also deleted.

ParameterTypeDescription
namestrThe registry name to remove.

Raises:

InstanceHoldingRegistry

Bases: Registry[InstanceT, MetadataT]

Registry that builds classes and stores named, configured instances.

Extends the class-catalog and construction behavior of Registry with a typed instances container. This keeps construction on the owning component registry while InstanceRegistry remains responsible only for storing and retrieving already-built objects.

Type Parameters:

ParameterTypeDescription
InstanceTThe identifiable component type that this registry builds and stores.
MetadataTThe metadata dataclass for buildable classes.

Constructor Parameters:

ParameterTypeDescription
lazy_discoveryboolIf True, class discovery is deferred until first access. If False, discovery runs immediately. Defaults to True.
reserved_instance_namesset[str] | frozenset[str] | NoneNames that cannot be used for stored instances. Defaults to None.

Methods:

create_named_instance

create_named_instance(name: str, type_name: str, params: Mapping[str, object] | None = None, registry_metadata: dict[str, Any] | None = None, external_input: bool = False, allowed_path_params: frozenset[str] = frozenset(), private: bool | None = None) → InstanceT

Build and store a configured instance under an explicit name, recording the caller in scope as its creator.

An instance built from the caller’s private entries is private too, so a shared component never uses a private one.

ParameterTypeDescription
namestrThe unique instance name.
type_namestrThe registered class name to build.
paramsMapping[str, object] | NoneConstructor arguments. Defaults to None.
registry_metadatadict[str, Any] | NonePer-entry metadata to store with the instance. Defaults to None.
external_inputboolWhether params come from an external caller, in which case the instance is built with create_instance_from_external_input. Defaults to False.
allowed_path_paramsfrozenset[str]External parameters that can name a server file or folder but that the caller has made safe. Defaults to none.
privatebool | NoneWhether only the caller can see and use the instance, or None to make it private only when it is built on the caller’s private entries. Defaults to None.

Returns:

Raises:

get_reconstruction_parameters

get_reconstruction_parameters(source: InstanceT) → dict[str, object]

Select declared constructor inputs from an opt-in source.

Returns:

Raises:

recreate_instance

recreate_instance(source: InstanceT, params: Mapping[str, object], external_input: bool = False, allowed_path_params: frozenset[str] = frozenset()) → InstanceT

Build an independent component; never change or register the source.

ParameterTypeDescription
sourceInstanceTThe registered component to copy.
paramsMapping[str, object]Constructor overrides.
external_inputboolWhether params come from an external caller. Defaults to False.
allowed_path_paramsfrozenset[str]External overrides that can name a server file or folder but that the caller has made safe. Defaults to none.

Returns:

Raises:

resolve_source

resolve_source(name: str, identifier_hash: str) → InstanceT

Resolve an unchanged source, allowing only an unambiguous rename.

Only sources the caller in scope may see are found, and each is looked up by name, so a build that uses a private source records it.

Returns:

Raises:

InstanceRegistry

Bases: Protocol[T]

Typed instance-container capability a registry exposes as .instances.

Holds named, pre-configured instances that callers register and retrieve by name, list, tag, and filter. Stored items must provide get_identifier(). DefaultInstanceRegistry is the concrete default implementation; expressing the surface as a protocol lets callers depend on the capability rather than a concrete class.

Type Parameters:

ParameterTypeDescription
TThe type of instances held (must provide get_identifier()).

Methods:

add_tags

add_tags(name: str, tags: dict[str, str] | list[str]) → None

Add tags to an existing entry.

find_dependents_of_tag

find_dependents_of_tag(tag: str) → list[RegistryEntry[T]]

Return entries whose identifier tree references a tagged entry’s eval_hash.

get

get(name: str) → T | None

Return the instance registered under name, or None.

get_all_instances

get_all_instances() → list[RegistryEntry[T]]

Return all entries the caller in scope may see, sorted by name.

get_all_instances_of_every_owner

get_all_instances_of_every_owner() → list[RegistryEntry[T]]

Return every entry, including other callers’ private ones, for internal bookkeeping only.

get_by_tag

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

Return entries carrying tag (optionally matching value), sorted by name.

get_entry

get_entry(name: str) → RegistryEntry[T] | None

Return the full entry (including tags) for name, or None.

get_names

get_names() → list[str]

Return the sorted names of registered instances.

list_metadata

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

List per-instance identifier metadata, optionally filtered.

query_by_tags

query_by_tags(query: TagQuery) → list[RegistryEntry[T]]

Return entries whose tag keys satisfy the composable TagQuery, sorted by name.

register

register(instance: T, name: str | None = None, tags: dict[str, str] | list[str] | None = None, metadata: dict[str, Any] | None = None, replace: bool = False) → None

Register a pre-configured instance, defaulting its name to the identifier’s unique_name.

unregister

unregister(name: str, expected_entry: RegistryEntry[T] | None = None) → T | None

Remove and return name when it still refers to expected_entry, if supplied.

validate_name_available

validate_name_available(name: str) → None

Raise if name is reserved or already registered.

NotSaveableError

Bases: ValueError

An entry can’t be saved as asked, though it can still be created without saving it.

Constructor Parameters:

ParameterTypeDescription
causestrWhy the entry can’t be saved, in words safe to show users. The error’s message adds that the entry can still be created without saving it.

ParamBagRegistry

Bases: Registry[ConfigurableT, MetadataT]

Registry whose components carry a parameter bag populated post-construction.

Extends the base Registry (catalog + create_instance from a flat arg dict) with the shared create → set-parameters lifecycle prefix used by the registries whose component type supports set_params_from_args (Scenario, PyRITInitializer). The component type parameter is bound to SupportsParamBag, so _create_and_configure is type-safe without a cast.

Subclasses layer the diverging post-configure step on top: ScenarioRegistry initializes, InitializerRegistry validates.

Registry

Bases: ABC, Generic[T, MetadataT]

Standalone base for PyRIT registries: a validated class catalog that builds instances.

Provides the common infrastructure every registry needs:

Subclasses provide the domain specifics:

The default _discover() scans _discovery_package().__all__ for concrete _base_type() subclasses and registers each by class name. A registry whose discovery is genuinely different (e.g. a directory or filesystem scan) overrides _discover() instead of supplying the two hooks.

Type Parameters:

ParameterTypeDescription
TThe type of classes being registered (e.g. Converter).
MetadataTThe metadata dataclass type (e.g. ConverterMetadata).

Constructor Parameters:

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

Methods:

create_instance

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

Build a configured instance by class name.

Looks up the catalogued class, resolves the given arguments via resolve_constructor_args (coerce simple strings, resolve registry references by name, raise on unknown params), and constructs the object.

ParameterTypeDescription
namestrThe catalog name to build.
**kwargsobjectConstructor arguments (simple values or registry names for reference parameters). Defaults to {}.

Returns:

Raises:

create_instance_from_external_input

create_instance_from_external_input(name: str, params: Mapping[str, object], allowed_path_params: frozenset[str] = frozenset()) → T

Build a configured instance from external input such as a REST or CLI request.

Unlike create_instance, which serves in-process callers that may pass any Python object, this accepts only parameters with Parameter.is_external_input and registry references given by name. A parameter that can name a server file or folder is accepted only when the caller lists it in allowed_path_params after making it safe. Anything else is rejected before construction; the constructor still validates the values it receives.

ParameterTypeDescription
namestrThe catalog name to build.
paramsMapping[str, object]Constructor arguments from the external caller.
allowed_path_paramsfrozenset[str]Parameters that can name a server file or folder but that the caller has made safe. Defaults to none.

Returns:

Raises:

get_all_registered_class_metadata

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

List metadata for all registered classes, optionally filtered.

Supports filtering on any metadata property:

ParameterTypeDescription
include_filtersdict[str, object] | NoneFilters that items must match (AND logic). Keys are metadata property names. Defaults to None.
exclude_filtersdict[str, object] | NoneFilters that exclude an item when matched. Keys are metadata property names. Defaults to None.

Returns:

get_class

get_class(name: str) → type[T]

Get a registered class by name.

ParameterTypeDescription
namestrThe catalog name.

Returns:

Raises:

get_class_metadata

get_class_metadata() → MetadataT

Build metadata for any class (registered or not).

Derives the catalog name via _get_registry_name and builds a fresh descriptor. Useful for describing a class without registering it.

ParameterTypeDescription
clstype[T]The class to describe.

Returns:

get_class_names

get_class_names() → list[str]

Get a sorted list of all registered catalog names.

Returns:

get_registered_class_metadata

get_registered_class_metadata(name: str) → MetadataT | None

Get the metadata for a single registered class by name.

ParameterTypeDescription
namestrThe catalog name.

Returns:

get_registry_singleton

get_registry_singleton() → Self

Get the singleton instance of this registry.

Creates the instance on first call with default parameters. Construction happens under a per-class lock rather than the shared map lock, so a slow eager constructor (e.g. one that runs discovery synchronously) blocks only other callers of the same registry class; unrelated registry classes construct independently.

Returns:

is_temporary_class

is_temporary_class(name: str) → bool

Return whether a scan’s launch scripts added the class under this name, so it’s gone after a restart.

ParameterTypeDescription
namestrThe catalog name.

Returns:

register_class

register_class(name: str | None = None) → None

Add a class to the catalog after validating it.

Registers a class type (not an instance) so the registry knows it exists and can later build instances of it via create_instance. The class is validated by _validate_class before being stored, so the catalog never holds a class whose build contract cannot be resolved.

ParameterTypeDescription
clstype[T]The class to register.
namestr | NoneOptional custom catalog name. If not provided, it is derived via _get_registry_name. Defaults to None.

Raises:

reset_registry_singleton

reset_registry_singleton() → None

Reset the singleton instance.

Useful for testing or when re-discovery is needed.

set_registry_singleton

set_registry_singleton(instance: Self) → None

Replace this registry’s singleton with an already constructed instance.

Raises:

RegistryEntry

Bases: Generic[T]

A wrapper around a registered item, holding its name, tags, and the item 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.

Attributes:

ParameterTypeDescription
namestrThe registry name for this entry.
instanceTThe registered object.
tagsdict[str, str]Key-value tags for categorization and filtering.
metadatadict[str, Any]Arbitrary key-value metadata for capability flags and other per-entry data that should not pollute the tag namespace.

RegistryMetadata

Minimal base for class-level registry metadata.

Provides the common fields every registry metadata type needs for display, lookup, and filtering in class registries.

Attributes:

ParameterTypeDescription
class_namestrPython class name (e.g., “ContentHarmsScenario”).
class_modulestrFull module path (e.g., “pyrit.scenario.scenarios.content_harms”).
class_descriptionstrHuman-readable description, typically from the class docstring.
registry_namestrThe suffix-stripped snake_case key used in the registry (e.g., “content_harms” for ContentHarmsScenario).
parameterstuple[Parameter, ...]The derived build contract for the class. Buildable registries (e.g. converters) populate this from the constructor signature; scenarios/initializers use their own supported_parameters today and will migrate to this unified shape.
class_attributesMapping[str, Any]Values sourced from class attributes (declared on the identifier via Param.ClassAttr), letting the entry describe class-level facts — e.g. a converter’s supported input/output types — without constructing an instance. Empty for entries with none.

Methods:

description_from_docstring

description_from_docstring(fallback: str = '') → str

Extract a normalized description from a class docstring.

Collapses all whitespace into single spaces. Returns fallback if no docstring is present or the docstring is empty after cleaning.

Returns:

markdown_from_docstring

markdown_from_docstring(fallback: str = '') → str

Extract a dedented description while preserving Markdown structure.

Returns:

summary_from_docstring

summary_from_docstring() → str

Extract a short summary from the first paragraph of a class docstring.

Uses the class’s own docstring only (never an inherited one), normalizes indentation, and collapses the first paragraph’s whitespace onto one line. Empty when the class has no docstring. This is the catalog-display counterpart to description_from_docstring (which collapses the whole docstring); buildable registries populate class_description from this first-paragraph form.

Returns:

ResolvedScenarioSuiteEntry

One preflighted suite entry ready for ordinary scenario submission.

Methods:

metadata

metadata(suite_execution_id: UUID, suite: ScenarioSuiteRegistryEntry) → dict[str, Any]

Build the child attribution metadata for this resolved entry.

Returns:

ResolvedScenarioSuiteLaunch

A version-checked suite and its ordered ordinary scenario run requests.

SavedEntryConflictError

Bases: ValueError

An entry can’t be saved under a name that a registered or saved entry of its kind already has.

SavedEntryStorageError

Bases: RuntimeError

Saved entries can’t be written right now.

ScenarioMetadata

Bases: RegistryMetadata

Metadata describing a registered Scenario class.

Use get_class() to get the actual class.

ScenarioPresetConflictError

Bases: DocumentConflictError

A stored preset changed after the caller read it.

ScenarioPresetMetadata

Bases: RegistryMetadata

Metadata describing a buildable preset class.

Placeholder for a catalog that is intentionally empty: a preset is a document, not a class this registry constructs. It carries only the common RegistryMetadata fields.

ScenarioPresetNameRegisteredError

Bases: ValueError

A preset name is owned by code in this deployment and cannot be stored.

Constructor Parameters:

ParameterTypeDescription
namestrThe preset name a document tried to claim.

ScenarioPresetRegistry

Bases: Registry['ScenarioPreset', ScenarioPresetMetadata]

The single owner of scenario preset storage, validation, and resolution.

A preset reaches the registry one of two ways. A stored preset is a JSON document an operator can edit, move between deployments, and delete. A registered preset is contributed in-process by code, lives only as long as the process, and can be neither edited nor deleted — which is the point when a configuration is meant to stay fixed. PresetEntry.origin tells a caller which it holds, since only one supports a write. A stored document wins a name collision: the operator’s data outranks a code default.

A preset is a document rather than a component class, so the buildable class catalog inherited from Registry stays empty and _discover registers nothing. What the base contributes is the shared singleton machinery every registry is reached through, alongside the instances container holding the registered half.

Stored presets are read through on every call; nothing caches them. The version guarding every write is sha256 of the stored bytes, so a cached copy could only describe what this process last read or wrote.

Constructor Parameters:

ParameterTypeDescription
storageScenarioPresetStorage | NoneStorage to read and write presets through. Defaults to the standard directory, constructed on first use so that merely importing the registry never creates a directory.

Examples:

Methods:

check_preset

check_preset(preset: ScenarioPreset) → list[PresetIssue]

Check one preset against this deployment’s registered scenarios and converters.

This is the only validation path: a preset is resolved by the same code the launch path resolves it with, so the two answers cannot drift apart.

Results are advisory. Nothing here rejects a preset.

ParameterTypeDescription
presetScenarioPresetThe preset to check.

Returns:

configure_source

configure_source(source: str | None) → None

Point the registry at a local directory or Azure Blob source.

ParameterTypeDescription
sourcestr | NoneThe configured source, or None to use the default directory under the PyRIT configuration path.

delete_preset

delete_preset(name: str, expected_version: str | None = None) → bool

Delete one stored preset, reporting whether it was there to delete.

Without expected_version the delete is unconditional. With it, the delete is refused if the preset changed after the caller read it, so confirming a delete cannot discard an edit the caller never saw. The answer comes from the delete itself rather than a preceding existence check, so when two callers race to remove the same preset exactly one is told it did.

ParameterTypeDescription
namestrThe preset name.
expected_versionstr | NoneThe version the caller read, or None to delete whatever is stored. Defaults to None.

Returns:

Raises:

ensure_preset

ensure_preset(preset: ScenarioPreset) → bool

Persist one preset only if nothing is stored under its name.

This is how code seeds a library the operator then owns: create-if-absent rather than a write, so a preset they have since edited or replaced is left alone. The create and the existence test are the same conditional write, so two workers starting together cannot both decide the name is free.

ParameterTypeDescription
presetScenarioPresetThe preset to persist if its name is free.

Returns:

Raises:

get_preset

get_preset(name: str) → PresetEntry | None

Read one preset together with the version needed to save an edit to it.

ParameterTypeDescription
namestrThe preset name.

Returns:

Raises:

get_preset_version

get_preset_version(name: str) → str | None

Read the version of one stored document without parsing it.

This is the recovery path: a document that cannot be parsed is unreachable through get_preset, so exposing its version lets a caller overwrite the broken file instead of leaving the name permanently unusable.

ParameterTypeDescription
namestrThe preset name.

Returns:

Raises:

list_presets

list_presets() → list[PresetEntry]

Read every preset this deployment offers, skipping documents that cannot be parsed.

Returns:

register_preset

register_preset(preset: ScenarioPreset, tags: dict[str, str] | list[str] | None = None) → None

Contribute one preset from code, for the lifetime of this process.

Nothing is written, so the preset cannot be edited or deleted through the registry. Use ensure_preset instead to seed a library the operator then owns.

A document already stored under this name shadows the registration and is warned about here rather than on every read; one appearing afterwards cannot be caught.

ParameterTypeDescription
presetScenarioPresetThe preset, registered under its own name.
tagsdict[str, str] | list[str] | NoneTags for discovery through instances. Defaults to None.

Raises:

resolve_preset

resolve_preset(name: str, expected_version: str | None) → PresetEntry | None

Read one preset for launch, confirming it is the version the caller reviewed.

The comparison is against a fresh read, because an edit landing between the preview and the launch is the case the check exists to catch. A registered preset has no version, so a caller supplying one read a document that has since been deleted, and the mismatch is reported rather than ignored.

ParameterTypeDescription
namestrThe preset name.
expected_versionstr | NoneThe version the caller read, or None to accept whatever is available now.

Returns:

Raises:

save_preset

save_preset(preset: ScenarioPreset, expected_version: str | None) → StoredPreset

Persist one preset, refusing a write that would discard a concurrent edit.

Unresolvable references are reported by check_preset rather than rejected here, so a preset authored against one deployment stays savable on another. A name already registered by code is refused: one name has one owner, which keeps the stored-shadows-registered rule a recovery path rather than a workflow.

ParameterTypeDescription
presetScenarioPresetThe preset to persist.
expected_versionstr | NoneNone to create a preset that must not already exist, or the version returned when the edited preset was read.

Returns:

Raises:

scan_stored_presets

scan_stored_presets() → int

Read every stored preset once so unusable documents are reported at startup.

list_presets skips a document it cannot parse, so without this a broken preset stays invisible until someone wonders where it went.

The pass checks the schema only: resolving a preset needs scenario metadata, and building that instantiates every registered scenario class, which this early in boot has neither its environment nor its memory nor its techniques. Failures are logged rather than raised so unusable operator data cannot stop boot.

Returns:

ScenarioPresetStorage

Bases: FileDocumentStorage

Read and write scenario presets as JSON documents.

Storage is read through on every call rather than cached: the same directory or blob container is routinely shared between a notebook, the API, and a second process, and a cache would serve edits those callers can no longer see.

Writes are guarded by an optimistic-concurrency check. Enforcing that check without a window for a second writer to slip through is the shared storage layer’s job, so this class only serializes, validates, and names documents.

Constructor Parameters:

ParameterTypeDescription
sourcestr | NoneLocal directory or Azure Blob source URI. Defaults to scenario_presets under the PyRIT configuration directory.

Methods:

delete_preset

delete_preset(name: str, expected_version: str | None = None) → bool

Delete one stored preset, reporting whether it was there to delete.

ParameterTypeDescription
namestrThe preset name.
expected_versionstr | NoneThe version the caller read, or None to delete whatever is stored. Defaults to None.

Returns:

Raises:

get_preset_source

get_preset_source(name: str) → str

Get the credential-free location of one stored preset.

Returns:

Raises:

get_preset_version

get_preset_version(name: str) → str | None

Read the version of one stored document without parsing it.

Returns:

Raises:

list_presets

list_presets() → dict[str, StoredPreset]

Read every stored preset, skipping any that cannot be parsed.

A malformed, unreadable, or hand-edited file must not prevent the rest of the library from loading, so failures are logged and that preset is omitted.

Returns:

load_preset

load_preset(name: str) → StoredPreset | None

Read one stored preset.

Returns:

Raises:

save_preset

save_preset(preset: ScenarioPreset, expected_version: str | None) → StoredPreset

Persist one preset.

A document that exists but cannot be parsed still has a version, so creating over a malformed file conflicts rather than silently discarding it.

ParameterTypeDescription
presetScenarioPresetThe preset to persist.
expected_versionstr | NoneNone to create a preset that must not already exist, or the version returned when the edited preset was read.

Returns:

Raises:

ScenarioRegistry

Bases: ParamBagRegistry['Scenario', ScenarioMetadata]

Registry for discovering and managing available scenario classes.

Discovers every concrete Scenario subclass under pyrit.scenario.scenarios via the unified Registry base (recursive subclass enumeration). Unlike the component registries, scenarios are keyed by their dotted module path (e.g. "garak.encoding", "foundry.red_team_agent") rather than class name, so only _get_registry_name and _build_metadata are customized.

Examples:

Methods:

create_and_estimate_async

create_and_estimate_async(name: str, scenario_params: dict[str, Any] | None = None, target_is_configured: bool = False, constructor_kwargs: dict[str, Any] | None = None, estimate_kwargs: Any = {}) → ScenarioRunSizeEstimate

Build, parameterize, and estimate a scenario without initializing a run.

ParameterTypeDescription
namestrRegistered scenario name.
scenario_paramsdict[str, Any] | NoneScenario-declared parameter values. Defaults to None.
target_is_configuredboolWhether the estimate has a concrete objective target. Defaults to False.
constructor_kwargsdict[str, Any] | NoneExplicit constructor inputs, such as a custom objective scorer. Defaults to None.
**estimate_kwargsAnyCommon resolved values such as techniques, dataset configuration, baseline choice, and an optional objective target. Defaults to {}.

Returns:

create_and_initialize_async

create_and_initialize_async(name: str, scenario_params: dict[str, Any] | None = None, scenario_result_id: str | None = None, initial_metadata: Mapping[str, Any] | None = None, constructor_kwargs: dict[str, Any] | None = None, configuration_metadata: Callable[[Scenario], Mapping[str, Any]] | None = None, initialize_kwargs: Any = {}) → Scenario

Build, parameterize, and initialize a scenario in one call.

This is the canonical entry point for producing a run-ready Scenario: the registry — not the caller — owns the full lifecycle.

  1. create the scenario via create_instance (seeding scenario_result_id when resuming an existing run),

  2. set parameters — the scenario-specific declared parameters (scenario_params) and the common run-resolved parameters (initialize_kwargs — objective_target, scenario_techniques, dataset_config, max_concurrency, max_retries, memory_labels, include_baseline) are merged into a single Scenario.set_params_from_args call, so every value flows through the one coerce/validate/inject-defaults path,

  3. initialize — Scenario.initialize_async() is called with no arguments; it reads every input from the now-populated bag.

Prefer this over manually chaining create_instance + set_params_from_args + initialize_async. Synchronous construction and configuration run off-loop; async initialization runs on the caller’s event loop.

ParameterTypeDescription
namestrThe registry name of the scenario (e.g. "foundry.red_team_agent").
scenario_paramsdict[str, Any] | NoneScenario-specific declared parameters to set before initialization. Defaults to an empty mapping.
scenario_result_idstr | NoneExisting scenario-result id to resume, or None to start a fresh run. Defaults to None.
initial_metadataMapping[str, Any] | NoneCaller-owned metadata to persist atomically when a fresh scenario result is created. Defaults to None.
constructor_kwargsdict[str, Any] | NoneExplicit constructor inputs for this run. Defaults to None.
configuration_metadataCallable[[Scenario], Mapping[str, Any]] | NoneValidate resolved configuration and capture identities before initialization. Defaults to None.
**initialize_kwargsAnyCommon run-resolved parameters merged into the param bag (notably objective_target). Defaults to {}.

Returns:

supports_objective_scorer

supports_objective_scorer(scenario_class: type[Scenario]) → bool

Check whether the constructor explicitly accepts an objective scorer.

Returns:

ScenarioSuiteConflictError

Bases: DocumentConflictError

A stored scenario suite changed after the caller read it.

ScenarioSuiteExecutionNotFoundError

Bases: LookupError

A requested suite definition does not exist.

ScenarioSuiteLaunchConflictError

Bases: ValueError

A suite or referenced preset changed after the operator reviewed it.

ScenarioSuiteLaunchResolver

Resolve suites and presets without owning backend task lifecycle.

Constructor Parameters:

ParameterTypeDescription
suite_registryScenarioSuiteRegistry | NoneSuite definitions to resolve. Defaults to None.
preset_registryScenarioPresetRegistry | NonePreset definitions to resolve. Defaults to None.

Methods:

resolve

resolve(name: str, request: LaunchScenarioSuiteRequest | ScenarioSuiteReadinessRequest) → ResolvedScenarioSuiteLaunch

Resolve and validate the complete suite before any child is submitted.

Returns:

Raises:

ScenarioSuiteMetadata

Bases: RegistryMetadata

Metadata for the intentionally empty buildable suite class catalog.

ScenarioSuiteNameRegisteredError

Bases: ValueError

A suite name is owned by code in this deployment and cannot be stored.

Constructor Parameters:

ParameterTypeDescription
namestrThe suite name a document tried to claim.

ScenarioSuiteNotRunnableError

Bases: ValueError

A suite cannot launch because one or more entries are unresolved.

ScenarioSuiteRegistry

Bases: Registry['ScenarioSuite', ScenarioSuiteMetadata]

Own registered and stored scenario suite resolution.

Stored suites are operator-owned JSON documents that can be edited and deleted. Registered suites are contributed in process by code and are read-only. A stored document shadows a registered suite with the same name so operator data takes precedence, while new writes to a code-owned name are refused.

Stored suites are read through on every call. Their versions describe the current document bytes, so caching them would weaken optimistic concurrency.

Constructor Parameters:

ParameterTypeDescription
storageScenarioSuiteStorage | NoneStorage to read and write suites through. Defaults to the standard directory, constructed on first use.

Examples:

Methods:

configure_source

configure_source(source: str | None) → None

Point the registry at a local directory or Azure Blob source.

ParameterTypeDescription
sourcestr | NoneConfigured source, or None for the default directory.

delete_suite

delete_suite(name: str, expected_version: str | None = None) → bool

Delete one stored suite without affecting a registered suite.

ParameterTypeDescription
namestrThe suite name.
expected_versionstr | NoneThe version the caller read, or None to delete whatever is stored. Defaults to None.

Returns:

Raises:

get_suite

get_suite(name: str) → ScenarioSuiteRegistryEntry | None

Read one suite together with its origin and optional document version.

ParameterTypeDescription
namestrThe suite name.

Returns:

get_suite_version

get_suite_version(name: str) → str | None

Read the version of one stored document without parsing it.

ParameterTypeDescription
namestrThe suite name.

Returns:

list_suites

list_suites() → list[ScenarioSuiteRegistryEntry]

Read every suite this deployment offers.

Returns:

register_suite

register_suite(suite: ScenarioSuite, tags: dict[str, str] | list[str] | None = None) → None

Contribute one read-only suite from code for the lifetime of this process.

ParameterTypeDescription
suiteScenarioSuiteThe suite, registered under its own name.
tagsdict[str, str] | list[str] | NoneTags for discovery through instances. Defaults to None.

Raises:

resolve_suite

resolve_suite(name: str, expected_version: str | None) → ScenarioSuiteRegistryEntry | None

Read one suite for execution, confirming the version the caller reviewed.

ParameterTypeDescription
namestrThe suite name.
expected_versionstr | NoneReviewed stored version, or None to accept whichever suite is currently available.

Returns:

Raises:

save_suite

save_suite(suite: ScenarioSuite, expected_version: str | None) → StoredScenarioSuite

Persist one suite behind an optimistic-concurrency check.

ParameterTypeDescription
suiteScenarioSuiteThe suite to persist.
expected_versionstr | NoneNone for create, or the version being replaced.

Returns:

Raises:

scan_stored_suites

scan_stored_suites() → int

Read every stored suite once so unusable documents are reported at startup.

Returns:

ScenarioSuiteStorage

Bases: FileDocumentStorage

Read and write scenario suites as versioned JSON documents.

Constructor Parameters:

ParameterTypeDescription
sourcestr | NoneLocal directory or Azure Blob source URI. Defaults to scenario_suites under the PyRIT configuration directory.

Methods:

delete_suite

delete_suite(name: str, expected_version: str | None = None) → bool

Delete one stored scenario suite.

ParameterTypeDescription
namestrThe suite name.
expected_versionstr | NoneThe version the caller read, or None to delete whatever is stored. Defaults to None.

Returns:

Raises:

get_suite_source

get_suite_source(name: str) → str

Get the credential-free location of one stored suite.

Returns:

get_suite_version

get_suite_version(name: str) → str | None

Read the version of one stored suite document without parsing it.

Returns:

list_suites

list_suites() → dict[str, StoredScenarioSuite]

Read every stored suite, skipping any that cannot be parsed.

Returns:

load_suite

load_suite(name: str) → StoredScenarioSuite | None

Read one stored suite.

Returns:

save_suite

save_suite(suite: ScenarioSuite, expected_version: str | None) → StoredScenarioSuite

Persist one scenario suite behind an optimistic-concurrency check.

Returns:

Raises:

ScorerMetadata

Bases: RegistryMetadata

Metadata describing a registered Scorer class.

Carries the derived parameters build contract (the same list the resolver consumes to build an instance). Whether the scorer is LLM-based is projected from that contract rather than stored, so the entry can never drift from the class.

Use ScorerRegistry.get_class() to get the actual class or create_instance() to build a configured instance.

ScorerRegistry

Bases: InstanceHoldingRegistry['Scorer', ScorerMetadata]

Registry that discovers, builds, and holds Scorer instances.

Discovers all concrete Scorer subclasses exported from pyrit.score (keyed by their exact class name, e.g. "SelfAskRefusalScorer") for the buildable catalog. Pre-configured instances registered via initializers or the backend are held under the instances property.

Building a scorer resolves its arguments through the shared resolver, so LLM scorers can be constructed by passing a chat_target that names a target in the TargetRegistry, and composite scorers by passing a list of scorers that name scorers already held under instances.

Constructor Parameters:

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

Examples:

SourceMetadata

Bases: RegistryMetadata

Metadata describing a registered ObservationSource class.

Carries the derived parameters build contract (the same list the resolver consumes to build an instance). Use SourceRegistry.get_class() to get the actual class or create_instance() to build a configured instance.

SourceRegistry

Bases: InstanceHoldingRegistry['ObservationSource[Any]', SourceMetadata]

Registry that discovers, builds, and holds ObservationSource instances.

ObservationSource is a protocol, so sources share no base class to enumerate. Discovery therefore reads the names pyrit.score.observation exports and keeps the concrete classes that satisfy the protocol (keyed by their exact class name, e.g. "OtelTraceSource"). Pre-configured instances registered via initializers or the backend are held under the instances property, and scorers resolve a source given by name from there.

Constructor Parameters:

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

Examples:

SupportsInstances

Bases: Protocol[T]

Structural marker for a registry that holds instances.

Lets callers and type-checkers express “a registry that holds instances” without naming a concrete class, so a registry’s capabilities are legible from its type.

.. note:: Introduced with the Phase 1 foundation but not yet consumed in the codebase. Its first real callers arrive when the target and scorer registries migrate onto .instances (Phase 4) and functions begin accepting “any registry that holds instances” structurally. It ships now so the typed capability is part of the foundation rather than a later additive change.

Type Parameters:

ParameterTypeDescription
TThe type of instances held (must provide get_identifier()).

TagQuery

Boolean predicate over string tag sets.

Leaf fields (include_all, include_any, exclude) are evaluated against a tag set directly. Composite queries are produced by the & and | operators and stored in _op / _children.

Prefer the classmethod shortcuts all, any_of, and exclude for single-field leaves.

Methods:

all

all(tags: str = ()) → Self

Leaf query: every tag must be present.

Returns:

any_of

any_of(tags: str = ()) → Self

Leaf query: at least one tag must be present.

Returns:

filter

filter(items: list[_T]) → list[_T]

Return items whose tags satisfy this query.

ParameterTypeDescription
itemslist[_T]Objects with a tags attribute.

Returns:

matches

matches(tags: set[str] | frozenset[str]) → bool

Return True if tags satisfies this query.

ParameterTypeDescription
tagsset[str] | frozenset[str]The tag set to test.

Returns:

none_of

none_of(tags: str = ()) → Self

Leaf query: none of the given tags may be present.

Returns:

TargetMetadata

Bases: RegistryMetadata

Metadata describing a registered PromptTarget class.

Carries the derived parameters build contract (the same list the resolver consumes to build an instance) and, via class_attributes on the base, the target’s declarative auth facts. supported_auth_modes is projected from those rather than stored, so the entry can never drift from the class. Use TargetRegistry.get_class() to get the actual class or create_instance() to build a configured instance.

TargetRegistry

Bases: InstanceHoldingRegistry['PromptTarget', TargetMetadata]

Registry that discovers, builds, and holds PromptTarget instances.

Discovers all concrete PromptTarget subclasses exported from pyrit.prompt_target (keyed by their exact class name, e.g. "OpenAIChatTarget") for the buildable catalog. Pre-configured instances registered via initializers or the backend are held under the instances property.

Building a multi-target resolves its arguments through the shared resolver, so a RoundRobinTarget can be constructed by passing a list of targets that name targets already held under instances.

Constructor Parameters:

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

Examples:

Methods:

create_instance_async

create_instance_async(name: str, params: Mapping[str, object], external_input: bool = False, allowed_path_params: frozenset[str] = frozenset()) → PromptTarget

Build a target through its create_async, so slow setup it needs runs off the calling event loop.

The arguments are resolved as create_instance resolves them or, with external_input, as create_instance_from_external_input does, so the target gets the values its constructor will.

ParameterTypeDescription
namestrThe catalog name to build.
paramsMapping[str, object]The constructor arguments.
external_inputboolWhether params come from an external caller such as a REST request. Defaults to False.
allowed_path_paramsfrozenset[str]External parameters that can name a server file or folder but that the caller has made safe. Defaults to none.

Returns:

Raises:

get_credential_parameter_names

get_credential_parameter_names(name: str) → frozenset[str]

Return the names of a target class’s credential parameters.

A target’s credentials are the parameters its class marks sensitive, such as api_key, sas_token, or github_token.

ParameterTypeDescription
namestrThe catalog name of the target class.

Returns: