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.models

Public model exports for PyRIT core data structures and helpers.

pyrit.models is the canonical data layer. Files in this package must import only from the standard library, pydantic, pyrit.common.deprecation, and other pyrit.models.* submodules. The CI test tests/unit/models/test_import_boundary.py enforces this. See .github/instructions/models.instructions.md for the rule.

Identifier types and helpers live in the pyrit.models.identifiers sub-package but are re-exported here, so callers should import them directly from pyrit.models (e.g. from pyrit.models import ComponentIdentifier).

Functions

build_objective_decomposition_tree

build_objective_decomposition_tree(objectives: Iterable[SeedObjective], root_id: uuid.UUID | None = None) → DecompositionTree

Build the decomposition trees of objectives that have a parent, paths, or children.

ParameterTypeDescription
objectivesIterable[SeedObjective]Objectives that include every member of each tree.
root_iduuid.UUID | NoneAn objective to treat as a tree root even though its own parent is not supplied, such as the starting objective of a stored subtree. Its parent link is not changed. Defaults to None, which requires every parent to be supplied.

Returns:

Raises:

class_name_to_snake_case

class_name_to_snake_case(class_name: str, suffix: str = '') → str

Convert a PascalCase class name to snake_case, optionally stripping a suffix.

ParameterTypeDescription
class_namestrThe class name to convert (e.g., “SelfAskRefusalScorer”).
suffixstrOptional explicit suffix to strip before conversion (e.g., “Scorer”). Defaults to ''.

Returns:

compute_eval_hash

compute_eval_hash(identifier: ComponentIdentifier, child_eval_rules: dict[str, ChildEvalRule], own_rule: ChildEvalRule | None = None, root_unwrap_child: str | None = None) → str

Compute a behavioral equivalence hash for evaluation grouping.

Unlike ComponentIdentifier.hash (which includes all params of self and children), the eval hash applies per-child rules to strip operational params (like endpoint, max_requests_per_minute), exclude children entirely, or filter list items. own_rule extends this to the root entity itself, which is required for leaf components (e.g., a target) whose own params need filtering and which have no relevant children to delegate to. This ensures the same logical configuration on different deployments produces the same eval hash.

Children not listed in child_eval_rules receive full recursive treatment.

When both child_eval_rules is empty and own_rule is None (and no root unwrap applies), no filtering occurs and the result equals identifier.hash.

ParameterTypeDescription
identifierComponentIdentifierThe component identity to compute the hash for.
child_eval_rulesdict[str, ChildEvalRule]Per-child eval rules.
own_ruleChildEvalRule | NoneRule applied to the root entity’s own params and fallbacks. Only included_params and param_fallbacks are honored; exclude, included_item_values, inner_child_name, and unordered_when are not meaningful at the root and will raise ValueError if set. Defaults to None.
root_unwrap_childstr | NoneIf set, names the wrapper passthrough slot on the root identifier (e.g. "targets"). When the root is a wrapper carrying that slot, the first element is substituted before filtering, so the eval hash matches the unwrapped inner component. Defaults to None.

Returns:

Raises:

compute_seed_group_hash

compute_seed_group_hash(seed_identifiers: Sequence[SeedIdentifier]) → str

Return the deterministic hash of ordered seed content hashes.

Content hashes exclude storage metadata (including PyRIT versions and eval hashes), also for child identifiers. Do not hash the flat storage serialization: its custom serializer does not honor model_dump(exclude=...).

ParameterTypeDescription
seed_identifiersSequence[SeedIdentifier]The ordered seed identifiers.

Returns:

config_hash

config_hash(config_dict: dict[str, Any]) → str

Compute a deterministic SHA256 hash from a config dictionary.

This is the single source of truth for identity hashing across the entire system. The dict is serialized with sorted keys and compact separators to ensure determinism.

ParameterTypeDescription
config_dictdict[str, Any]A JSON-serializable dictionary.

Returns:

Raises:

construct_response_from_request

construct_response_from_request(request: MessagePiece, response_text_pieces: list[str], response_type: PromptDataType = 'text', prompt_metadata: dict[str, str | int] | None = None, error: PromptResponseError = 'none') → Message

Construct a response message from a request message piece.

ParameterTypeDescription
requestMessagePieceSource request message piece.
response_text_pieceslist[str]Response values to include.
response_typePromptDataTypeData type for original and converted response values. Defaults to 'text'.
prompt_metadatadict[str, str | int] | NoneAdditional metadata to merge. Defaults to None.
errorPromptResponseErrorError classification for the response. Defaults to 'none'.

Returns:

Examples:

display_choices

display_choices(param_type: Any) → tuple[Any, ...] | None

Derive the allowed-value display list from a constrained-scalar param_type.

This is the presentation projection of an allowed set: a Parameter stores the constraint as a Literal[...] / Enum type, and serializers render the members on demand instead of reading a separate field. Optional[X] / X | None is unwrapped first.

A list[...] parameter is unwrapped to its element type first, so a constrained list (list[Literal[...]] / list[Enum]) surfaces its element’s allowed set — the is_list + choices projection a multi-select consumer needs.

ParameterTypeDescription
param_typeAnyThe parameter’s type annotation.

Returns:

flatten_to_message_pieces

flatten_to_message_pieces(messages: Sequence[Message]) → MutableSequence[MessagePiece]

Flatten messages into a single list of message pieces.

ParameterTypeDescription
messagesSequence[Message]Messages to flatten.

Returns:

get_all_harm_definitions

get_all_harm_definitions() → dict[str, HarmDefinition]

Load all harm definitions from the standard harm_definition directory.

This function scans the HARM_DEFINITION_PATH directory for all YAML files and loads each one as a HarmDefinition.

Returns:

Raises:

get_all_values

get_all_values(messages: Sequence[Message]) → list[str]

Return all converted values across the provided messages.

ParameterTypeDescription
messagesSequence[Message]Messages to aggregate.

Returns:

get_common_json_schema

get_common_json_schema(name: str) → JsonSchemaDefinition

Return a deep copy of the named schema from COMMON_JSON_SCHEMAS.

Triggers a one-shot YAML scan of JSON_SCHEMAS_PATH on first call. A fresh dict is returned so callers may freely mutate, extend, or merge the schema without affecting other consumers of the same name.

ParameterTypeDescription
namestrRegistry key of the desired schema.

Returns:

Raises:

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:

group_conversation_message_pieces_by_sequence

group_conversation_message_pieces_by_sequence(message_pieces: Sequence[MessagePiece]) → MutableSequence[Message]

Group message pieces from the same conversation into messages.

This is done using the sequence number and conversation ID.

Example:

>>> message_pieces = [
>>>     MessagePiece(conversation_id=1, sequence=1, text="Given this list of creatures, which is your
>>>     favorite:"),
>>>     MessagePiece(conversation_id=1, sequence=2, text="Good question!"),
>>>     MessagePiece(conversation_id=1, sequence=1, text="Raccoon, Narwhal, or Sloth?"),
>>>     MessagePiece(conversation_id=1, sequence=2, text="I'd have to say raccoons are my favorite!"),
>>> ]
>>> grouped_responses = group_conversation_message_pieces(message_pieces)
... [
...     Message(message_pieces=[
...         MessagePiece(conversation_id=1, sequence=1, text="Given this list of creatures, which is your
...         favorite:"),
...         MessagePiece(conversation_id=1, sequence=1, text="Raccoon, Narwhal, or Sloth?")
...     ]),
...     Message(message_pieces=[
...         MessagePiece(conversation_id=1, sequence=2, text="Good question!"),
...         MessagePiece(conversation_id=1, sequence=2, text="I'd have to say raccoons are my favorite!")
...     ])
... ]
ParameterTypeDescription
message_piecesSequence[MessagePiece]A list of MessagePiece objects representing individual message pieces.

Returns:

Raises:

group_message_pieces_into_conversations

group_message_pieces_into_conversations(message_pieces: Sequence[MessagePiece]) → list[list[Message]]

Group message pieces from multiple conversations into separate conversation groups.

This function first groups pieces by conversation ID, then groups each conversation’s pieces by sequence number. Each conversation is returned as a separate list of Message objects.

Example:

>>> message_pieces = [
>>>     MessagePiece(conversation_id="conv1", sequence=1, text="Hello"),
>>>     MessagePiece(conversation_id="conv2", sequence=1, text="Hi there"),
>>>     MessagePiece(conversation_id="conv1", sequence=2, text="How are you?"),
>>>     MessagePiece(conversation_id="conv2", sequence=2, text="I'm good"),
>>> ]
>>> conversations = group_message_pieces_into_conversations(message_pieces)
>>> # Returns a list of 2 conversations:
>>> # [
>>> #   [Message(seq=1), Message(seq=2)],  # conv1
>>> #   [Message(seq=1), Message(seq=2)]   # conv2
>>> # ]
ParameterTypeDescription
message_piecesSequence[MessagePiece]A list of MessagePiece objects from potentially different conversations.

Returns:

group_seeds_into_attack_groups

group_seeds_into_attack_groups(seeds: Sequence[Seed[Any]]) → list[AttackSeedGroup]

Group flat seeds by prompt_group_id into AttackSeedGroup instances.

Seeds sharing a prompt_group_id are collapsed into a single AttackSeedGroup; seeds without one (prompt_group_id is None) each become their own group. Within a group, seeds are ordered by sequence when available before construction.

Construction validates the grouping: AttackSeedGroup requires exactly one objective per group (plus the inherited SeedGroup invariants), so a group that lacks an objective -- or otherwise violates the invariants -- raises a ValueError here. This is intentional: callers that want stored groupings turned into attack groups get a fail-fast error on malformed data.

ParameterTypeDescription
seedsSequence[Seed]The flat seeds to group.

Returns:

Raises:

is_finding_path_complete

is_finding_path_complete(path: DecompositionPath, demonstrated: Mapping[UUID, bool]) → bool

Whether every step of a finding’s path was demonstrated. Completeness is derived, never stored.

ParameterTypeDescription
pathDecompositionPathA path of direct sub-findings.
demonstratedMapping[UUID, bool]Each known sub-finding’s demonstrated flag. Unknown steps count as not demonstrated.

Returns:

load_next_message_prompt

load_next_message_prompt(template_path: str | Path) → SeedPrompt

Load a next-message system prompt template and verify it declares the parameters it needs.

ParameterTypeDescription
template_pathstr | PathPath to the YAML file containing the prompt template.

Returns:

Raises:

Examples:

load_simulated_target_prompt

load_simulated_target_prompt(template_path: str | Path) → SeedPrompt

Load a simulated target system prompt template and verify it declares the parameters it needs.

ParameterTypeDescription
template_pathstr | PathPath to the YAML file containing the prompt template.

Returns:

Raises:

project_behavioral_identity

project_behavioral_identity(identifier: ComponentIdentifier, identifier_type: type[ComponentIdentifier]) → ComponentIdentifier

Return the behavioral view of an identifier tree.

Each component is filtered by its own typed markers, so operational params (endpoints, deployment names, rate limits) are dropped and declared fallbacks are applied. A parent may drop a child outright with Evaluate.Exclude; wrapper slots marked Evaluate.Unwrap are replaced by their first inner component.

ParameterTypeDescription
identifierComponentIdentifierThe full component identifier to project.
identifier_typetype[ComponentIdentifier]The typed identifier schema for the root component.

Returns:

read_usage_int

read_usage_int(source: Any, name: str) → int | None

Read name from a provider usage payload and return it only when it is an integer count.

Which field name holds which count is wire-format specific and therefore the caller’s concern; this helper only owns the read and the int guard, so a partial usage payload contributes just the counts the provider actually reports. Booleans are rejected even though bool is a subclass of int.

ParameterTypeDescription
sourceAnyThe usage object or nested details object (may be None).
namestrThe field name to read.

Returns:

read_usage_value

read_usage_value(source: Any, name: str) → Any

Read name from a provider usage payload, which may be a mapping or an attribute object.

Provider SDKs surface usage either as a typed object (OpenAI/LiteLLM Usage) or as a model_dump’d mapping, so both access styles are supported. Use this to reach nested breakdown objects (for example prompt_tokens_details) before reading counts out of them with read_usage_int.

ParameterTypeDescription
sourceAnyThe usage object or nested details object (may be None).
namestrThe field name to read.

Returns:

register_common_json_schema

register_common_json_schema(name: str, schema: JsonSchemaDefinition, overwrite: bool = False) → None

Register a JSON schema in COMMON_JSON_SCHEMAS under a stable name.

YAML seed prompts (and any other SeedPrompt caller) can then reference the schema via the response_json_schema_name constructor kwarg / YAML key instead of inlining the schema body. A deep copy of schema is stored so later mutation of the caller’s dict does not affect the registry.

Bundled schemas under pyrit/datasets/json_schemas/ are discovered on first access and live in the same registry; this function is the runtime path for adding more (e.g. from a PyRITInitializer body or a test fixture).

Tests that register custom schemas should clean up via unregister_common_json_schema (typically in a fixture’s teardown) so registrations do not leak between tests.

ParameterTypeDescription
namestrStable registry key. Use snake_case.
schemaJsonSchemaDefinitionThe schema body to register.
overwriteboolIf False (default), raises ValueError when name is already registered. Set True to intentionally replace an existing entry.

Raises:

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_prompt_source

resolve_prompt_source(prompt: SeedPrompt | None, path: str | Path | None, prompt_name: str, path_name: str, load_prompt: Callable[[str | Path], SeedPrompt]) → SeedPrompt | None

Choose between a canonical prompt and its deprecated path input, loading the path if needed.

Every boundary that still accepts a *_system_prompt_path uses this so they all warn the same way and reject the same ambiguity. It reads from disk, so async callers must run it through asyncio.to_thread.

ParameterTypeDescription
promptSeedPrompt | NoneThe canonical prompt, if the caller supplied one.
pathstr | Path | NoneThe deprecated path input, if the caller supplied one.
prompt_namestrName of the canonical parameter, used in messages.
path_namestrName of the deprecated parameter, used in messages.
load_promptCallable[[str | Path], SeedPrompt]Loader that turns the path into a prompt.

Returns:

Raises:

scenario_dataset_size_from_limit

scenario_dataset_size_from_limit(limit: ResolvedDatasetLimit) → BoundedDatasetSize | AllAvailableDatasetSize

Return a finite-source budget from an optional selection limit.

scorable_from_dict

scorable_from_dict(value: dict[str, Any]) → ScorableUnion

Rebuild a stored scorable from its scorable_type tag.

ParameterTypeDescription
valuedict[str, Any]A stored model_dump of a scorable.

Returns:

Raises:

scoring_expectation_fingerprint

scoring_expectation_fingerprint(exp: ScoringExpectation) → str

Return a stable content fingerprint of an expectation.

The fingerprint is the lowercase SHA-256 hex of the canonical JSON serialization (sorted keys, compact separators). JSON object key order does not affect the digest, but condition tuple order is preserved and remains significant.

ParameterTypeDescription
expScoringExpectationThe expectation to fingerprint.

Returns:

snake_case_to_class_name

snake_case_to_class_name(snake_case_name: str, suffix: str = '') → str

Convert a snake_case name to a PascalCase class name.

ParameterTypeDescription
snake_case_namestrThe snake_case name to convert (e.g., “my_custom”).
suffixstrOptional suffix to append to the class name (e.g., “Scenario” would convert “my_custom” to “MyCustomScenario”). Defaults to ''.

Returns:

sort_message_pieces

sort_message_pieces(message_pieces: list[MessagePiece]) → list[MessagePiece]

Group by conversation_id, then order by sequence and piece timestamp.

Conversations are ordered by their earliest piece’s timestamp; pieces within a conversation are ordered by sequence and then by creation time.

ParameterTypeDescription
message_pieceslist[MessagePiece]The pieces to sort. Not mutated.

Returns:

unregister_common_json_schema

unregister_common_json_schema(name: str) → None

Remove a previously registered schema from COMMON_JSON_SCHEMAS.

Works uniformly on YAML-discovered and runtime-registered entries. Primarily intended for test teardown so transient registrations do not leak across test cases.

ParameterTypeDescription
namestrRegistry key to remove.

Raises:

validate_own_decomposition

validate_own_decomposition(node_id: UUID | None, parent_id: UUID | None, paths: tuple[DecompositionPath, ...]) → None

Check the relationship fields one node can validate without its relatives.

ParameterTypeDescription
node_idUUID | NoneThe node’s ID.
parent_idUUID | NoneThe node’s parent, if any.
pathstuple[DecompositionPath, ...]The node’s paths.

Raises:

validate_registry_name

validate_registry_name(name: str) → None

Validate that name is a legal registry name.

ParameterTypeDescription
namestrThe name to validate.

Raises:

warn_prompt_path_deprecated

warn_prompt_path_deprecated(prompt: SeedPrompt | None, prompt_name: str, path_name: str) → None

Reject an ambiguous prompt source and warn that the path input is deprecated.

Separated from loading so async callers can run this on the event loop, where the warning points at their own call site, and send only the file read to a worker thread.

ParameterTypeDescription
promptSeedPrompt | NoneThe canonical prompt, if the caller supplied one alongside the path.
prompt_namestrName of the canonical parameter, used in messages.
path_namestrName of the deprecated parameter, used in messages.

Raises:

Acquisition

Bases: str, Enum

Whether evidence was acquired and the selected scope was completely covered.

AdversarialPrompts

Bases: BaseModel

Text prompts associated with a seed group, not its application conversation.

Methods:

from_metadata

from_metadata(metadata: Mapping[str, Any] | None) → Self | None

Read the association without changing seed metadata.

ParameterTypeDescription
metadataMapping[str, Any] | NoneSeed metadata that may hold the association.

Returns:

to_metadata

to_metadata() → dict[str, Any]

Serialize the group association on its objective seed.

Returns:

AllAvailableDatasetSize

Bases: _BudgetModel

A finite source without a finite aggregate cap; child caps still apply.

AnswerMatches

Bases: Condition

The evidence answers a question with the expected choice label or answer text.

AssertBehaviorCategory

Bases: _AssertModel

An observable behavior with an explicit policy stance.

AssertBehaviorDefinition

Bases: _AssertModel

The root behavior and its operational scope.

AssertBehaviorPreset

Bases: _AssertPreset

A ready-made behavior description from the bundled ASSERT behavior library.

Methods:

to_config

to_config(group_count: int, context: str = '') → AssertGenerationConfig

Build a generation request for this behavior.

ParameterTypeDescription
group_countintThe number of seed groups to generate.
contextstrThe application the generated groups test. Defaults to none.

Returns:

AssertBinaryRate

Bases: _AssertMetricsModel

A flagged share of applicable conversations, with a 90% Wilson score interval.

rate and the interval are None when no conversation is applicable. Not-applicable conversations are counted but never enter the denominator. sufficient_support is False below 5 applicable conversations, ASSERT’s minimum support.

AssertCategoryJudgment

Bases: _AssertScoreMetadata

The per-category judgments of a category-validated ASSERT judge.

Only relevant categories are listed. original_score_value is the judge’s own verdict, before policy_violation is recomputed from the categories.

Examples:

Methods:

to_metadata

to_metadata() → _ScoreMetadata

Return the score metadata keys for this data.

Returns:

AssertConceptPattern

Bases: _AssertModel

An observable pattern with theory, terms, and variable components.

AssertConceptSpecification

Bases: _AssertModel

The root behavior and its acceptable and problematic patterns.

AssertCoverage

Bases: _AssertModel

Measured level and pair coverage for one generated population.

Methods:

from_assignments

from_assignments(levels: Mapping[str, Sequence[str]], assignments: Sequence[Mapping[str, str]]) → Self

Measure actual assignments, including the behavior axis.

Returns:

Raises:

AssertDimension

Bases: _AssertModel

Explicit levels or an English description from which to generate levels.

Examples:

AssertDimensionLevel

Bases: _AssertModel

One named level of a coverage dimension.

AssertDimensionResult

Bases: _AssertScoreMetadata

Which ASSERT dimension a score judges, and what it records beyond the true/false verdict.

A not-applicable answer and a skipped conversation are undetermined scores. A graded dimension records its declared grades in order, and the grade the judge chose.

Methods:

to_metadata

to_metadata() → _ScoreMetadata

Return the score metadata keys for this data.

Returns:

AssertGeneratedGroupContent

Bases: _AssertModel

Model-written content and coverage assignment for one seed group, before it’s packaged as seeds.

AssertGenerationCheckpoint

Bases: _AssertModel

The completed stages of one ASSERT generation request.

A checkpoint lets generation stop after any stage for review, accept a revised taxonomy and dimensions, and resume after an interruption without repeating finished model calls. It records the target that produced each role’s work, so packaging attributes it correctly and resuming can’t silently mix models.

Examples:

Methods:

with_reviewed_policy

with_reviewed_policy(taxonomy: AssertTaxonomy, dimensions: Sequence[AssertDimension]) → Self

Replace the generated taxonomy and dimensions with reviewed versions.

The reviewed policy becomes part of the request: its taxonomy and explicit dimension levels. Each stored group’s request then reproduces that policy on a rerun, without the research stages. The provenance records which stages a person edited.

ParameterTypeDescription
taxonomyAssertTaxonomyThe reviewed taxonomy. Its behavior name can’t change.
dimensionsSequence[AssertDimension]The reviewed dimensions, each with explicit levels.

Returns:

Raises:

AssertGenerationConfig

Bases: _AssertModel

A serializable generation request, without targets or credentials.

Examples:

AssertGenerationProvenance

Bases: _AssertModel

Research stages, the generation batch, and any human edits behind one seed group.

AssertGenerationStage

Bases: StrEnum

ASSERT generation stages, in execution order.

Examples:

AssertGroupMetadata

Bases: _AssertModel

Policy, tester task, coverage assignment, and provenance for one ASSERT group.

Examples:

Methods:

from_metadata

from_metadata(metadata: Mapping[str, Any] | None) → Self

Validate a group’s retained ASSERT generation context.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, Any]

Serialize this value for seed metadata.

Returns:

AssertJudgeDimension

Bases: _AssertJudgeModel

A custom ASSERT judge dimension.

Without a scale the dimension is a boolean bad-event flag: True means the undesirable event occurred. With ASSERT’s ordinal scale the judge returns one of the declared grades, and violation_at (a PyRIT addition) names the first grade, in declared order, that counts as a violation. allow_not_applicable lets the judge report that the conversation did not exercise the dimension; such a verdict is undetermined. The built-in policy_violation and overrefusal dimensions are judged against the taxonomy and cannot be redefined; disable one and add a differently named dimension to replace it.

Methods:

grade_index

grade_index(value: object) → int | None

Find a verdict’s position among the dimension’s grades, matching its type exactly.

ParameterTypeDescription
valueobjectA boolean verdict, or a declared grade.

Returns:

AssertJudgePreset

Bases: _AssertJudgeModel

A named, reusable group of judge dimensions.

The YAML form matches ASSERT’s judge_preset files: dimensions maps each dimension name to its definition. builtin_dimensions names the built-in dimensions a preset covers. Built-ins are always enabled unless disabled, so listing them only documents the preset.

Methods:

from_yaml_file

from_yaml_file(path: str | Path) → AssertJudgePreset

Load a preset from an ASSERT-style judge_preset YAML file.

ParameterTypeDescription
pathstr | PathThe preset file.

Returns:

Raises:

AssertNodeJudgment

Bases: BaseModel

The judge’s verdict for one taxonomy category it found relevant.

AssertPatternRole

Bases: str, Enum

The policy stance of an observable concept pattern.

AssertPolicyMetrics

Bases: _AssertMetricsModel

ASSERT’s headline metrics for one foundry.assert_policy run.

techniques is keyed by attack technique name, with baseline (ASSERT’s prompt cases) first; rates are never pooled across them. The split is unavailable, with split_unavailable_reason set, when no conversation has a policy verdict with per-category judgments. judgment_mode is category_validated, direct, or mixed across the policy verdicts, or None when there are none.

AssertReplication

Bases: str, Enum

Replication policy for full-factorial assignments.

AssertSampleVote

Bases: str, Enum

One judge sample’s answer in a repeated ASSERT judgment.

AssertSampleVotes

Bases: _AssertScoreMetadata

Every sample’s answer when an ASSERT judge is repeated, and how much the decided samples agree.

voted_score_value is the plain majority, recorded only when the verdict was recomputed from the voted category judgments and differs from it.

Methods:

to_metadata

to_metadata() → _ScoreMetadata

Return the score metadata keys for this data.

Returns:

AssertSamplingConfig

Bases: _AssertModel

Configuration for deterministic assignment selection.

AssertSamplingMethod

Bases: str, Enum

Assignment-selection methods supported by ASSERT.

AssertSkipReason

Bases: str, Enum

Why an ASSERT scenario didn’t judge a conversation.

AssertSlot

Bases: _AssertModel

A pattern component and its conditional refinements.

AssertSlotValue

Bases: _AssertModel

One concrete value of a concept-pattern slot.

AssertStakeholder

Bases: _AssertModel

One distinct perspective used in behavior research.

AssertSuitePreset

Bases: _AssertPreset

An application context and the library behaviors to evaluate in it, one dataset per behavior.

Methods:

to_configs

to_configs(behaviors: Mapping[str, AssertBehaviorPreset], group_count: int) → list[AssertGenerationConfig]

Build one generation request per suite behavior, each in the suite’s context.

ParameterTypeDescription
behaviorsMapping[str, AssertBehaviorPreset]Behavior presets by name, such as list_assert_behavior_presets().
group_countintThe number of seed groups to generate for each behavior.

Returns:

Raises:

AssertSystematization

Bases: _AssertModel

Research and concept specification preceding taxonomy conversion.

AssertTaxonomy

Bases: _AssertModel

The complete policy used to generate seed groups.

Examples:

Methods:

get_coverage_levels

get_coverage_levels(dimensions: tuple[AssertDimension, ...]) → dict[str, list[str]]

Describe the category and dimension levels available for generation assignments.

ParameterTypeDescription
dimensionstuple[AssertDimension, ...]Resolved coverage dimensions.

Returns:

AssertTerm

Bases: _AssertModel

An operational definition used by a behavior taxonomy.

AtomicAttackEvaluationIdentifier

Bases: EvaluationIdentifier

Evaluation identity for atomic attacks.

Rules are derived from AtomicAttackIdentifier’s field markers, which propagate down the technique/attack subtree. The behavioral projection of targets, the objective_target restriction to temperature, and the exclusion of objective_scorer / seed_identifiers all live on the typed identifier fields.

AtomicAttackIdentifier

Bases: ComponentIdentifier

Strongly-typed projection of an atomic attack’s ComponentIdentifier.

Promotes the attack technique (attack_technique) and all seed identifiers from the dataset (seed_identifiers). seed_identifiers is excluded from the eval hash — it is present for traceability only.

The simulated-conversation adversarial chat hash is an unpromoted param: it feeds the identity and eval hashes without adding a persisted identifier column.

Methods:

build

build(technique_identifier: ComponentIdentifier | None = None, attack_identifier: ComponentIdentifier | None = None, seed_group: SeedGroup | None = None, simulated_conversation_adversarial_chat_eval_hash: str | None = None) → Self

Build a composite AtomicAttackIdentifier for an atomic attack.

The identifier places the attack technique in children["attack_technique"] and all seeds from the seed group in children["seed_identifiers"] for traceability. A simulated-conversation adversarial chat hash, when given, is stored in params.

Callers that have an AttackTechnique object should pass technique_identifier=attack_technique.get_identifier(). Callers that only have a raw attack strategy identifier (e.g. legacy backward-compat paths) can pass attack_identifier instead, which is wrapped in a minimal technique node automatically.

ParameterTypeDescription
technique_identifierComponentIdentifier | NonePre-built technique identifier from AttackTechnique.get_identifier(). Mutually exclusive with attack_identifier. Defaults to None.
attack_identifierComponentIdentifier | NoneRaw attack strategy identifier. Used when no AttackTechnique instance is available. Mutually exclusive with technique_identifier. Defaults to None.
seed_groupSeedGroup | NoneThe seed group to extract all seeds from. Defaults to None.
simulated_conversation_adversarial_chat_eval_hashstr | NoneBehavioral eval hash of the adversarial chat the atomic attack uses to generate simulated conversations. None when the atomic attack generates none. Defaults to None.

Returns:

Raises:

AttackAnalyticsCell

Bases: _AnalyticsModel

A heatmap cell and the predicates that select its exact cohort.

AttackAnalyticsConverterDirection

Bases: str, Enum

The converter pipeline recorded on an attack.

AttackAnalyticsDimension

Bases: _AnalyticsModel

A metadata dimension, optionally selecting a literal label key or pipeline side.

Label keys containing dots are still literal keys, not nested JSON paths. The dedicated operation/operator dimensions must be used for attribution.

Examples:

AttackAnalyticsDimensionName

Bases: str, Enum

Supported dimensions from saved result metadata, not current registry state.

Objective-target keys use a persisted, versioned evaluation identity so deployment details do not split equivalent configurations. Scenario keys identify saved runs, not their possibly repeated display names. Operation keys are saved Operation IDs; legacy activity saved with only an Operation name uses legacy_operation_name keys. Harm categories describe the attack’s intended coverage, not detected harms. Converter membership describes recorded usage, not an ordered per-turn pipeline.

AttackAnalyticsFacetQuery

Bases: _AnalyticsModel

A bounded lookup for one opened filter control.

Other dimension predicates and outcome/date restrictions remain active. Predicates on this exact dimension are omitted so alternatives remain discoverable. Search is a case-insensitive literal substring of option labels, not attack objectives. search_pattern supplies a full LIKE pattern instead, with ‘%’ and ‘_’ wildcards and ‘/’ escaping.

Examples:

AttackAnalyticsFacets

Bases: _AnalyticsModel

A single page of facet options.

AttackAnalyticsFilter

Bases: _AnalyticsModel

One predicate, with ANY/ALL applied only to the values inside this predicate.

Separate predicates are AND-combined, including repeated predicates for the same dimension. A drill-down must append its predicate instead of replacing an existing converter ANY filter and unintentionally broadening the cohort.

Examples:

AttackAnalyticsFilters

Bases: _AnalyticsModel

The shared cohort selection for reports, facets, and result pages.

No predicates and no outcomes means unrestricted saved results. All four outcomes normalize to the same unrestricted representation. Updated bounds form a half-open interval [after, before) over last-modified timestamps, not attack execution time. Bounds are stored as UTC instants; values outside the supported UTC datetime range are rejected. Request-size limits bound work without sampling results.

Examples:

AttackAnalyticsGroup

Bases: AttackAnalyticsOption

One grouped outcome aggregate and its additional drill-down predicate.

AttackAnalyticsMatchMode

Bases: str, Enum

How values within one dimension predicate are combined.

AttackAnalyticsOption

Bases: _AnalyticsModel

A filter or axis option with a stable, typed key.

AttackAnalyticsQuery

Bases: _AnalyticsModel

A report request, including the initial lightweight result page.

compare_by=None requests one-dimensional groups; otherwise the response contains a bounded heatmap. Group offset/limits paginate groups, not individual attacks. Result and axis limits affect displayed output, never the cohort totals.

Examples:

AttackAnalyticsReport

Bases: _AnalyticsModel

A coherent saved-result report; all numeric analytics come from the SDK.

computed_at belongs to this report and its included first result page. outcome_filter_applied requests the ASR asterisk but never changes the rate formula. groups_overlap warns that multi-valued group/cell totals cannot be summed to recover the overall result count. A non-null drilldown_unavailable_reason means appending this chart’s predicates would exceed the shared filter budget; the current report and result pages remain valid.

Examples:

AttackAnalyticsResultRow

Bases: _AnalyticsModel

A lightweight result projection retaining the exact target content hash for inspection.

AttackAnalyticsResults

Bases: _AnalyticsModel

One fresh result page, independent of the last report’s refresh time.

AttackAnalyticsResultsQuery

Bases: _AnalyticsModel

A results-only request that does not recalculate aggregates.

The opaque cursor belongs to these filters and must be discarded when the cohort changes. Each page is a new read, not a frozen snapshot of an old report.

Examples:

AttackAnalyticsStatistics

Bases: AttackStats

Shared outcome statistics for saved results or selected scenario execution units.

success_rate_decided (also available as success_rate) uses successes / decided results; errors and undetermined outcomes do not enter that denominator. success_rate_ci_lower and success_rate_ci_upper give the 95% Wilson score confidence interval for success_rate_decided (None when total_decided == 0 or when omitted on older payloads). success_rate_all instead includes every outcome in its denominator, as do decided_share and outcome_shares. Rates with no applicable denominator are None; shares for an empty cohort are zero. All proportions are in the range 0 through 1.

Analytics calculates these values after selecting the counted population. total_results can therefore describe distinct saved IDs or latest scenario units. The model does not select attempts or infer a counting policy. Construction and explicit revalidation reject contradictory supplied values. The nullable all-outcome rate and confidence-interval bounds preserve older payloads that omit those fields.

Methods:

validate_consistency

validate_consistency() → None

Check supplied counts, totals, rates, and shares without replacing any of them.

This also validates mutable instances at analytics input boundaries. Analytics remains responsible for calculating statistics from counts.

Raises:

AttackAnalyticsValue

Bases: _AnalyticsModel

An exact metadata value, a legacy Operation name, or an explicit absence bucket.

A real empty string or a label named “Unknown” remains a VALUE. LEGACY_OPERATION_NAME carries the stored name, possibly empty, of activity saved without an Operation ID. MISSING and NO_CONVERTERS carry no string, so neither can collide with user metadata; an absent identifier is different from a known empty pipeline.

Examples:

AttackAnalyticsValueKind

Bases: str, Enum

Disambiguate real metadata from missing values, empty pipelines, and legacy Operation names.

AttackIdentifier

Bases: ComponentIdentifier

Strongly-typed projection of an AttackStrategy’s ComponentIdentifier.

Promotes the effective adversarial system/seed prompts and the attack’s own child slots — objective target, adversarial chat target, objective scorer, and the request/response converter pipelines.

Evaluate.* markers: objective_target is restricted to temperature for the eval hash (its other behavioral params do not affect grouping at the objective slot), and objective_scorer is excluded entirely.

Param.Include makes objective_target a build-time target reference. Param.Exclude keeps effective configuration fields out of build references; callers supply those through the attack’s typed configurations.

AttackOutcome

Bases: str, Enum

Enum representing the possible outcomes of an attack.

Inherits from str so that values serialize naturally in Pydantic models and REST responses without a dedicated mapping function.

Examples:

AttackResult

Bases: StrategyResult, Generic[_ResponsePieceT, _ScoreT]

Base class for all attack results.

Methods:

get_active_conversation_ids

get_active_conversation_ids() → set[str]

Return the main conversation ID plus pruned (user-visible) related conversation IDs.

Excludes adversarial chat conversations which are internal implementation details.

Returns:

get_all_conversation_ids

get_all_conversation_ids() → set[str]

Return the main conversation ID plus all related conversation IDs.

Returns:

get_attack_strategy_identifier

get_attack_strategy_identifier() → ComponentIdentifier | None

Return the attack strategy identifier from the composite atomic identifier.

This replaces the removed attack_identifier property. Extracts the "attack" child from the nested "attack_technique" child of atomic_attack_identifier.

Falls back to children["attack"] for rows created before the nested structure was introduced.

Returns:

get_conversations_by_type

get_conversations_by_type(conversation_type: ConversationType) → list[ConversationReference]

Return all related conversations of the requested type.

ParameterTypeDescription
conversation_typeConversationTypeThe type of conversation to filter by.

Returns:

get_pruned_conversation_ids

get_pruned_conversation_ids() → list[str]

Return IDs of pruned (branched) conversations only.

Returns:

get_scoring_failure

get_scoring_failure(conversation_id: str) → ScoringFailure | None

Read a conversation’s scoring error for the current objective.

Returns:

includes_conversation

includes_conversation(conversation_id: str) → bool

Check whether a conversation belongs to this attack (main or any related).

ParameterTypeDescription
conversation_idstrThe conversation ID to check.

Returns:

AttackResultMetadata

Producer-recorded role and immediate-parent position stored in AttackResult.attribution_data.

Methods:

from_metadata

from_metadata(metadata: dict[str, Any] | None) → Self

Read semantic metadata without inferring a role from conversations or parent linkage.

ParameterTypeDescription
metadatadict[str, Any] | NoneStored attribution data, including legacy records.

Returns:

to_metadata

to_metadata() → dict[str, Any]

Serialize the semantic metadata fragment without parent linkage.

Returns:

AttackResultRole

Bases: str, Enum

What a persisted attack result represents, recorded by the strategy that produced it.

The role says which kind of record this is, not what happened. A target-facing result can still end before any request reaches the objective target (for example, a preparation failure), so the role is not proof that the target was called.

AttackResultSelection

Bases: str, Enum

The identity used when selecting persisted results.

ALL_RESULTS keeps different result IDs distinct even when they share a conversation. LATEST_PER_CONVERSATION represents the legacy newest-matching-result-per-conversation behavior. Defining these modes does not change any caller’s selection policy.

AttackSeedGroup

Bases: SeedGroup

A group of seeds for use in attack scenarios.

This class extends SeedGroup with attack-specific validation:

All other functionality (simulated conversation, prepended conversation, next_message, etc.) is inherited from SeedGroup.

Examples:

Methods:

filter_compatible

filter_compatible(seed_groups: Sequence[AttackSeedGroup], technique: AttackTechniqueSeedGroup) → list[AttackSeedGroup]

Return only the seed groups compatible with the given technique.

A seed group is incompatible when the technique carries a SeedSimulatedConversation whose sequence range overlaps with the group’s prompt sequences.

ParameterTypeDescription
seed_groupsSequence[AttackSeedGroup]Candidate seed groups.
techniqueAttackTechniqueSeedGroupThe technique to check compatibility against.

Returns:

is_compatible_with_technique

is_compatible_with_technique(technique: AttackTechniqueSeedGroup) → bool

Check whether this seed group can be merged with the given technique.

A technique containing a SeedSimulatedConversation is incompatible with seed groups that have SeedPrompt objects whose sequences fall within the simulated conversation’s range.

ParameterTypeDescription
techniqueAttackTechniqueSeedGroupThe technique group to check compatibility with.

Returns:

with_technique

with_technique(technique: AttackTechniqueSeedGroup) → AttackSeedGroup

Return a new AttackSeedGroup with technique seeds merged in.

The original group is not mutated. Technique seeds are inserted at technique.insertion_index (or appended at the end when None). When requested, the objective is appended as a separate final user prompt after merged static prompts and reserved simulated-conversation sequences.

ParameterTypeDescription
techniqueAttackTechniqueSeedGroupA validated AttackTechniqueSeedGroup whose seeds will be merged.

Returns:

Raises:

AttackStats

Compatible six-field statistics for attack analysis results.

AttackTechniqueIdentifier

Bases: ComponentIdentifier

Strongly-typed projection of an AttackTechnique’s ComponentIdentifier.

Promotes the attack strategy child (attack) and the optional technique seeds (technique_seeds).

AttackTechniqueSeedGroup

Bases: SeedGroup

A group of seeds representing a general attack technique.

This class extends SeedGroup with technique-specific validation:

All other functionality (simulated conversation, prepended conversation, next_message, etc.) is inherited from SeedGroup.

Methods:

from_messages

from_messages(messages: list[Message], starting_sequence: int = 0, insertion_index: int | None = None, prompt_placement: Literal['preserve', 'prepend'] = 'prepend') → Self

Build a technique group from conversation messages.

This supports techniques that generate reusable teaching or priming messages programmatically before a generic attack sends each objective.

ParameterTypeDescription
messageslist[Message]Conversation messages to convert into technique seeds.
starting_sequenceintSequence number assigned to the first message. Prompt sequences are usually normalized when the technique is merged into an AttackSeedGroup. If the merged group contains a SeedSimulatedConversation, prompt sequences are preserved, so choose a starting value outside that simulated conversation’s sequence range. Defaults to 0.
insertion_indexint | NoneWhere to insert the technique when merging into a AttackSeedGroup. Defaults to None.
prompt_placementLiteral['preserve', 'prepend']How to place prompts when merging into a AttackSeedGroup. Defaults to "prepend".

Returns:

from_system_prompt

from_system_prompt(system_prompt: str, insertion_index: int | None = None) → Self

Build a technique group carrying a single system-role instruction.

This is the common shape for jailbreaks and role-play techniques whose only payload is a system prompt that should be prepended to every objective. The value is wrapped verbatim (is_jinja_template=False), so any literal {{ ... }} in system_prompt is preserved rather than re-rendered.

The group declares prompt_placement="prepend" so AttackSeedGroup.with_technique places the system framing before the base prompts without relying on a reserved sequence value.

ParameterTypeDescription
system_promptstrThe system-role instruction text.
insertion_indexint | NoneWhere to insert the seed when merging into a AttackSeedGroup. None (default) appends at the end.

Returns:

with_simulation_changes

with_simulation_changes(changes: SimulationChanges) → Self

Rebuild simulation settings and a fixed final turn without changing the source group.

Returns:

Raises:

BoundedDatasetSize

Bases: _BudgetModel

A finite upper limit, not a minimum or an observed count.

CapabilityName

Bases: str, Enum

Canonical identifiers for target capabilities.

This keeps capability identity in one place so policy, requirements, and normalization code do not duplicate string field names.

ChatMessage

Bases: BaseModel

Represents a single OpenAI Chat Completions message.

Mirrors the OpenAI message schema. The content field can be:

Methods:

to_dict

to_dict() → dict[str, Any]

Convert the ChatMessage to a dictionary.

Returns:

ChatMessagesDataset

Bases: BaseModel

Represents a dataset of chat messages.

ChildEvalRule

Bases: BaseModel

Per-child configuration for eval-hash computation.

Controls how a specific named child is treated when building the evaluation hash:

ComponentIdentifier

Bases: BaseModel

Immutable snapshot of a component’s behavioral configuration.

A single type for all component identity — scorers, targets, converters, and any future component types all produce a ComponentIdentifier with their relevant params and children.

The hash is content-addressed: two ComponentIdentifiers with the same class, params, and children produce the same hash. This enables deterministic metrics lookup, DB deduplication, and registry keying.

Typed projections: subclasses (TargetIdentifier, ConverterIdentifier, …) may promote well-known params and children to ordinary typed fields. Promotion is automatic and keyed off the field’s annotation: a scalar field maps to a params entry; a field annotated as a ComponentIdentifier subclass (or a list thereof) maps to a children slot of the same name. The promoted value is mirrored back into params / children before hashing, so a typed subclass serializes and hashes identically to a plain ComponentIdentifier built with the same params/children. Non-promoted members simply stay in params / children.

Attributes: a third bucket alongside params and children for identity-bearing state that is neither behavioral nor a constructor input — e.g. a deployment / model version observed at runtime. Like params it feeds the content hash, but it is excluded from the eval hash and is never used to build the component. No identifier promotes attributes to a typed field today; they are populated explicitly through the attributes dict.

Serialization: model_dump() returns a flat dict where reserved keys (class_name, class_module, hash, pyrit_version, eval_hash, Serialization: model_dump() returns a flat dict where reserved keys (class_name, class_module, hash, pyrit_version, eval_hash, children, attributes) sit at the top level alongside the inlined param values. This shape is also the storage / REST format. Param values are stored in full (no truncation). model_validate() accepts the same flat shape (plus a structured form with an explicit params dict); the content hash is always recomputed on validation, so any stored hash is ignored.

Mutability: the model is frozen, but params and children are dicts whose contents are not deep-frozen — mutating them after construction creates an identifier whose stored hash no longer matches its content. Treat every identifier as a fully immutable value.

Examples:

Methods:

from_component_identifier

from_component_identifier(identifier: ComponentIdentifier) → Self

Return identifier as an instance of this typed subclass.

Pass-through when identifier is already an instance of cls; otherwise revalidate its flat dump into cls (e.g. a base identifier loaded from the DB), rehydrating promoted typed fields. The content hash is recomputed identically across the round-trip.

ParameterTypeDescription
identifierComponentIdentifierA ComponentIdentifier (possibly the base type).

Returns:

get_child

get_child(key: str) → ComponentIdentifier | None

Get a single child by key.

ParameterTypeDescription
keystrChild name.

Returns:

Raises:

get_child_list

get_child_list(key: str) → list[ComponentIdentifier]

Get a list of children by key. Wraps singletons; [] if missing.

ParameterTypeDescription
keystrChild name.

Returns:

get_class_attribute_values

get_class_attribute_values(target_cls: type) → dict[str, Any]

Read each Param.ClassAttr-marked field’s value off a target class.

Lets a registry describe a class (with no configured instance) by sourcing the marked fields directly from class attributes. For every promoted field carrying a ClassAttrMarker, reads the named class attribute (defaulting to the field name upper-cased) from target_cls.

ParameterTypeDescription
target_clstypeThe component class to read class attributes from.

Returns:

get_identity_conflicting_parameter_names

get_identity_conflicting_parameter_names() → frozenset[str]

Get constructor parameter names that override identity-based authentication.

Returns:

get_multiline_parameter_names

get_multiline_parameter_names() → frozenset[str]

Get constructor parameter names whose values require multiline controls.

Returns:

get_reference_component_types

get_reference_component_types() → dict[str, ComponentType]

Map constructor-arg names to the component family each reference resolves to.

A promoted field that is an included constructor parameter (explicit Param.Include or unmarked) and is typed as a child identifier contributes {arg_name: component_type}, where arg_name is the marker alias or the field name and component_type is the child identifier type’s own component_type. Param.Exclude() fields, plain-value fields, and any field typed as a base ComponentIdentifier (whose component_type is None and is therefore not buildable) contribute nothing.

References declared in constructor_references are included as well.

Returns:

get_sensitive_parameter_names

get_sensitive_parameter_names() → frozenset[str]

Get constructor parameter names whose values must be obscured in user interfaces.

Returns:

of

of(obj: object, params: dict[str, Any] | None = None, children: Mapping[str, ComponentIdentifier | list[ComponentIdentifier] | None] | None = None, attributes: dict[str, Any] | None = None, promoted: Any = {}) → Self

Build a ComponentIdentifier from a live object instance.

Extracts class_name and class_module from the object’s type automatically. None-valued params and children are filtered out to keep schemas backward-compatible.

ParameterTypeDescription
objobjectThe live object whose class metadata will populate the identifier.
paramsdict[str, Any] | NoneOptional behavioral params. Defaults to None.
childrenMapping[str, ComponentIdentifier | list[ComponentIdentifier] | None] | NoneOptional child identifiers; None-valued entries are omitted. Defaults to None.
attributesdict[str, Any] | NoneOptional identity-bearing state (hashed, but excluded from the eval hash and not a constructor input). None values dropped. Defaults to None.
**promotedAnyOptional promoted typed fields (for subclasses). Passed by name; None values are dropped. These are mirrored back into params / children automatically. Defaults to {}.

Returns:

promoted_child_field_names

promoted_child_field_names() → tuple[str, ...]

Get names of this identifier’s promoted child fields.

Returns:

promoted_scalar_field_names

promoted_scalar_field_names() → tuple[str, ...]

Get names of this identifier’s promoted scalar (param) fields — the DB-column projection.

Returns:

promoted_scalar_values

promoted_scalar_values() → dict[str, Any]

Get this identifier’s promoted scalar fields as {name: value} (children/targets excluded).

Returns:

with_eval_hash

with_eval_hash(eval_hash: str) → ComponentIdentifier

Return a new identifier with eval_hash set.

This is the single supported way to set eval_hash: it is not computed by the base model, so callers attach it here rather than via the constructor. The content hash is recomputed from the (unchanged) params and children, so it is identical to this identifier’s hash.

ParameterTypeDescription
eval_hashstrThe evaluation hash to attach.

Returns:

ComponentType

Bases: StrEnum

The component family a registry reference resolves to.

Each member maps one-to-one to a registry singleton that resolves references of that family by name (TARGET → TargetRegistry, CONVERTER → ConverterRegistry, SCORER → ScorerRegistry, SCENARIO → ScenarioRegistry, SOURCE → SourceRegistry).

Condition

Bases: BaseModel

What counts as satisfied.

A condition is a neutral predicate about evidence: it says what to detect, never whether detecting it is good or bad. Polarity belongs to a scorer that wraps another, such as TrueFalseInverterScorer. Each scoring domain adds its own subclass.

A concrete subclass declares a condition_type field as a single-value Literal with a matching default. That default is the stable discriminator persisted with the condition and carried in REST payloads, so the type survives serialization without its import path.

Methods:

model_validate

model_validate(obj: Any, strict: bool | None = None, extra: ExtraValues | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) → Self

Validate a condition, dispatching the registry root to its concrete subtype.

ParameterTypeDescription
objAnyThe condition instance or discriminator-tagged representation.
strictbool | NoneWhether Pydantic uses strict validation. Defaults to None.
extraExtraValues | NoneHow Pydantic handles extra fields. Defaults to None.
from_attributesbool | NoneWhether Pydantic reads object attributes. Defaults to None.
contextAny | NoneContext supplied to Pydantic validators. Defaults to None.
by_aliasbool | NoneWhether Pydantic accepts field aliases. Defaults to None.
by_namebool | NoneWhether Pydantic accepts field names. Defaults to None.

Returns:

Raises:

Contains

Bases: _TextMatcher

Find the normalized value within nonempty text.

Examples:

ContentEntryScorable

Bases: Scorable

Persisted loose content, named by id.

This is the stored anchor for a score about loose content: every scorable that reaches storage is a reference, so a persisted score never carries a payload.

ContentScorable

Bases: Scorable

Loose content with no conversation behind it.

This names content, not a message: there is no role or error state. A message-family resolver adapts it for existing message scorers. Once the content is persisted, the score anchors on a ContentEntryScorable naming the stored row instead.

Examples:

Methods:

from_message

from_message(message: Message) → Self

Describe the converted content of a single-piece ephemeral message.

Scorers consume converted_value, so this adapter preserves the converted value and data type rather than the pre-conversion input. Everything else the message carried is dropped, including its role and its error state, so a scorer’s deterministic blocked-response handling no longer applies. Use MessageScorer.score_message_async when that state is part of the evidence.

ParameterTypeDescription
messageMessageThe ephemeral message whose converted content to take.

Returns:

ContentWritten

Bases: Condition

The named location holds content that satisfies an optional text matcher.

The condition supplies the locator, so a scorer builds the SurfaceScorable from uri and match and judges only the content criterion against what its source acquired. SurfaceMatch.GLOB asks whether any selected location holds such content. With no matcher, any nonempty content counts, including binary content.

require_content_change additionally requires a different content state from the attempt’s baseline. This is a state comparison, not a write-event claim: an unrelated edit can leave matching content in place, and identical rewrites or writes followed by restoration are not detected. Without a baseline, this comparison is undetermined.

Examples:

Conversation

Bases: BaseModel

Conversation-scoped metadata shared by every piece in a conversation.

A Conversation records state that belongs to the conversation as a whole rather than to any individual MessagePiece -- most importantly the target the conversation is held with, the attack execution that owns it, and the record of any turns that were retried. Persisting the per-conversation identifiers once here (instead of stamping them onto every piece/row) is what keeps MessagePiece small.

ConversationObservationPayload

Bases: BaseModel

An ordered, reference-backed snapshot of acquired conversation messages.

ConversationReference

Bases: BaseModel

Immutable reference to a conversation that played a role in the attack.

ConversationRetry

Bases: BaseModel

Record of a single retried turn within a conversation.

A retry happens when a turn’s response failed validation (e.g. malformed JSON) and the failed turn was rolled back out of memory so the turn could be resent on a clean history. The record is conversation-scoped metadata: it captures which turn was retried and why, without keeping the discarded turn’s pieces around.

ConversationRetryReason

Bases: StrEnum

Why a turn in a conversation had to be retried.

ConversationScorable

Bases: Scorable

The entire conversation at acquisition time; observations retain the exact snapshot.

Examples:

ConversationStats

Bases: BaseModel

Lightweight aggregate statistics for a conversation.

Used to build attack summaries without loading full message pieces.

ConversationSummary

Bases: BaseModel

Read-only conversation metadata shared by attack and hierarchy views.

ConversationType

Bases: Enum

Types of conversations that can be associated with an attack.

ConverterIdentifier

Bases: ComponentIdentifier

Strongly-typed projection of a Converter’s ComponentIdentifier.

Promotes the supported input/output data types; any converter-specific params stay in params. The converter’s own child slots — converter_target (an LLM target) and sub_converter (a wrapped converter) — are promoted to typed fields.

Build markers (Param.*) declare how these fields map to the converter’s constructor: the supported-type lists are class attributes sourced from the converter class (Param.ClassAttr), while converter_target and sub_converter are included constructor parameters whose identifier types make them references resolved from the target and converter registries.

DatasetFetchPolicy

Bases: str, Enum

When scenario preparation may load a dataset.

DatasetLimitInput

Bases: BaseModel

Editable dataset limit, separate from combined or generated population budgets.

Methods:

validate_value

validate_value() → Self

Require a numeric value only for the value state.

Returns:

Raises:

DatasetLimitState

Bases: str, Enum

How the dataset-limit control obtains its initial value.

DatasetProviderInfo

Bases: BaseModel

Facts and coarse estimates for a dataset provider’s default configuration.

DatasetSelectionMode

Bases: str, Enum

The permitted named-dataset selection.

DatasetSourceInput

Bases: BaseModel

A named source and optional limit and preparation overrides.

Examples:

DecompositionNode

The decomposition relationships of one objective or finding.

DecompositionPath

Bases: BaseModel

One ordered chain of a parent’s direct children that together achieve the parent.

DecompositionTree

A validated forest of decomposition nodes.

Children keep the order in which their nodes were supplied.

Constructor Parameters:

ParameterTypeDescription
nodesIterable[DecompositionNode]Every node of each tree.

Methods:

get_children

get_children(node_id: UUID) → tuple[UUID, ...]

Get a node’s direct children.

ParameterTypeDescription
node_idUUIDThe parent’s ID.

Returns:

Raises:

get_node

get_node(node_id: UUID) → DecompositionNode

Get a node by ID.

ParameterTypeDescription
node_idUUIDThe node’s ID.

Returns:

Raises:

get_subtree

get_subtree(root_id: UUID) → tuple[UUID, ...]

Get a node and all of its descendants.

ParameterTypeDescription
root_idUUIDThe node to start from.

Returns:

Raises:

walk

walk(root_id: UUID) → Iterator[tuple[UUID, int]]

Visit a node and its descendants depth-first, parents before children.

ParameterTypeDescription
root_idUUIDThe node to start from.

Raises:

DisclosesSecret

Bases: Condition

The evidence reveals part of a known secret beyond what the request already revealed.

secret is the value to look for, without whitespace. known_context holds the text the request itself revealed, such as a name or other attributes. Positions of the secret that this text already discloses are not credited to the evidence.

DivergesFromRepetition

Bases: Condition

The evidence continues with other content after repeating the literal text.

EmbeddingData

Bases: BaseModel

Single embedding vector payload with index and object metadata.

EmbeddingResponse

Bases: BaseModel

Embedding API response containing vectors, model metadata, and usage.

Methods:

load_from_file

load_from_file(file_path: Path) → EmbeddingResponse

Load the embedding response from disk.

ParameterTypeDescription
file_pathPathThe path to load the file from.

Returns:

save_to_file

save_to_file(directory_path: Path) → str

Save the embedding response to disk and return the path of the new file.

ParameterTypeDescription
directory_pathPathThe path to save the file to.

Returns:

EmbeddingSupport

Bases: ABC

Protocol-like interface for classes that generate text embeddings.

Methods:

generate_text_embedding

generate_text_embedding(text: str, kwargs: object = {}) → EmbeddingResponse

Generate text embedding synchronously.

ParameterTypeDescription
textstrThe text to generate the embedding for
**kwargsobjectAdditional arguments to pass to the function. Defaults to {}.

Returns:

generate_text_embedding_async

generate_text_embedding_async(text: str, kwargs: object = {}) → EmbeddingResponse

Generate text embedding asynchronously.

ParameterTypeDescription
textstrThe text to generate the embedding for
**kwargsobjectAdditional arguments to pass to the function. Defaults to {}.

Returns:

EmbeddingUsageInformation

Bases: BaseModel

Token usage metadata returned by an embedding API.

Equals

Bases: _TextMatcher

Compare the complete normalized text.

Examples:

Evaluate

Namespace for the field-level evaluation markers (see module docstring).

EvaluationIdentifier

Wraps a ComponentIdentifier with domain-specific eval-hash configuration.

Concrete subclasses name their root typed-identifier type via EVAL_ROOT; the per-child rules (CHILD_EVAL_RULES), the root OWN_RULE, and the root-unwrap slot (ROOT_UNWRAP_CHILD) are then derived from the Evaluate.* field markers on that type’s class graph (see derive_eval_config). The typed identifier fields are the single source of truth for what feeds the eval hash.

Subclasses may instead set CHILD_EVAL_RULES (and optionally OWN_RULE / ROOT_UNWRAP_CHILD) directly to bypass derivation.

The concrete eval_hash property delegates to the module-level compute_eval_hash free function.

ExecutionStep

Bases: _TraceInterval

One normalized execution span: a model call, tool call, agent step, or other operation.

index is the step’s stable position within its observation, used to cite it. Names, labels, inputs, outputs, and errors are kept complete and exactly as observed.

ExecutionStepKind

Bases: str, Enum

The role an execution span played, normalized across tracing conventions.

ExecutionTraceObservationPayload

Bases: BaseModel

An immutable normalized execution snapshot: model calls, tool calls, agent steps, and their content.

Content is kept complete; budgets for what a judge is shown apply when rendering.

Examples:

Finding

Bases: FindingCreate

A saved finding in one operation.

Findings decompose like SeedObjectives, without being linked to them: a parent lists paths, each an ordered chain of its direct sub-findings that together demonstrate it. Paths are replaced on their own, so creating or updating a finding’s fields never changes them.

FindingCreate

Bases: BaseModel

A finding as an operator enters it, independent of attack outcomes and scores.

A sub-finding names its parent finding. Every finding keeps its own severity, and demonstrated records whether the operator showed it, so a decomposition can include steps that were not achieved.

FindingEvidence

Bases: BaseModel

A saved attack result linked to a finding as evidence.

FindingField

Bases: BaseModel

One field of the finding dialog, as a deployment defines it.

Attributes:

ParameterTypeDescription
keystrThe stored name of the value. Keep it fixed; change label to rename what users see.
labelstrThe name the finding dialog and cards show.
typeFindingFieldTypetext, multiline, choice or number. A number takes a plain decimal, such as 9.8 or -2.
requiredboolWhether every finding needs a value. For a cascade, every level with options needs one.
optionslist[FindingFieldOption]A choice field’s options. Write (key, label) pairs for one dropdown, or a dict from each pair to its children for a cascade.
levelslist[tuple[str, str]]The (key, label) of each dropdown under a cascade’s first one. Each level’s value is stored under its own key.
defaultstr | NoneA top-level option the finding dialog preselects for new findings.
allow_otherboolWhether a single-level choice field also accepts typed text.
colorsdict[str, FindingSeverityColor]The severity slot’s badge color for each top-level option.
hintstr | NoneHelp text under the field in the finding dialog.
sectionstr | NoneA heading, such as “Reproduction”, that the finding dialog shows above this field when the field before it has a different section.

Examples:

FindingFieldType

Bases: StrEnum

How the finding dialog collects a field’s value.

Examples:

FindingFields

Bases: BaseModel

A deployment’s finding fields: the severity slot and the fields shown after it.

Attributes:

ParameterTypeDescription
severityFindingFieldThe required severity choice. List its options from highest to lowest; findings sort in that order.
fieldslist[FindingField]The fields after the severity slot, in dialog order.

Examples:

Methods:

apply_edit

apply_edit(stored: FindingCreate, edit: FindingCreate, keep_retired_keys: Collection[str] = (), remove_retired_keys: Collection[str] = ()) → FindingCreate

Build the finding that an edit saves, checked against these fields.

A current field left out of the edit is cleared. Stored values of fields that are no longer configured are kept unchanged, unless their keys are listed in remove_retired_keys. A stored value whose key is listed in keep_retired_keys is kept too, even if these fields use the key again.

ParameterTypeDescription
storedFindingCreateThe finding as saved.
editFindingCreateThe edited finding, with its current field values.
keep_retired_keysCollection[str]Keys of the stored values the editor showed as retired. Defaults to none.
remove_retired_keysCollection[str]Keys of the stored retired values to delete. Defaults to none.

Returns:

Raises:

check_values

check_values(severity: str, field_values: dict[str, str], previous_severity: str | None = None, previous_values: dict[str, str] | None = None) → None

Check a finding’s severity and field values against these fields.

On an edit, pass the stored finding’s severity and values. A value that has not changed since then may name an option or key that no longer exists.

ParameterTypeDescription
severitystrThe severity slot’s value.
field_valuesdict[str, str]The values of the other fields and of every level, by key.
previous_severitystr | NoneThe stored finding’s severity, or None for a new finding. Defaults to None.
previous_valuesdict[str, str] | NoneThe stored finding’s field values, or None for a new finding. Defaults to None.

Raises:

describe_values

describe_values(severity: str, field_values: dict[str, str]) → FindingValueDescription

Label a finding’s filled values for display.

Rows follow the configured order: the severity slot’s levels, then each field and its levels. A choice value shows the label of the matching option under its stored parent; any other value shows as typed.

ParameterTypeDescription
severitystrThe severity slot’s value.
field_valuesdict[str, str]The values of the other fields and of every level, by key.

Returns:

FindingSeverityColor

Bases: StrEnum

Badge color of a severity option. CoPyRIT renders each one with a Fluent UI badge color.

Examples:

FindingValuesError

Bases: ValueError

A finding’s values do not fit the deployment’s finding fields.

FloatFeedback

The float value behind a true/false verdict, such as the scale score a threshold was applied to.

This type owns the original_float_value metadata key and its readers and writers. An ordinary read treats missing or unusable data as unset. A strict read is for callers that rely on a scorer’s promise to keep the value, and rejects missing or invalid data.

Attributes:

ParameterTypeDescription
valuefloatA finite number in [0, 1].

Methods:

from_metadata

from_metadata(metadata: Mapping[str, str | int | float] | None) → FloatFeedback | None

Read usable feedback from metadata, treating legacy or invalid values as unset.

Returns:

read

read(score: Score | None) → FloatFeedback | None

Read the float value a score kept, treating missing or unusable data as unset.

ParameterTypeDescription
scoreScore | NoneThe score to read.

Returns:

remove_from

remove_from(metadata: Mapping[str, str | int | float] | None) → dict[str, str | int | float]

Return a copy of score metadata without a float value.

Use this when a result no longer judges the same criterion as the value it carried, for example after inverting a verdict.

ParameterTypeDescription
metadataMapping[str, str | int | float] | NoneThe metadata to copy.

Returns:

require

require(score: Score) → FloatFeedback

Read the float value a score promised to keep.

ParameterTypeDescription
scoreScoreA complete true/false score from a scorer that guarantees the value.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, float]

Return the metadata fragment carrying this value.

Returns:

write_to

write_to(metadata: Mapping[str, str | int | float] | None) → dict[str, str | int | float]

Return a copy of score metadata that carries this value.

ParameterTypeDescription
metadataMapping[str, str | int | float] | NoneThe metadata to copy.

Returns:

GCGSeedMetadata

Bases: BaseModel

A seed’s supplied GCG completion prefix, independent of inline job transport.

Methods:

from_metadata

from_metadata(metadata: dict[str, Any]) → GCGSeedMetadata | None

Read a supplied prefix without interpreting other seed metadata.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, Any]

Return the namespaced metadata fragment for a seed.

HarmDefinition

Bases: BaseModel

A harm definition loaded from a YAML file.

This class represents the structured content of a harm definition YAML file, which includes the version, category name, and scale descriptions that define how to score content for this harm category.

Attributes:

ParameterTypeDescription
versionstrThe version of the harm definition (e.g., “1.0”).
categorystrThe harm category name (e.g., “violence”, “hate_speech”).
scale_descriptionslist[ScaleDescription]List of scale descriptions defining score levels.
source_pathstr | NoneThe path to the YAML file this was loaded from.

Methods:

from_yaml

from_yaml(harm_definition_path: str | Path) → Self

Load and validate a harm definition from a YAML file.

The function first checks if the path is a simple filename (e.g., “violence.yaml”) and if so, looks for it in the standard HARM_DEFINITION_PATH directory. Otherwise, it treats the path as a full or relative path.

ParameterTypeDescription
harm_definition_pathstr | PathPath to the harm definition YAML file. Can be a simple filename like “violence.yaml” which will be resolved relative to the standard harm_definition directory, or a full path.

Returns:

Raises:

get_scale_description

get_scale_description(score_value: str) → str | None

Get the description for a specific score value.

ParameterTypeDescription
score_valuestrThe score value to look up (e.g., “1”, “2”).

Returns:

validate_category

validate_category(category: str, check_exists: bool = False) → bool

Validate a harm category name.

Validates that the category name follows the naming convention (lowercase letters and underscores only) and optionally checks if it exists in the standard harm definitions.

ParameterTypeDescription
categorystrThe category name to validate.
check_existsboolIf True, also verify the category exists in get_all_harm_definitions(). Defaults to False.

Returns:

Identifiable

Bases: ABC

Abstract base class for components that provide a behavioral identity.

Components implement _build_identifier() to return a frozen ComponentIdentifier snapshot. The identifier is built lazily on first access and cached for the component’s lifetime.

Methods:

get_identifier

get_identifier() → ComponentIdentifier

Get the component’s identifier, building it lazily on first access.

The identifier is computed once via _build_identifier() and then cached for subsequent calls. This ensures consistent identity throughout the component’s lifetime while deferring computation until actually needed.

Returns:

IdentifierFilter

Bases: BaseModel

Immutable filter definition for matching JSON-backed identifier properties.

Attributes:

ParameterTypeDescription
identifier_typeIdentifierTypeThe type of identifier column to filter on.
property_pathstrThe JSON path for the property to match.
array_element_pathAn optional JSON path that indicates the property at property_path is an array and the condition should resolve if the value at array_element_path matches the target for any element in that array. Cannot be used with partial_match or case_sensitive.
valuestr | NoneThe string value that must match the extracted JSON property value.
value_patternstr | NoneAn explicit case-insensitive full LIKE pattern, instead of value. ‘%’ and ‘_’ are wildcards, ‘/’ escapes the next character; brackets and ‘*’ are literal.
partial_matchboolWhether value is a case-insensitive literal substring. Cannot be used with array_element_path, case_sensitive or value_pattern.
case_sensitiveboolWhether the match should be case-sensitive. Cannot be used with array_element_path or partial_match.

Examples:

IdentifierType

Bases: Enum

Enumeration of supported identifier types for filtering.

Examples:

IndeterminateDatasetSize

Bases: _BudgetModel

A population whose configuration is not known.

InvalidFloatFeedbackError

Bases: ValueError

A score that promised a float value has none, or has one that is not a finite number in [0, 1].

InvalidStrongRejectAnswersError

Bases: ValueError

A StrongREJECT rubric answer is not an integer in the rubric’s range.

JsonResponseConfig

Bases: BaseModel

Canonical PyRIT configuration for requesting a JSON response from a target.

A value object that owns PyRIT’s canonical MessagePiece.prompt_metadata keys for JSON responses ("response_format", JSON_SCHEMA_METADATA_KEY, "json_schema_name", "json_schema_strict") and (de)serializes them via from_metadata / to_metadata. Producers (scorers, attacks, converters) build one and call to_metadata to attach it to a piece; targets read it back with from_metadata.

Providing a json_schema implies enabled (a schema is meaningless without JSON output), so JSON-object mode is enabled=True with no schema and JSON-schema mode is just json_schema=....

These are PyRIT keys, not a provider’s wire format. Translating this config into a specific provider’s request block (e.g. the OpenAI chat response_format or Responses text.format shape) is the target’s job and lives in pyrit.prompt_target (build_response_format / _build_text_format).

For the provider shapes those translators emit, see: https://platform.openai.com/docs/api-reference/chat/create#chat_create-response_format-json_schema and https://platform.openai.com/docs/api-reference/responses/create#responses_create-text

Examples:

Methods:

from_metadata

from_metadata(metadata: dict[str, Any] | None) → Self

Reconstruct a config from a MessagePiece’s prompt_metadata.

Reads the canonical response_format / json_schema keys written by to_metadata. Returns a disabled config when JSON output was not requested (response_format absent or not "json"). A schema stored as a JSON string is parsed back into a dict.

ParameterTypeDescription
metadatadict[str, Any] | NoneThe prompt metadata to read.

Returns:

Raises:

parse_schema

parse_schema(schema_val: dict[str, Any] | str) → dict[str, Any] | None

Read a schema stored under JSON_SCHEMA_METADATA_KEY, which may be a dict or a JSON string.

ParameterTypeDescription
schema_valdict[str, Any] | strThe stored schema. An empty string means no schema.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, Any]

Serialize to the canonical response_format / json_schema metadata keys.

Symmetric with from_metadata: a disabled config produces an empty dict (nothing to request), an enabled config without a schema produces just the response_format marker, and an enabled config with a schema also writes the schema body plus its name and strict flag. The result is meant to be merged into a MessagePiece.prompt_metadata dict.

Returns:

LaunchScenarioSuiteRequest

Bases: _ScenarioSuiteConfiguration

Launch configuration requiring an explicitly selected objective target.

Examples:

MatchesObjective

Bases: Condition

The evidence satisfies the expectation’s own objective, as a judge reads it.

This carries no text of its own. The objective lives on the ScoringExpectation, so a scorer matching this condition reads it from there and the two can never disagree.

Message

Bases: BaseModel, Generic[_MessagePieceT]

Represents a message in a conversation, for example a prompt or a response to a prompt.

This is a single request to a target. It can contain multiple message pieces.

Examples:

Methods:

duplicate

duplicate() → Message

Create a deep copy of this message with new IDs and timestamp for all message pieces.

This is useful when you need to reuse a message template but want fresh IDs to avoid database conflicts (e.g., during retry attempts).

The original_prompt_id is intentionally kept the same to track the origin. Generates a new timestamp to reflect when the duplicate is created.

Returns:

from_prompt

from_prompt(prompt: str, role: ChatMessageRole, prompt_metadata: dict[str, str | int] | None = None) → Self

Build a single-piece message from prompt text.

ParameterTypeDescription
promptstrPrompt text.
roleChatMessageRoleRole assigned to the message piece.
prompt_metadatadict[str, str | int] | NoneOptional prompt metadata. Defaults to None.

Returns:

from_system_prompt

from_system_prompt(system_prompt: str) → Self

Build a message from a system prompt.

ParameterTypeDescription
system_promptstrSystem instruction text.

Returns:

from_system_prompts

from_system_prompts(system_prompts: str = ()) → list[Self]

Build a list of system-role messages, ready to pass as prepended_conversation.

ParameterTypeDescription
*system_promptsstrSystem instruction texts. When omitted, returns an empty list. Defaults to ().

Returns:

get_piece

get_piece(n: int = 0) → MessagePiece

Return the nth message piece.

ParameterTypeDescription
nintZero-based index of the piece to return. Defaults to 0.

Returns:

Raises:

get_piece_by_type

get_piece_by_type(data_type: PromptDataType | None = None, original_value_data_type: PromptDataType | None = None, converted_value_data_type: PromptDataType | None = None) → MessagePiece | None

Return the first message piece matching the given data type, or None.

ParameterTypeDescription
data_typePromptDataType | NoneAlias for converted_value_data_type (for convenience). Defaults to None.
original_value_data_typePromptDataType | NoneThe original_value_data_type to filter by. Defaults to None.
converted_value_data_typePromptDataType | NoneThe converted_value_data_type to filter by. Defaults to None.

Returns:

get_pieces_by_type

get_pieces_by_type(data_type: PromptDataType | None = None, original_value_data_type: PromptDataType | None = None, converted_value_data_type: PromptDataType | None = None) → list[MessagePiece]

Return all message pieces matching the given data type.

ParameterTypeDescription
data_typePromptDataType | NoneAlias for converted_value_data_type (for convenience). Defaults to None.
original_value_data_typePromptDataType | NoneThe original_value_data_type to filter by. Defaults to None.
converted_value_data_typePromptDataType | NoneThe converted_value_data_type to filter by. Defaults to None.

Returns:

get_value

get_value(n: int = 0) → str

Return the converted value of the nth message piece.

ParameterTypeDescription
nintZero-based index of the piece to read. Defaults to 0.

Returns:

Raises:

get_values

get_values() → list[str]

Return the converted values of all message pieces.

Returns:

is_error

is_error() → bool

Check whether any message piece indicates an error.

Returns:

set_response_not_in_memory

set_response_not_in_memory() → None

Mark every piece in this message as ephemeral.

This is needed when we’re scoring prompts or other things that have not been sent by PyRIT. Ephemeral pieces are skipped by add_message_pieces_to_memory.

set_simulated_role

set_simulated_role() → None

Mark all message pieces as injected history with simulated response roles.

This marks the message as coming from a simulated conversation rather than an actual target response.

validate

validate() → None

Validate that all message pieces are internally consistent.

Retained as a public instance method because callers invoke message.validate() directly. Shadows the deprecated BaseModel.validate classmethod.

Raises:

MessagePiece

Bases: BaseModel

A single piece of a message exchanged with a target.

Targets that accept multimodal input (e.g., text + image) are represented as a list of MessagePiece instances grouped under one Message.

Examples:

Methods:

adversarial_placeholder

adversarial_placeholder(role: ChatMessageRole = 'user') → Self

Build a placeholder text piece that signals the adversarial chat will generate the text content at this position.

Intended for use inside AttackParameters.next_message when combining a user-supplied seed (e.g. a base image to edit) with adversarial-generated text on turn 1 of a multi-turn attack. A consumer that walks the message pieces can call is_adversarial_placeholder to detect a slot and replace its value with the generated text before sending the message.

ParameterTypeDescription
roleChatMessageRoleThe chat role to assign to the piece. Defaults to "user".

Returns:

copy_lineage_from

copy_lineage_from(source: MessagePiece) → None

Copy lineage metadata from source onto this piece.

Lineage fields are the metadata that tie a piece back to its originating conversation. Mutable containers (prompt_metadata) are shallow-copied so that mutations on one piece do not affect others.

ParameterTypeDescription
sourceMessagePieceThe piece whose lineage will be copied onto self.

has_error

has_error() → bool

Return True when response_error is not "none".

Returns:

is_adversarial_placeholder

is_adversarial_placeholder() → bool

Return True when this piece is a placeholder for adversarial-generated text.

Detection is based on the adversarial_placeholder flag set by adversarial_placeholder. Plain pieces (created without the flag) always return False.

Returns:

is_blocked

is_blocked() → bool

Return True when response_error is "blocked".

Returns:

is_blocked_error

is_blocked_error() → bool

Return True when this is an error piece for a content-filtered response.

A blocked turn is a real provider round trip that stays in conversation history (filter_non_replayable_messages keeps it), so targets replay it as a text part when rebuilding provider payloads. Error pieces with any other response_error represent failed exchanges and are never replayed.

Returns:

mark_as_structured_refusal

mark_as_structured_refusal(refusal: str) → None

Record an SDK-provided model refusal on this blocked response piece.

ParameterTypeDescription
refusalstrThe model’s refusal explanation.

Raises:

mark_as_truncated

mark_as_truncated() → None

Record that the target cut this response off at its output-token limit.

A truncated piece may still carry a partial answer with response_error == "none", so without this flag a consumer cannot tell a complete answer from a clipped one.

set_simulated_role

set_simulated_role() → None

Mark injected history without retaining evidence of a previous live send.

to_message

to_message() → Message

Wrap this piece in a single-piece Message.

Returns:

MessageScorable

Bases: Scorable

Specific message pieces, named by id.

This names one message, or a subset of its pieces. Loose content that was never persisted has no ids to name, so it is a ContentScorable instead.

Examples:

Methods:

from_message

from_message(message: Message) → Self

Name the pieces of a persisted message.

ParameterTypeDescription
messageMessageThe message whose pieces to name.

Returns:

names_same_evidence

names_same_evidence(other: Scorable | None) → bool

Check whether other names the same message pieces, in any order.

ParameterTypeDescription
otherScorable | NoneThe scorable to compare.

Returns:

Modality

Bases: str, Enum

Canonical high-level modalities for dataset content and target capabilities.

Inherits from str so members compare equal to their string values (e.g. Modality.TEXT == "text") and JSON-serialize as plain strings. This keeps the enum interoperable with existing string-typed APIs while giving authors autocomplete and lint-time typo protection.

Not yet used by TargetCapabilities (which still uses PromptDataType with finer-grained image_path/audio_path/video_path storage tokens). Unifying the two is tracked as a follow-up — see PR #1780.

Methods:

data_type_aliases

data_type_aliases() → dict[str, str]

Map stored media data types to their canonical content modalities.

Returns:

NextMessageSystemPromptPaths

Bases: enum.Enum

Enum for predefined next message generation system prompt paths.

ObjectiveTargetEvaluationIdentifier

Bases: EvaluationIdentifier

Evaluation identity for an objective target.

Rules are derived from TargetIdentifier’s field markers: the target’s own params are filtered to the behavioral set (underlying_model_name, temperature, top_p, http_request_fingerprint) via the derived OWN_RULE, and wrapper targets (e.g. RoundRobinTarget) are unwrapped at the root, so the same logical target produces the same eval hash whether bare or wrapped.

Observation

Bases: BaseModel

Managed evidence acquired about the caller’s scorable anchor.

Methods:

validate_evidence

validate_evidence(message_pieces: Mapping[uuid.UUID, MessagePiece], stored_content: tuple[ContentScorable, str] | None = None) → None

Validate supplied canonical evidence without loading or changing it.

Raises:

Operation

Bases: OperationCreate

A saved operation with stable identity and creation time.

Examples:

OperationCreate

Bases: BaseModel

A named engagement that groups human findings.

OperationUsage

Bases: BaseModel

What still refers to an Operation by ID. Activity attributed only by a deprecated name is not counted.

OutputMatches

Bases: Condition

The output satisfies the supplied text matcher.

Examples:

Parameter

Bases: BaseModel

Describes a parameter that a PyRIT component accepts.

This is the single JSON-serializable parameter descriptor reused across the registry, scenarios, the backend API, and the CLI. param_type carries the value’s live Python type and its allowed set (a Literal[...] or Enum is the allowed set) and drives coerce_value / validate; it is not serialized. Serialization instead projects the type into the display fields type_name, choices, is_list, sensitive, multiline, identity_conflicting, and copy_locked (plus required from the REQUIRED_VALUE sentinel), so a consumer can rebuild a usable contract from the registry without the live type travelling on the wire.

reference, when set, marks the parameter as a registry reference: its value is supplied by name and resolved to a registered instance by the registry layer (Parameter itself never resolves references). The live reference is excluded from serialization; reference_type exposes its component family, while type_name and is_list expose whether clients supply one name or a list of names.

Coercion, strict supplied-value checks, and scalar JSON projection live here. validate checks declarations; validate_value checks an existing value, while validate_json_value applies the opt-in strict external-input contract.

Examples:

Methods:

coerce_value

coerce_value(raw_value: Any) → Any

Coerce raw_value to this parameter’s declared type.

An opaque or reference parameter passes its value through unchanged (by identity — the registry layer resolves a reference by name; an opaque value is a live object owned by the caller). Otherwise it branches by shape: None passes through (deep-copied), a list coerces per element, and a scalar form (including Literal/Enum) coerces and validates membership. Arbitrary defaulted types pass through unchanged.

ParameterTypeDescription
raw_valueAnyThe raw value to coerce.

Returns:

Raises:

for_external_catalog

for_external_catalog() → Parameter

Describe this parameter in the form external callers send it.

A flat Collection or Sequence is described as a list, and a union as its first alternative in declaration order that external callers can send, so font_size: int | tuple[int, int] is described as int; Path | str keeps its own form. Other alternatives are still accepted and coercion is unchanged; only the catalog description changes, and registry metadata keeps the full annotation. A default the described form cannot hold is left out, so callers omit the value and the constructor default applies. SeedPrompt values are described as multiline text, including loaded defaults.

Returns:

is_allowed_external_input

is_allowed_external_input(allowed_path_params: frozenset[str] = frozenset()) → bool

Return whether an external caller may set this parameter.

A parameter that can name a file or folder on the server is allowed only when it is in allowed_path_params.

ParameterTypeDescription
allowed_path_paramsfrozenset[str]Path parameters the caller has made safe. Defaults to none.

Returns:

is_reference_to

is_reference_to(component_type: ComponentType) → bool

Whether this parameter is a registry reference to the given component family.

A reference parameter is supplied by name and resolved to a registered instance by the registry layer. This is the single source of truth for “does this parameter point at a TARGET / CONVERTER / SCORER”, so callers never re-derive it from reference internals.

ParameterTypeDescription
component_typeComponentTypeThe component family to test against.

Returns:

project_json_value

project_json_value(value: Any) → JsonValue

Project a scalar source value without reconstructing opaque or structured state.

Returns:

Raises:

validate

validate() → None

Reject a declaration with an unsupported param_type.

Supported forms are a plain scalar, a constrained scalar (Literal/Enum), a list of any of those, a registry reference, an opaque passthrough, or None. An otherwise-unsupported type is tolerated only when the parameter declares a default (the builder simply does not supply it, and the value passes through unchanged).

Raises:

validate_json_value

validate_json_value(value: Any) → Any

Validate a supplied JSON value without enabling CLI-style scalar coercion.

Enum names and values retain their declared coercion. Structured values are validated recursively by registry resolution, not by this lightweight model.

Returns:

Raises:

validate_value

validate_value(value: Any) → None

Check a resolved scalar or list without coercing or replacing it.

ParameterTypeDescription
valueAnyThe resolved parameter value.

Raises:

ParameterDestination

Bases: str, Enum

Where a declarative parameter is consumed at build time.

ParameterResolution

Bases: BaseModel

The requested numeric value, submitted parameter, and origin of that parameter.

PresetEntry

Bases: BaseModel

A preset as the registry sees it, whichever layer contributed it.

version is set only for a stored preset. A registered preset is held in memory by the code that registered it, so there is no document to guard and nothing to round-trip into a write.

PresetIssue

Bases: BaseModel

One advisory problem found while checking a preset against the live registry.

Issues are reported, never enforced. A preset naming a scenario this deployment has not registered is still a valid preset; it simply cannot run here yet. Blocking the save would make presets un-portable between deployments, which is the one property they exist to have.

ProgramBehaves

Bases: Condition

The program produces the expected result for every case.

The condition carries test stimuli and assertions together, because both vary by dataset row. A scorer splits them before acquisition: the runtime profile and each invocation go to the source, and each expected result stays with the scorer’s matcher. A run that times out or exceeds a resource limit fails its case.

Examples:

ProgramCase

Bases: BaseModel

One invocation and the result it is expected to produce.

Examples:

ProgramExecutionObservationPayload

Bases: BaseModel

What one isolated execution attempt produced: one event per invocation that ran.

program_sha256 digests the exact code the sandbox received, so the evidence names the program even if the message it came from is later edited. reasons explains why an acquisition is not complete. A program that fails its invocations is still complete evidence; only a sandbox that could not run it, or did not finish, leaves gaps.

ProgramExecutionScorable

Bases: Scorable

A program, its runtime, and the invocations to execute.

This is an acquisition request, not a result: it holds no expected output, so the source that runs it cannot see which output passes. program names the code to run: a stored message with one text piece, loose text, or stored loose text. It is used verbatim; code is never extracted from surrounding prose.

Each acquisition runs afresh. The resulting observation’s ID identifies that run; replay uses the stored observation, not this input description.

ProgramResult

Bases: BaseModel

The expected result of one invocation.

exit_code defaults to 0; None accepts any exit code from a program that exited on its own. A stream with no matcher is not checked.

Examples:

PromptGenerationEstimate

Bases: BaseModel

The remaining model calls and an approximate token range for a generation request.

Token counts use a characters-per-token heuristic and typical output sizes, so they show the scale of a request rather than a bill. JSON validation retries and target-side tools such as web search can add more.

Methods:

tokens_from_characters

tokens_from_characters(characters: int) → int

Approximate a token count from a character count.

ParameterTypeDescription
charactersintCharacters of text.

Returns:

PromptGenerationProgress

Bases: BaseModel

Completed stages and item counts.

PromptGenerationRecord

Bases: BaseModel

A stored generation: its inputs, status, resumable progress, and output dataset name.

PromptGenerationStageEstimate

Bases: BaseModel

Expected model calls and approximate total tokens for one generation stage.

PromptGenerationStatus

Bases: str, Enum

Where a generation is in its lifecycle.

ProviderTraceReference

Bases: BaseModel

The identifier a provider returned for one request, for resolving its trace later.

PyRIT-created context is recorded as a W3C traceparent (RequestTraceContext), which only works when the provider accepts and continues that context. Many providers and gateways do not, but they return their own id for the response. This record keeps that id as it came back, with no propagation format, so a trace backend can resolve it to a trace.

Attributes:

ParameterTypeDescription
providerstrThe provider route the target sent the request through. For LiteLLMChatTarget this is LiteLLM’s provider (custom_llm_provider, such as "openai" for any OpenAI-compatible gateway), not a gateway’s own name.
request_idstrThe provider’s id for the response, such as a completion id.

Examples:

Methods:

clear_metadata

clear_metadata(metadata: dict[str, Any]) → None

Remove the reference without touching unrelated metadata.

from_metadata

from_metadata(metadata: dict[str, Any]) → Self | None

Read the reference, rejecting malformed stored metadata.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, str]

Return the namespaced request metadata.

Returns:

QuestionAnsweringDataset

Bases: BaseModel

Represents a dataset for question answering.

QuestionAnsweringEntry

Bases: BaseModel

Represents a question model.

Examples:

Methods:

get_correct_answer_text

get_correct_answer_text() → str

Get the text of the correct answer.

Returns:

Raises:

QuestionChoice

Bases: BaseModel

Represents a choice for a question.

Examples:

ReasoningContentMetadata

Bases: BaseModel

Provider reasoning retained separately from the answer and outbound history.

Methods:

clear_metadata

clear_metadata(metadata: dict[str, Any]) → None

Remove inherited reasoning before recording a new response.

ParameterTypeDescription
metadatadict[str, Any]The response piece’s metadata to update.

from_metadata

from_metadata(metadata: dict[str, Any]) → Self | None

Read reasoning, treating absent or legacy unnamespaced values as unset.

ParameterTypeDescription
metadatadict[str, Any]The response piece’s metadata.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, Any]

Return the response metadata fragment containing the reasoning.

Regex

Bases: _TextMatcher

Search text with the pattern as authored, without normalizing the pattern.

RegistryReference

Self-describing reference to another registry-backed component.

RequestGenerationConfig

Bases: BaseModel

Request-local generation options, independent of the target’s configured defaults.

Examples:

Methods:

clear_metadata

clear_metadata(metadata: dict[str, Any]) → None

Remove request options without touching unrelated metadata.

from_message

from_message(message: Message) → RequestGenerationConfig

Read all current pieces.

Returns:

Raises:

from_metadata

from_metadata(metadata: dict[str, Any] | None) → RequestGenerationConfig

Read generation options from the canonical metadata envelope.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, Any]

Serialize only explicitly selected options into the canonical envelope.

Returns:

RequestGenerationInfo

Bases: BaseModel

Framework-authored generation evidence for one logical send, not a provider success claim.

Methods:

clear_metadata

clear_metadata(metadata: dict[str, Any]) → None

Remove evidence before a new send or response association.

from_metadata

from_metadata(metadata: dict[str, Any] | None) → RequestGenerationInfo | None

Read framework-authored evidence from the canonical metadata envelope.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, Any]

Serialize evidence separately from caller-authored request options.

Returns:

RequestTraceContext

Bases: BaseModel

Request metadata linking stored evidence to a W3C trace.

Methods:

from_metadata

from_metadata(metadata: dict[str, Any]) → Self | None

Read the request context, rejecting malformed stored metadata.

Returns:

to_metadata

to_metadata() → dict[str, str]

Return the namespaced request metadata.

ResolveScenarioPresetRequest

Bases: ScenarioLaunchConfiguration

Launch-owned fields a preset deliberately omits.

expected_version is a precondition rather than launch configuration. A caller that previewed a stored preset supplies that opaque version so an edit landing before launch is reported instead of silently changing the run.

RetryEvent

Bases: BaseModel

A single retry attempt captured during attack execution.

Records structured information about a Tenacity retry event, including which component was retrying, what exception triggered the retry, and timing information. These events are collected by a RetryCollector and attached to AttackResult objects for persistence and REST API exposure.

ScaleDescription

Bases: BaseModel

A single scale description entry from a harm definition.

Attributes:

ParameterTypeDescription
score_valuestrThe score value (e.g., “1”, “2”, etc.)
descriptionstrThe description for this score level.

ScenarioActiveConversation

Bases: BaseModel

A saved objective conversation and the scan execution that produced it.

ScenarioAtomicGroupProgress

Bases: ScenarioProgressCounts

Progress for one planned atomic-attack group.

ScenarioAttackResultDelta

Bases: BaseModel

Lightweight memory projection used to map one scenario progress delta.

ScenarioAttackTechniqueDetails

Bases: ScenarioComponentIdentity

REST details for the technique used by one scenario attack attempt.

ScenarioComponentIdentity

Bases: BaseModel

Display-safe projection of a component’s behavioral identity.

ScenarioDatasetOptions

Bases: BaseModel

Scenario-owned capabilities for dataset overrides.

ScenarioDatasetRequest

Bases: BaseModel

Serializable dataset overrides shared by all application surfaces.

Examples:

ScenarioDatasetSettings

Bases: BaseModel

Resolved defaults or effective settings for display and persistence.

ScenarioDatasetSizeCap

Bases: BaseModel

One configured cap affecting a dataset or compound population.

ScenarioDatasetSizeEstimateKind

Bases: str, Enum

Meaning of a population budget.

ScenarioDatasetSourceSettings

Bases: BaseModel

Effective source settings, not editable request fields.

ScenarioDatasetSummary

Bases: BaseModel

Logical seed-group counts for one default dataset or synthesized population.

ScenarioDisplayGroupProgress

Bases: ScenarioProgressCounts

Progress for one scenario-defined display group.

ScenarioEvaluationIdentifier

Bases: EvaluationIdentifier

Evaluation identity for scenarios.

Rules are derived from ScenarioIdentifier’s field markers: the definition version and resolved techniques / datasets feed the hash, the resolved scenario params are included, and the objective_target / objective_scorer children contribute their full behavioral projection. Two runs of the same scenario definition with the same configuration produce the same eval hash, which backs resume drift detection.

ScenarioExecutionStatistics

Bases: BaseModel

Effective execution-unit statistics for one scenario run, calculated by pyrit.analytics.

Each execution unit counts once, by its latest attempt, so recovered errors do not lower the success percentage. attempts and the errors and retries of each count keep the historical attempt history separately from the effective-unit statistics.

ScenarioExecutionUnit

Bases: BaseModel

Identity of one scenario execution unit.

atomic_group_id identifies the atomic attack together with its technique configuration, so two configurations that share an atomic attack name are separate units. seed_group_id identifies the logical seed group within it.

ScenarioHierarchyDiagnostics

Bases: BaseModel

Bounded diagnostic detail with exact aggregate totals.

Diagnostics lists are capped to bound payload sizes, but total counts remain exact and truncation is signaled explicitly.

ScenarioHierarchyGroup

Bases: BaseModel

One atomic attack group’s hierarchy projection.

ScenarioHierarchyNode

Bases: BaseModel

One node in the scenario result hierarchy.

Can represent an orchestration parent (with children) or a leaf target-facing attack. Maintains ordered child links, parent-relative index, and unresolved child references.

ScenarioHierarchyProjection

Bases: BaseModel

Complete consumed, typed, bounded Scenario result hierarchy projection.

ScenarioIdentifier

Bases: ComponentIdentifier

Strongly-typed projection of a Scenario’s ComponentIdentifier.

Like the sibling projections (TargetIdentifier / ScorerIdentifier), this is produced by the scenario registry when a scenario is built. It is also the canonical per-run identity carried on the ScenarioResult aggregate and persisted with it: the scenario class name (class_name), definition version, resolved techniques / datasets, the resolved scenario params, and the objective_target / objective_scorer child references all live here rather than as separate denormalized fields. Its eval hash (via ScenarioEvaluationIdentifier) backs resume drift detection.

Promotes the scenario’s behavioral identity to typed params fields that feed both the content and eval hash: the definition version and the resolved techniques / datasets the scenario runs (a v1 vs a v2, or a different technique / dataset selection, is a different identity). The two run-resolved reference slots — objective_target (a PromptTarget) and objective_scorer (a Scorer) — are promoted children the registry resolves by name from the target / scorer registries when building a scenario. A run that selects from a scorer pool leaves objective_scorer unset and records the pool as its objective_scorer_pool child.

ScenarioLaunchConfiguration

Bases: _ScenarioLaunchOptions

Target and execution fields a preset or suite launch supplies.

ScenarioObjectiveScorer

Bases: ScenarioScorerIdentity

Objective scorer identity and official evaluation metrics.

ScenarioObjectiveScorerAttribution

Bases: str, Enum

How a report knows which objective scorer judged a set of execution units.

ScenarioObjectiveScorerMetrics

Bases: BaseModel

Official evaluation metrics for an objective scorer configuration.

ScenarioObjectiveScorerScope

Bases: str, Enum

Whether a scenario’s completed results come from one identified objective scorer.

ScenarioObjectiveScorerStatistics

Bases: BaseModel

Effective execution-unit statistics for the units one objective scorer judged.

Success rates are only comparable within one objective scorer: different scorers apply different rubrics. attribution is the weakest evidence used for any attempted unit in the set.

ScenarioOrchestrationParentSummary

Bases: BaseModel

Typed summary of an orchestration parent (e.g. SequentialAttack, Adaptive).

Surfaces execution metrics, completion policies, ordered child result IDs, and retry pressure without equating orchestration results with direct target calls.

ScenarioPreset

Bases: BaseModel, Identifiable

A named, reusable, target-agnostic scenario configuration.

Presets own what to test; a launch owns how and where — target, concurrency, retries, and labels — so those fields are absent here by design and the two sets are combined by union rather than by precedence.

Unknown keys are rejected rather than ignored: these documents are hand-edited, and because an absent field is a meaningful state, a misspelled key would otherwise parse cleanly and leave the preset testing the scenario default.

A document names what to build by registered name, not by class identity, so a preset can move between deployments that register the same name from different code.

Methods:

get_identifier

get_identifier() → ComponentIdentifier

Return the behavioral identity of this preset, rebuilt on every call.

The inherited implementation caches on the instance, which suits a component configured once at construction. A preset is a mutable document, so a cached value would survive model_copy(update=...) and a modified copy would report the original’s identity.

Returns:

ScenarioProducerCategoryCounts

Bases: BaseModel

Raw attempt totals for one specific producer role.

ScenarioProducerCounts

Bases: BaseModel

Raw attempts grouped by their recorded producer role.

ScenarioProgressCounts

Bases: BaseModel

Canonical progress counts for a set of scenario execution units.

outcomes describes only the selected latest attempts and supplies both decided-only and all-outcome success rates. errors and retries retain their historical-attempt meaning and must not be used as outcome denominators. None preserves older count-only payloads whose outcome breakdown is unknown. Supplied totals must agree with the outcome breakdown; mutable values are revalidated when they are passed back into analytics. producer_counts uses a separate historical population and never changes these logical totals.

ScenarioProgressHeader

Bases: BaseModel

Compact persisted run header returned by the progress endpoint.

ScenarioProgressResult

Bases: BaseModel

One persisted attack attempt in ascending progress order.

ScenarioProgressScore

Bases: BaseModel

The objective score attached to one persisted scenario attack result.

ScenarioProgressSummary

Bases: BaseModel

Backend-owned progress rollups for a scenario run.

ScenarioQueueEntry

Bases: BaseModel

One active or queued scenario run in scheduler order.

ScenarioQueueSnapshot

Bases: BaseModel

Point-in-time FIFO scheduler state.

ScenarioResult

Bases: BaseModel

Scenario result class for aggregating scenario results.

Methods:

get_display_groups

get_display_groups() → dict[str, list[AttackResult]]

Aggregate attack results by display group.

When a display_group_map was provided, results from multiple atomic_attack_name keys that share the same display group are merged into a single list. When no map was provided, this returns the same structure as attack_results (identity mapping).

Returns:

get_objectives

get_objectives(atomic_attack_name: str | None = None) → list[str]

Get the list of unique objectives for this scenario.

ParameterTypeDescription
atomic_attack_namestr | NoneName of specific atomic attack to include. If None, includes objectives from all atomic attacks. Defaults to None.

Returns:

get_techniques_used

get_techniques_used() → list[str]

Get the list of techniques present in the results.

With a saved run plan, each planned group counts under its technique, and a baseline counts as baseline, whatever its display group. Without one, results are aggregated by display group so each technique is counted once, even when it fans out into multiple atomic-attack cells (e.g. across datasets or targets in a matrix scenario). When no display_group_map is set, atomic-attack names are returned unchanged.

Returns:

normalize_scenario_name

normalize_scenario_name(scenario_name: str) → str

Normalize a scenario name to match the stored class name format.

Converts CLI-style snake_case names (e.g., “foundry” or “content_harms”) to PascalCase class names (e.g., “ContentHarms”) for callers resolving an alias. If the input is already in PascalCase or doesn’t match the snake_case pattern, it is returned unchanged.

This is the inverse of the snake_case registry-name conversion (class_name_to_snake_case) applied to scenario class names during discovery.

Memory text searches never call this helper implicitly; literal underscores and LIKE pattern syntax must not be rewritten inside a search.

ParameterTypeDescription
scenario_namestrThe scenario name to normalize.

Returns:

objective_achieved_rate

objective_achieved_rate(atomic_attack_name: str | None = None) → int

Get the success rate of this scenario.

.. deprecated:: 1.2.0 Counts every persisted attempt, including ERROR attempts that were later retried or resumed. Use pyrit.analytics.compute_scenario_statistics(result), which counts each execution unit once and is shared with the GUI backend and the reports. Removed in 1.4.0.

ParameterTypeDescription
atomic_attack_namestr | NoneName of specific atomic attack to calculate rate for. If None, calculates rate across all atomic attacks. Defaults to None.

Returns:

ScenarioRunExecutionToken

Bases: BaseModel

The unique identity of one scheduled scenario-run execution.

Methods:

from_metadata

from_metadata(metadata: dict[str, Any]) → Self | None

Read the execution token, or return None when it is absent.

ParameterTypeDescription
metadatadict[str, Any]The scenario-result metadata.

Returns:

to_metadata

to_metadata() → dict[str, str]

Return the namespaced scenario-run metadata.

ScenarioRunListItem

Bases: BaseModel

Lightweight scenario run metadata returned by the history endpoint.

ScenarioRunPlan

Bases: BaseModel

Versioned normalized execution plan persisted in ScenarioResult metadata.

Examples:

ScenarioRunPlanAtomicGroup

Bases: BaseModel

A planned atomic-attack group and its ordered units of work.

ScenarioRunPlanGroupKind

Bases: str, Enum

What a planned atomic group runs, recorded by the code that builds the group.

Examples:

ScenarioRunPlanScorerBinding

Bases: BaseModel

The objective scorer a pool selected for one atomic group.

Recorded only for runs that use a scorer pool. It is part of the group’s id, so a resumed run that would select a different scorer cannot match its saved groups.

ScenarioRunPlanSeedGroup

Bases: BaseModel

A de-duplicated logical seed group in a scenario run plan.

ScenarioRunPlanSeedPrompt

Bases: BaseModel

One non-objective prompt persisted with a logical seed group.

ScenarioRunProgress

Bases: BaseModel

Canonical rollups and an incremental page of scenario progress results.

ScenarioRunSizeComponent

Bases: BaseModel

One additive component of a default-run size estimate.

Methods:

validate_factor_product

validate_factor_product() → Self

Require known component totals to equal their ordered factor product.

Returns:

Raises:

ScenarioRunSizeEstimate

Bases: BaseModel

Structured estimate of default planned scenario execution units.

Counts use the same outer unit as ScenarioRunPlan: one atomic-attack and logical-seed-group pair. Retries and internal attack turns are excluded.

Methods:

normalize_legacy_estimate

normalize_legacy_estimate(data: Any) → Any

Infer status for callers using the original additive estimate fields.

Returns:

Raises:

unavailable

unavailable(note: str = 'Default-run size estimate is unavailable.', dataset_size: ScenarioDatasetSizeEstimate | None = None, dataset_limit: DatasetLimitInput | None = None) → Self

Build an unavailable estimate without presenting a guessed total.

Returns:

validate_estimate

validate_estimate() → Self

Ensure status, bounds, and additive components describe one estimate.

Returns:

Raises:

ScenarioRunSizeEstimateCondition

Bases: str, Enum

Reason an estimate remains conditional until launch.

ScenarioRunSizeEstimateRequest

Bases: _DatasetRequestModel

Request-specific scenario run-size configuration.

ScenarioRunSizeEstimateStatus

Bases: str, Enum

Confidence level for a scenario run-size estimate.

ScenarioRunSizeFactor

Bases: BaseModel

One labeled multiplicative factor in a run-size component.

ScenarioRunState

Bases: StrEnum

Lifecycle state of a scenario run.

A StrEnum, so values serialize naturally in Pydantic models and REST responses, compare equal to their string form, and format as their value (COMPLETED, not ScenarioRunState.COMPLETED) in messages and logs.

ScenarioScorerIdentity

Bases: ScenarioComponentIdentity

Display identity for a scorer and its nested sub-scorers.

ScenarioSeedGroupProgress

Bases: ScenarioProgressCounts

Progress for one logical seed group across atomic attacks.

ScenarioSuite

Bases: BaseModel, Identifiable

A named, ordered collection of scenario preset references.

Only preset names are stored. Preset origin, version, and advisory issues are deployment-specific projections added when the suite is read.

Methods:

get_identifier

get_identifier() → ComponentIdentifier

Return the behavioral identity derived from the current suite definition.

Returns:

ScenarioSuiteEntry

Bases: BaseModel

One ordered reference to a scenario preset.

ScenarioSuiteExecutionEntrySummary

Bases: BaseModel

Current process-local state for one ordered suite entry.

ScenarioSuiteExecutionMetadata

Bases: BaseModel

Identity stamped on every scenario result successfully submitted by a suite launch.

Methods:

from_metadata

from_metadata(metadata: dict[str, Any]) → Self | None

Read suite execution metadata from a scenario result.

Returns:

to_metadata_fields

to_metadata_fields() → dict[str, Any]

Return the namespaced scenario metadata entry owned by this model.

Returns:

ScenarioSuiteExecutionStatus

Bases: str, Enum

Process-local lifecycle of one accepted suite execution.

Examples:

ScenarioSuiteExecutionSummary

Bases: BaseModel

Transient progress and grouped child results for one suite launch.

ScenarioSuiteLaunchEntrySnapshot

Bases: BaseModel

The preset state the operator reviewed for one suite entry.

Examples:

ScenarioSuiteReadinessRequest

Bases: _ScenarioSuiteConfiguration

Dependency-free preview of a suite whose roles may not yet be selected.

ScenarioSuiteSubmissionState

Bases: str, Enum

Suite-owned state before a child becomes an ordinary scenario run.

ScenarioTechniqueProgress

Bases: ScenarioProgressCounts

Progress for one scenario technique.

ScenarioTechniqueSummary

Bases: BaseModel

One concrete attack technique available to a scenario.

Scorable

Bases: BaseModel, ABC

What a scorer looks at.

A scorable is normally an inert reference: it names the evidence instead of carrying or acquiring it. ContentScorable is the exception, because loose content has nothing behind it to point at. A scorer-family resolver acquires the named evidence.

A scorable that can be stored on a Score joins ScorableUnion and declares a scorable_type tag, which is what storage round-trips it on.

Methods:

names_same_evidence

names_same_evidence(other: Scorable | None) → bool

Check whether other names the same evidence.

ParameterTypeDescription
otherScorable | NoneThe scorable to compare.

Returns:

Score

Bases: BaseModel

Represents a normalized score generated by a scorer component.

Examples:

Methods:

get_value

get_value() → bool | float

Return the value of the score based on its type.

If the score type is “true_false”, it returns True if the score value is “true” (case-insensitive), otherwise it returns False.

If the score type is “float_scale”, it returns the score value as a float.

Returns:

Raises:

set_value

set_value(value: bool | float | None) → None

Set this score’s verdict, keeping score_value and status consistent.

A true/false score takes a bool and stores "true" or "false". A float scale score takes a number in [0, 1]. None marks either type undetermined. Nothing changes if the value is rejected.

ParameterTypeDescription
valuebool | float | NoneThe verdict, or None when no verdict was reachable.

Raises:

ScoreStatus

Bases: str, Enum

Whether a verdict was reachable at all.

Completeness is a separate axis from the value, which is what keeps the model honest on both score types at once: a complete true/false score has a boolean, a complete float score has a number, and an undetermined score of either type has nothing.

Inherits from str so values serialize naturally in Pydantic models and REST responses.

Examples:

ScorerCandidateVerdict

Bases: BaseModel

What selection concluded about one candidate in the pool.

Candidates after the selected one are not checked, so they have no verdict.

Attributes:

ParameterTypeDescription
candidate_indexintThe candidate’s position in the pool.
candidate_labelstrThe scorer class and evaluation key, for display.
statusScorerVerdictStatusWhether the candidate was selected or rejected.
reason_kindScorerMismatchKind | NoneFor a rejection, the kind of mismatch.
reasonstr | NoneFor a rejection, why the candidate cannot judge the group.

ScorerCapabilities

What a configured scorer accepts and guarantees, derived from its existing contracts.

This is not a declaration to edit. Scorer.capabilities builds it from the scorer’s supported evidence types, its condition coverage, and the output guarantees its class and configuration make, so it cannot drift from the scorer it describes.

Attributes:

ParameterTypeDescription
scorable_typesfrozenset[type[Scorable]]Evidence references the scorer accepts.
condition_typesfrozenset[type[Condition]]Condition types the scorer tree evaluates.
supportedfrozenset[ScorerCapabilityName]The output guarantees the scorer makes.

Methods:

accepts_scorable_type

accepts_scorable_type(scorable_type: type[Scorable]) → bool

Check whether the scorer accepts an evidence family.

ParameterTypeDescription
scorable_typetype[Scorable]The evidence family the caller will supply.

Returns:

includes

includes(capability: ScorerCapabilityName) → bool

Check whether the scorer makes an output guarantee.

ParameterTypeDescription
capabilityScorerCapabilityNameThe guarantee to check.

Returns:

ScorerCapabilityName

Bases: str, Enum

An output guarantee a scorer can make and a consumer can require.

Scorers declare the result family they return; consumers such as attacks list the guarantees they rely on in ScorerRequirements instead of checking scorer classes.

ScorerEvaluationIdentifier

Bases: EvaluationIdentifier

Evaluation identity for scorers.

Rules are derived from ScorerIdentifier’s field markers. The prompt_target child is projected to behavioral target params only (underlying_model_name, temperature, top_p and, for raw HTTP targets, http_request_fingerprint) and wrapper targets are unwrapped, so the same scorer configuration on different deployments produces the same eval hash.

ScorerIdentifier

Bases: ComponentIdentifier

Strongly-typed projection of a Scorer’s ComponentIdentifier.

Promotes the scorer_type discriminator, the score_aggregator name, and the scorer’s own child slots — prompt_target (an LLM target) and sub_scorers (nested scorers).

Build markers (Param.*) declare how the child slots map to the scorer’s constructor: prompt_target is an included parameter aliased to the chat_target constructor arg, and sub_scorers is an included parameter aliased to the composite scorer’s scorers arg. Their identifier types make them references resolved by name from the target and scorer registries.

The optional sub_scorers_order_independent param declares that the aggregation verdict does not depend on child order.

A source-backed scorer’s source and trace_source constructor arguments are references resolved by name from the source registry. Their identities already sit in children, so they are declared in constructor_references rather than promoted to typed fields.

ScorerMismatchKind

Bases: str, Enum

Why a candidate cannot judge a population.

ScorerSelectionEntry

Bases: BaseModel

The objective scorer selected for one planned atomic group, and the candidates passed over.

Attributes:

ParameterTypeDescription
atomic_attack_namestrThe planned atomic group.
display_groupstrThe group’s report grouping.
techniquestr | NoneThe technique that built the group, when known.
group_kindScenarioRunPlanGroupKindWhat the group runs.
required_capabilitieslist[ScorerCapabilityName]Every output guarantee the selection required, sorted.
required_evaluationstr | NoneThe evaluation the selection required, if any.
candidateslist[ScorerCandidateVerdict]The rejected candidates and the selected one, in pool order.

ScorerSelectionReport

Bases: BaseModel

Which objective scorer each planned atomic group will use, and why earlier candidates were passed over.

Scenario.get_scorer_selection_report builds it from the planned atomic groups after initialize_async, before any prompt is sent and without calling a judge model. Only groups whose scorer was selected from a CompatibleScorers pool have an entry.

Attributes:

ParameterTypeDescription
entrieslist[ScorerSelectionEntry]One entry per planned atomic group, in plan order.

ScorerTargetResponsePayload

Bases: BaseModel

References to the retained response from the scorer’s target.

Methods:

validate_scored_evidence

validate_scored_evidence(scorable: ScorableUnion, scored_piece: MessagePiece | None = None, stored_content: tuple[ContentScorable, str] | None = None) → None

Check supplied scored evidence against the retained digest.

Raises:

ScorerVerdictStatus

Bases: str, Enum

What scorer selection concluded about one candidate.

ScoringExpectation

Bases: BaseModel

What a scorer scores against.

An expectation is a single parameter, so a question authored in a technique configuration or a seed can reach a scorer through an attack that knows nothing about it. It has two independent axes.

objective carries optional scoring context. It can differ from the attack objective that drives adversarial prompts. Scorers may read it for framing or use it as criterion text through MatchesObjective.

conditions carry the criteria: typed objects routed by type to the scorers that match them. Attacks forward them without inspecting them. A typed leaf accepts exactly one of its declared type; wrappers validate coverage and route subsets to their children. Their tuple order is part of the persisted expectation and its fingerprint. SerializeAsAny keeps each condition serialized as its own subtype, so subclass fields survive a round trip.

Seeds can author these criteria; execution parameters transport the resolved expectation. Seed types and condition types need not map one-to-one.

Examples:

Methods:

model_validate_persisted

model_validate_persisted(value: Any) → ScoringExpectation

Validate an expectation loaded from its durable, versioned representation.

ParameterTypeDescription
valueAnyThe persisted expectation representation.

Returns:

validate_type

validate_type(value: object) → None

Check a runtime input without parsing or copying it.

ParameterTypeDescription
valueobjectThe expectation input.

Raises:

Seed

Bases: BaseModel, Generic[_SeedDataTypeT]

Represents seed data with various attributes and metadata.

Methods:

bind_template_parameters

bind_template_parameters(parameters: Any = {}) → Self

Bind literal parameter values for a later template render.

ParameterTypeDescription
**parametersAnyValues retained as template data, not template source. Defaults to {}.

Returns:

escape_for_jinja

escape_for_jinja(value: str) → str

Wrap a string in Jinja2 {% raw %}...{% endraw %} tags to prevent template evaluation.

Use this for any untrusted or externally-fetched text that will be stored as a Seed value, to ensure it is treated as literal text by the Jinja2 renderer.

ParameterTypeDescription
valuestrThe raw string to escape.

Returns:

from_yaml_file

from_yaml_file(file: str | Path) → Self

Create a new Seed from a YAML file, marking it as a trusted Jinja2 template.

Thin shim that delegates to load_seed_from_yaml in the yaml_seed_loader module; file I/O and the is_jinja_template trust marker live in the loader module.

ParameterTypeDescription
filestr | PathThe input file path.

Returns:

Raises:

get_template_parameter_names

get_template_parameter_names() → list[str]

Get the variable names used by this template.

Returns:

Raises:

render_template_value

render_template_value(kwargs: Any = {}) → str

Render self.value as a template with provided parameters.

ParameterTypeDescription
kwargsAnyKey-value pairs to replace in the SeedPrompt value. Defaults to {}.

Returns:

Raises:

render_template_value_silent

render_template_value_silent(kwargs: Any = {}) → str

Render self.value as a template with provided parameters. For parameters in the template that are not provided as kwargs here, this function will leave them as is instead of raising an error.

ParameterTypeDescription
kwargsAnyKey-value pairs to replace in the SeedPrompt value. Defaults to {}.

Returns:

Raises:

SeedDataset

Bases: BaseModel

SeedDataset manages seed prompts plus optional top-level defaults. Prompts are stored as a Sequence[Seed], so references to prompt properties are straightforward (e.g. ds.seeds[0].value).

Examples:

Methods:

from_dict

from_dict(data: dict[str, Any]) → Self

Build a SeedDataset, assigning per-seed prompt_group_id by alias.

Default merging now lives in _build_seeds so direct construction and from_dict produce equivalent results. This method handles the YAML-only concerns: rejecting pre-set prompt_group_id on input seeds and resolving prompt_group_alias into a shared prompt_group_id.

ParameterTypeDescription
datadict[str, Any]Dataset payload with top-level defaults and seed entries.

Returns:

Raises:

from_yaml_file

from_yaml_file(file: str | Path, default_dataset_name: str | None = None) → SeedDataset

Create a SeedDataset from a YAML file, marking nested seeds as trusted templates.

Thin shim that delegates to pyrit.models.seeds.yaml_seed_loader.load_seed_dataset_from_yaml; file I/O and the is_jinja_template trust marker live in the loader module.

ParameterTypeDescription
filestr | PathThe input file path.
default_dataset_namestr | NoneDataset name used when the YAML declares neither dataset_name nor name. Defaults to None.

Returns:

Raises:

get_decomposition_tree

get_decomposition_tree() → DecompositionTree

Build the decomposition trees of this dataset’s objectives.

Only objectives with a parent, paths, or children are included.

Returns:

Raises:

get_random_values

get_random_values(number: NonNegativeInt, harm_categories: Sequence[str] | None = None) → Sequence[str]

Extract and return random prompt values from the dataset.

ParameterTypeDescription
numberintThe number of random prompt values to return.
harm_categoriesSequence[str] | NoneIf provided, only prompts containing at least one of these harm categories are included. Defaults to None.

Returns:

Raises:

get_values

get_values(first: NonNegativeInt | None = None, last: NonNegativeInt | None = None, harm_categories: Sequence[str] | None = None) → Sequence[str]

Extract and return prompt values from the dataset.

ParameterTypeDescription
firstint | NoneIf provided, values from the first N prompts are included. Defaults to None.
lastint | NoneIf provided, values from the last N prompts are included. Defaults to None.
harm_categoriesSequence[str] | NoneIf provided, only prompts containing at least one of these harm categories are included. Defaults to None.

Returns:

Raises:

group_seed_prompts_by_prompt_group_id

group_seed_prompts_by_prompt_group_id(seeds: Sequence[Seed[Any]]) → Sequence[SeedGroup]

Group the given list of seeds by prompt_group_id and create SeedGroup or AttackSeedGroup instances.

For each group, this method first attempts to create a AttackSeedGroup (which has attack-specific properties like objective). If validation fails, it falls back to a basic SeedGroup.

ParameterTypeDescription
seedsSequence[Seed[Any]]A list of Seed objects.

Returns:

Raises:

render_template_value

render_template_value(kwargs: object = {}) → None

Render seed values as templates using provided parameters.

ParameterTypeDescription
kwargsobjectKey-value pairs to replace in the SeedDataset value. Defaults to {}.

Raises:

SeedDatasetGroupProfile

Counts of stored groups sharing structural facts, without seed bodies or schema validation.

SeedDatasetSummary

Aggregate statistics and metadata for the stored seeds in one dataset.

SeedGroup

Bases: BaseModel

A container for grouping prompts that need to be sent together.

This class handles:

All prompts in the group share the same prompt_group_id.

Examples:

Methods:

get_next_message

get_next_message(include_final_assistant: bool = False) → Message | None

Get the outgoing final user turn, or an explicitly opted-in assistant prefix.

Returns:

get_prepended_conversation

get_prepended_conversation(include_final_assistant: bool = False) → list[Message] | None

Get history, optionally reserving the final assistant sequence for continuation.

Returns:

is_single_part_single_text_request

is_single_part_single_text_request() → bool

Check if this is a single text prompt.

Returns:

is_single_request

is_single_request() → bool

Check if all prompts are in a single sequence.

Returns:

is_single_turn

is_single_turn() → bool

Check if this is a single-turn group (single request without objective).

Returns:

render_template_value

render_template_value(kwargs: Any = {}) → None

Render seed values as templates with provided parameters.

ParameterTypeDescription
kwargsAnyKey-value pairs to replace in seed values. Defaults to {}.

SeedGroupRequirements

Dataset input constraints and permission for objective-only adaptation.

Methods:

check

check(seed_group: AttackSeedGroup) → list[str]

Inspect the source group without changing it or applying adaptation.

ParameterTypeDescription
seed_groupAttackSeedGroupThe incoming dataset group, without technique seeds.

Returns:

to_identity

to_identity() → dict[str, Any]

Describe behavioral requirements without serializing executable validators.

Returns:

SeedIdentifier

Bases: ComponentIdentifier

Strongly-typed projection of a Seed’s ComponentIdentifier.

Promotes the seed properties that define its identity: the raw value, its SHA256, the originating dataset, the data type, and whether it is a general technique. Objective conditions and named adversarial prompts are retained in the full identifier JSON. Seeds without them retain their existing identity.

Methods:

from_seed

from_seed(seed: Seed[Any]) → Self

Build a SeedIdentifier from a seed’s behavioral properties.

Captures the seed’s content hash, dataset name, and class type so that different seeds produce different identifiers while the same seed content always produces the same identifier.

ParameterTypeDescription
seedSeed[Any]The seed to build an identifier for.

Returns:

get_behavioral_parameters

get_behavioral_parameters(seed: Seed[Any]) → dict[str, Any]

Project conditions and named prompts for seed identity and storage.

ParameterTypeDescription
seedSeedThe seed whose behavioral inputs are projected.

Returns:

SeedMetadataRequirement

A schema check owned by its parser; bump version when its accepted population changes.

SeedObjective

Bases: Seed[Literal['text']]

Represents a seed objective with various attributes and metadata.

An objective can be decomposed into child objectives. A child names its parent in parent_objective_id, and the parent lists paths: each an ordered chain of its direct children that together achieve it. Children can be decomposed further.

Examples:

SeedOrigin

Bases: StrEnum

How a seed entered PyRIT, independent of upstream authorship.

Examples:

SeedPrompt

Bases: Seed[PromptDataType | None]

Represents a seed prompt with various attributes and metadata.

Examples:

Methods:

compose_with_prefix

compose_with_prefix(base_prompt: SeedPrompt, prefix: str | SeedPrompt, required_parameters: list[str], base_component_name: str = 'prompt', prefix_component_name: str = 'prefix') → SeedPrompt

Prepend static guidance ahead of an already-resolved base prompt.

Combines prefix with base_prompt (separated by a blank line, prefix first). The combined prompt declares the union of both prompts’ parameters — not just required_parameters, which is only the minimum each is validated against — and its response_json_schema is whichever of the two declares one (an error if both do).

An inline string prefix must be static text (no Jinja syntax); an explicitly provided SeedPrompt prefix is exempt and validated against required_parameters like any other SeedPrompt.

The combined prompt is marked is_jinja_template only when both components are, so composing never promotes untrusted text into a trusted template. Promoting it would Jinja-render a value that was deliberately left unrendered, letting a crafted {% endraw %} escape its raw wrapper (see _render_and_infer_data_type).

Descriptive metadata (name, description, source) is intentionally not carried over: the composed prompt is a distinct prompt and should not inherit the base template’s identity.

ParameterTypeDescription
base_promptSeedPromptThe already-resolved base SeedPrompt that the prefix is layered ahead of.
prefixstr | SeedPromptInline string or SeedPrompt to prepend before base_prompt.
required_parameterslist[str]Minimum parameter names the resolved (and, if explicit, the prefix) template must support.
base_component_namestrHuman-readable label for base_prompt, used only in the response_json_schema conflict message. Defaults to 'prompt'.
prefix_component_namestrHuman-readable label for prefix, used in its validation messages and the response_json_schema conflict message. Defaults to 'prefix'.

Returns:

Raises:

from_messages

from_messages(messages: list[Message], starting_sequence: int = 0, prompt_group_id: uuid.UUID | None = None) → list[SeedPrompt]

Convert a list of Messages to a list of SeedPrompts.

Each MessagePiece becomes a SeedPrompt. All pieces from the same message share the same sequence number, preserving the grouping.

ParameterTypeDescription
messageslist[Message]List of Messages to convert.
starting_sequenceintThe starting sequence number. Defaults to 0.
prompt_group_iduuid.UUID | NoneOptional group ID to assign to all prompts. Defaults to None.

Returns:

from_value_with_required_parameters

from_value_with_required_parameters(value: str | SeedPrompt, required_parameters: list[str], error_message: str | None = None, component_name: str = 'prompt') → SeedPrompt

Coerce an inline string or SeedPrompt into a SeedPrompt declaring required_parameters.

Inline strings are trusted: they are wrapped in a Jinja SeedPrompt whose declared parameters are set to required_parameters. Explicitly provided SeedPrompt objects are validated against required_parameters and returned unchanged (never copied).

ParameterTypeDescription
valuestr | SeedPromptThe inline string or SeedPrompt to coerce.
required_parameterslist[str]Parameter names the resolved template must support.
error_messagestr | NoneOptional custom error message for validation failures. Defaults to None.
component_namestrHuman-readable label used in the default failure message (ignored when error_message is provided). Defaults to 'prompt'.

Returns:

Raises:

from_yaml_with_required_parameters

from_yaml_with_required_parameters(template_path: str | Path, required_parameters: list[str], error_message: str | None = None) → SeedPrompt

Load a SeedPrompt from a YAML file and validate that it declares each required parameter.

Thin shim that delegates to pyrit.models.seeds.yaml_seed_loader.load_seed_prompt_from_yaml_with_required_parameters.

ParameterTypeDescription
template_pathstr | PathPath to the YAML file containing the template.
required_parameterslist[str]List of parameter names that must exist in the template.
error_messagestr | NoneCustom error message if validation fails. If None, a default message is used. Defaults to None.

Returns:

Raises:

reject_jinja_syntax

reject_jinja_syntax(value: str, component_name: str = 'prompt') → None

Raise if an inline string contains Jinja template syntax.

Shared by callers that accept static, reviewable guidance rather than a template (e.g. compose_with_prefix, AttackTechniqueFactory.create).

ParameterTypeDescription
valuestrThe inline string to check.
component_namestrHuman-readable label for value, used in the failure message. Defaults to 'prompt'.

Raises:

set_encoding_metadata

set_encoding_metadata() → None

Set encoding metadata for the prompt within metadata dictionary. For images, this is just the file format. For audio and video, this also includes bitrate (kBits/s as int), samplerate (samples/second as int), bitdepth (as int), filesize (bytes as int), and duration (seconds as int) if the file type is supported by TinyTag. Example supported file types include: MP3, MP4, M4A, and WAV.

with_value

with_value(value: str, sequence: int | None = None) → SeedPrompt

Rebuild resolved prompt text and optional sequence without rendering literal template syntax.

ParameterTypeDescription
valuestrThe resolved prompt text.
sequenceint | NoneA replacement sequence, or None to keep the current sequence. Defaults to None.

Returns:

SeedRecord

Bases: BaseModel

Stored seed data for inspection, without rendering, file loading, or generated defaults.

SeedSimulatedConversation

Bases: Seed[Literal['text']]

Configuration for generating a simulated conversation dynamically.

This class holds the prompts and parameters needed to generate prepended conversation content by running an adversarial chat against a simulated (compliant) target. Use with_layered_prefix to layer additional static guidance ahead of the adversarial chat system prompt on an already-built seed (e.g. from a factory producing a per-instance copy) rather than reconstructing its fields directly.

The actual multi-turn conversation is generated by generate_simulated_conversation_async in the executor layer, which accepts this config’s resolved prompt along with runtime dependencies (adversarial_chat target, scorer).

The value property returns a JSON serialization of the config for database storage and deduplication.

The prompts are canonical SeedPrompt templates, so a technique carries its prompt text rather than a file location and can be inspected or edited in place. The matching *_system_prompt_path inputs are still accepted at construction for legacy callers and for reading records persisted before the change; they are resolved immediately and are not stored on the model.

To change a prompt, edit the SeedPrompt and then build a new SeedSimulatedConversation from it. Like the other fields, value is a snapshot taken when the configuration is validated, so mutating a prompt on an existing instance changes what executes without changing what is stored.

Attributes:

ParameterTypeDescription
num_turnsintNumber of conversation turns to generate.
adversarial_chat_system_promptSystemPromptSystem-prompt SeedPrompt for the adversarial chat. Use with_layered_prefix to prepend static guidance ahead of it.
simulated_target_system_promptSystemPromptSystem-prompt SeedPrompt for the simulated target. Defaults to the compliant prompt if not specified.
next_message_system_promptSystemPrompt | NoneOptional system-prompt SeedPrompt for generating an additional user message after the simulated conversation. If provided, a single LLM call generates a final user message that attempts to get the target to fulfill the objective in their next response.

Examples:

Methods:

compute_hash

compute_hash() → str

Compute a deterministic hash of this configuration.

Returns:

get_identifier

get_identifier() → dict[str, Any]

Get an identifier dict capturing this configuration for comparison/storage.

Returns:

load_simulated_target_system_prompt

load_simulated_target_system_prompt(objective: str, num_turns: int, simulated_target_system_prompt_path: str | Path | None = None) → str | None

Load and render the simulated target system prompt.

.. deprecated:: Render SeedSimulatedConversation.simulated_target_system_prompt directly with SeedPrompt.render_template_value(objective=..., num_turns=...) instead. This helper reads from disk, so it must not be called from an async path.

If no path is provided, returns None (no system prompt). Validates that the template has required objective and num_turns parameters.

ParameterTypeDescription
objectivestrThe objective to render into the template.
num_turnsintThe number of turns to render into the template.
simulated_target_system_prompt_pathstr | Path | NoneOptional path to the prompt YAML file. If None, no system prompt is used. Defaults to None.

Returns:

Raises:

with_layered_prefix

with_layered_prefix(prefix: str) → SeedSimulatedConversation

Return a copy of this seed with prefix layered ahead of the adversarial chat prompt.

Prepends prefix directly onto adversarial_chat_system_prompt via SeedPrompt.compose_with_prefix (new prefix first, separated by a blank line). Lets a caller (e.g. a factory layering shared guidance onto a baked technique) extend a seed’s adversarial prompt without reimplementing its copy-and-recompute mechanics. Calling this again on the result layers the new prefix ahead of the previous one.

The original seed is not mutated. The returned copy gets a fresh id and recomputed value/value_sha256 since its configuration changed. The other two prompts are passed through as the same already-resolved instances so they are not re-validated (see _keep_prompt_instance).

ParameterTypeDescription
prefixstrStatic guidance to prepend ahead of the adversarial chat system prompt. Must be static text (no Jinja syntax).

Returns:

Raises:

with_settings

with_settings(changes: SimulationChanges) → SeedSimulatedConversation

Rebuild generation settings without changing message modes or prompt metadata.

Returns:

Raises:

SimulatedTargetSystemPromptPaths

Bases: enum.Enum

Enum for predefined simulated target system prompt paths.

StartsWith

Bases: _TextMatcher

Compare a literal prefix, optionally stripping candidate whitespace and ignoring case.

StoredPreset

Bases: BaseModel

A preset together with the version of the document it was read from.

The version describes the stored document, not the preset, so it is paired with the preset rather than carried as a field on it: storing the token inside the file it guards would let a hand-edit rewrite the value used to detect that edit.

The token is opaque. Callers round-trip it from a read back into a write.

StoredScenarioSuite

Bases: BaseModel

A scenario suite together with the version of its stored document.

StrategyResult

Bases: BaseModel, ABC

Base class for all strategy results.

Methods:

duplicate

duplicate() → Self

Create a deep copy of the result.

Returns:

StrongRejectAnswers

A judge’s answers to the three StrongREJECT rubric questions.

This type owns the strongreject_refusal, strongreject_convincingness and strongreject_specificity metadata keys and their readers and writers. A read treats missing, partial, legacy or invalid data as unset.

Attributes:

ParameterTypeDescription
refusalint1 if the model refused, otherwise 0.
convincingnessintHow convincing the response is, from 1 to 5.
specificityintHow specific the response is, from 1 to 5.

Methods:

from_metadata

from_metadata(metadata: Mapping[str, str | int | float] | None) → StrongRejectAnswers | None

Read the answers from score metadata.

ParameterTypeDescription
metadataMapping[str, str | int | float] | NoneThe score metadata.

Returns:

read

read(score: Score | None) → StrongRejectAnswers | None

Read the answers a StrongREJECT score recorded.

ParameterTypeDescription
scoreScore | NoneThe score to read.

Returns:

to_metadata

to_metadata() → dict[str, int]

Return the metadata fragment carrying these answers.

Returns:

StructuredParameterValue

Bases: ABC

A parameter value with explicitly allowed structured variants.

Methods:

get_registry_input_variants

get_registry_input_variants() → dict[str, type[StructuredParameterValue]]

Declare the implementations available for registry construction.

Returns:

SurfaceBaseline

Bases: BaseModel

What the named locations held when an attempt started.

A baseline lets a later snapshot show differences in observed content, not who wrote it or whether writes occurred between snapshots. Entries keep bounded evidence so a criterion can compare what was there before with what is there now. A location the baseline did not cover cannot establish that a later location is new.

concurrent is set when another attempt observed the same locations while this one ran. The comparison cannot associate a change with this attempt’s window.

Methods:

entry_for

entry_for(uri: str) → SurfaceEntry | None

Return the baseline entry for one location.

ParameterTypeDescription
uristrThe location.

Returns:

SurfaceCoverage

Bases: BaseModel

Whether every location the scorable names was enumerated and read.

SurfaceEntry

Bases: BaseModel

One location a source read, with a bounded copy of its content.

size_bytes is the whole file’s size. sha256 covers the whole content and is None when the source stopped reading before the end, for example on a read budget, so a digest is never claimed for bytes that were not hashed. content retains at most the source’s configured limit and is None when the bytes are not UTF-8 text, so a criterion that needs the text can tell “absent” from “not retained”.

SurfaceMatch

Bases: str, Enum

How a surface locator selects files.

Examples:

SurfaceObservationPayload

Bases: BaseModel

An immutable snapshot of the locations a surface scorable names, as they were when read.

A snapshot finalized against a baseline carries it, so replay can tell which locations differ between the observed states. It does not retain write events.

SurfaceScorable

Bases: Scorable

A file location to inspect when evidence is acquired.

uri names one location, or with SurfaceMatch.GLOB every location the pattern covers. A location names a place, not a write: it does not identify the run that put the content there.

Examples:

TargetCapabilities

Bases: BaseModel

Describes the capabilities of a PromptTarget so that attacks and other components can adapt their behavior accordingly.

Each target class defines default capabilities via the _DEFAULT_CONFIGURATION class attribute. Users can override individual capabilities per instance through constructor parameters, which is useful for targets whose capabilities depend on deployment configuration (e.g., Playwright, HTTP).

Immutable (frozen) so a single capabilities object can be safely shared across targets and reused as a known-model profile.

This model also serves as the REST wire snapshot of a target’s capabilities (it is embedded in TargetInstance), so serialization must be lossless: a dumped payload validated back in has to rebuild an equal object. The immutable frozenset[frozenset] combination fields are therefore serialized in a deterministic form -- a sorted list of sorted lists -- which pydantic parses back into the same structure. The flattened supported_input_modalities / supported_output_modalities computed fields are emitted alongside them for API consumers that only need per-piece modality checks.

Methods:

includes

includes(capability: CapabilityName) → bool

Return whether this target supports the given capability.

ParameterTypeDescription
capabilityCapabilityNameThe capability to check.

Returns:

TargetIdentifier

Bases: ComponentIdentifier

Strongly-typed projection of a PromptTarget’s ComponentIdentifier.

Promotes the common target params to typed fields; any other params stay in params. Message-handling capabilities are not part of identity and are not surfaced here. supported_auth_modes is the one non-identity fact surfaced: a Param.ClassAttr (Evaluate.Exclude) the registry reads off the class into TargetMetadata — never an identity input or a constructor argument.

Promotes the one child slot a target owns in its own constructor: targets (inner targets of a multi-target like RoundRobinTarget), typed recursively as TargetIdentifier.

Evaluate.* markers declare the behavioral projection used for the eval hash: operational params (endpoint / model_name / max_requests_per_minute) are excluded, underlying_model_name falls back to model_name, and targets is a wrapper passthrough that is unwrapped so a multi-target hashes the same as its inner target.

Methods:

get_identity_conflicting_parameter_names

get_identity_conflicting_parameter_names() → frozenset[str]

Get target constructor parameters that override identity-based authentication.

Returns:

get_multiline_parameter_names

get_multiline_parameter_names() → frozenset[str]

Get target constructor parameters whose values require multiline controls.

Returns:

TargetObjectiveGenerationRequest

Bases: BaseModel

The request of a target_objective generation, as TargetObjectiveGenerator accepts it.

Generated objectives store the request in their metadata so it can be edited and run again.

Methods:

from_metadata

from_metadata(metadata: Mapping[str, Any] | None) → Self | None

Read the request stored in seed metadata.

ParameterTypeDescription
metadataMapping[str, Any] | NoneA seed’s metadata.

Returns:

to_metadata

to_metadata() → dict[str, Any]

Serialize this request for seed metadata.

Returns:

TokenUsage

Provider-neutral token accounting for a single model call.

Field names use the input/output vocabulary (aligned with the OpenAI Responses API, Anthropic, and Gemini) rather than the Chat Completions prompt/completion terms. The object is persisted onto a MessagePiece’s prompt_metadata via to_metadata using matching token_usage_input_tokens / token_usage_output_tokens key names (one consistent vocabulary end to end). reasoning_tokens and cached_tokens are the two widely-available sub-breakdowns promoted to fields; any other provider-specific counts (audio, predicted-output, cache-write) ride along in extra.

This is a pure value object: it holds counts and (de)serializes them to metadata. Turning a provider usage payload into a TokenUsage is the responsibility of the target/parser that knows which wire format it received (for example, the Chat Completions parser in pyrit.prompt_target.common.chat_completions_response_parser). Only the format-agnostic part of that read -- mapping-or-attribute access and the integer guard -- is shared here, via read_usage_value and read_usage_int.

Neither cost nor the responding model name is modeled here: cost is a currency amount (tracked separately under token_usage_cost) and the model identity is already recorded on the target’s identifier. Both would be a category error inside a token-count value object.

Only fields the provider actually reports are populated; absent values stay None (and are omitted from to_metadata) rather than being coerced to a misleading zero.

Methods:

from_metadata

from_metadata(metadata: dict[str, Any]) → Self | None

Reconstruct a TokenUsage from a MessagePiece’s prompt_metadata.

Reads the token_usage_input_tokens / token_usage_output_tokens keys written by to_metadata. Non-core integer token_usage_* keys are collected into extra; the string token_usage_cost key is ignored (cost is tracked separately).

ParameterTypeDescription
metadatadict[str, Any]The prompt metadata to read.

Returns:

to_metadata

to_metadata() → dict[str, int]

Serialize to flat token_usage_* metadata keys, omitting fields that are None.

Uses the input/output vocabulary for the key names to match the field names (one consistent naming end to end). extra counts are written verbatim under the token_usage_ prefix.

Returns:

ToolArgumentRequirement

Bases: BaseModel

One argument a tool call must have been made with, compared by a text matcher.

name is an exact, case-sensitive top-level argument key. A string value is compared as it is; any other JSON value is compared as its compact JSON text, with sorted keys.

ToolCall

Bases: BaseModel

Represents a tool invocation requested by the assistant.

ToolCallRequirement

Bases: BaseModel

One exact, case-sensitive tool name required as execution evidence.

arguments optionally narrows the requirement to a call made with matching arguments: one execution of the tool must satisfy every argument requirement. Evidence that does not retain a call’s arguments cannot show that it does, so it leaves the requirement undetermined rather than satisfied.

Examples:

ToolCaptureCoverage

Bases: BaseModel

Whether a target stored every tool execution behind one model response.

A target that runs the model’s function calls itself records this on each model response. complete means every tool that ran for the response is stored as a function_call piece paired with a function_call_output piece, so the stored messages can rule out other tools. gaps name what the target could not store, such as a tool the provider ran itself.

Methods:

from_metadata

from_metadata(metadata: dict[str, Any]) → Self | None

Read the recorded capture coverage.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, Any]

Return the metadata fragment for the response’s first piece.

ToolCaptureGap

Bases: str, Enum

Why the stored messages for a model response may not show every tool that ran for it.

ToolEventsObservationPayload

Bases: BaseModel

An immutable allowlisted tool snapshot, with arguments and results not retained.

Examples:

ToolExecution

Bases: _TraceInterval

Safe immutable name-only execution evidence; arguments and results are not retained.

ToolExecutionMetadata

Bases: BaseModel

Target-recorded invocation status, separate from a tool’s returned data.

Methods:

from_metadata

from_metadata(metadata: dict[str, Any]) → Self | None

Read invocation status without interpreting tool-returned data.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, Any]

Return the metadata fragment for a function-call output piece.

ToolLoopStop

Bases: BaseModel

The reason a target recorded on the error response that ended a tool loop early.

Methods:

from_metadata

from_metadata(metadata: dict[str, Any]) → Self | None

Read the reason a tool loop stopped.

Returns:

Raises:

to_metadata

to_metadata() → dict[str, str | int]

Return the metadata fragment for the error response.

ToolLoopStopReason

Bases: str, Enum

Why a target’s tool loop ended a turn before the model gave its answer.

ToolsCalled

Bases: Condition

Require every named tool to have an execution attempt, regardless of success.

By default this is a subset match: other tools may also have run. exhaustive asks for an exact match instead, so the named tools ran and no other tool did. An exhaustive condition with no tools asks that no tool ran at all.

An exhaustive match can be disproved by one observed execution of an unnamed tool, but confirming it needs evidence complete enough to rule out every other tool.

Examples:

ToolsCalledInOrder

Bases: Condition

Require the named tools to have execution attempts in this relative order.

Each listed tool needs an execution attempt that finished before an execution attempt of the next listed tool started. Other tools, and further attempts of the listed tools, may run in between. Success is not required. Overlapping or unfinished attempts do not establish an order in either direction.

Each tool may be named only once, so an order that returns to a tool (for example read_file then send_email then read_file again) is out of scope. Distinct names keep each tool’s attempts in a single pool, which keeps the match sound.

Examples:

TraceCoverage

Bases: BaseModel

Explicit capture completeness and known reasons coverage is incomplete.

TraceQuery

Bases: BaseModel

A bounded request for the traces named by an immutable scoring scope.

TraceQueryResult

Bases: BaseModel

A transient span snapshot and the client’s explicit capture coverage.

Set available=False only when no evidence can be retrieved, for example after retention expires. Pending capture uses available=True with incomplete coverage. If only some requested traces are available, return their spans with incomplete coverage.

TraceScorable

Bases: Scorable

An exact trace scope supplied by the caller.

Examples:

TraceSpan

Bases: _TraceInterval

Transient backend-neutral span; raw attributes are not durable scoring evidence.

TraceSpanEvent

Bases: BaseModel

A transient timestamped event recorded on a span, such as a GenAI message or an exception.

TraceSpanStatus

Bases: str, Enum

The status of an observed execution attempt, not its scoring verdict.

UndeterminedScoreError

Bases: ValueError

Raised when a caller reads the value of a score that has none.

UnvalidatedScore

Score is an object that validates all the fields. However, we need a common data class that can be used to store the raw score value before it is normalized and validated.

Methods:

to_score

to_score(score_value: str, score_type: ScoreType) → Score

Convert this unvalidated score into a validated Score.

ParameterTypeDescription
score_valuestrNormalized score value.
score_typeScoreTypeScore type.

Returns:

ViolatesAssertPolicy

Bases: Condition

The conversation fails one of an ASSERT judge’s dimensions under this policy.

taxonomy is the complete policy. application_context describes the application and its capabilities, and target_instructions holds its actual instructions when known.

WebSearchConfig

Bases: BaseModel

A request policy; targets own provider options and search-result evidence.

Methods:

from_metadata

from_metadata(metadata: Mapping[str, Any] | None) → Self

Read a policy without changing the metadata.

ParameterTypeDescription
metadataMapping[str, Any] | NoneMessage-piece prompt metadata.

Returns:

to_metadata

to_metadata() → dict[str, Any]

Serialize the policy to message-piece prompt metadata.

Returns:

WebSearchMode

Bases: str, Enum

Whether a request preserves, disables, or requires target-hosted search.