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) → DecompositionTreeBuild the decomposition trees of objectives that have a parent, paths, or children.
| Parameter | Type | Description |
|---|---|---|
objectives | Iterable[SeedObjective] | Objectives that include every member of each tree. |
root_id | uuid.UUID | None | An 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:
DecompositionTree— The validated trees.
Raises:
ValueError— If a parent is missing, an objective appears twice, the parents form a cycle, a path step is not a direct child of the path’s owner, orroot_idis not supplied.
class_name_to_snake_case¶
class_name_to_snake_case(class_name: str, suffix: str = '') → strConvert a PascalCase class name to snake_case, optionally stripping a suffix.
| Parameter | Type | Description |
|---|---|---|
class_name | str | The class name to convert (e.g., “SelfAskRefusalScorer”). |
suffix | str | Optional explicit suffix to strip before conversion (e.g., “Scorer”). Defaults to ''. |
Returns:
str— The snake_case name (e.g., “self_ask_refusal” if suffix=“Scorer”).
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) → strCompute 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.
| Parameter | Type | Description |
|---|---|---|
identifier | ComponentIdentifier | The component identity to compute the hash for. |
child_eval_rules | dict[str, ChildEvalRule] | Per-child eval rules. |
own_rule | ChildEvalRule | None | Rule 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_child | str | None | If 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:
str— A hex-encoded SHA256 hash suitable for eval registry keying.
Raises:
RuntimeError— If the identifier’s hash is None and no filtering is configured.ValueError— Ifown_rulecarries fields that are not meaningful at the root.
compute_seed_group_hash¶
compute_seed_group_hash(seed_identifiers: Sequence[SeedIdentifier]) → strReturn 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=...).
| Parameter | Type | Description |
|---|---|---|
seed_identifiers | Sequence[SeedIdentifier] | The ordered seed identifiers. |
Returns:
str— The SHA256 logical seed-group ID.
config_hash¶
config_hash(config_dict: dict[str, Any]) → strCompute 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.
| Parameter | Type | Description |
|---|---|---|
config_dict | dict[str, Any] | A JSON-serializable dictionary. |
Returns:
str— Hex-encoded SHA256 hash string.
Raises:
TypeError— If config_dict contains values that are not JSON-serializable.
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') → MessageConstruct a response message from a request message piece.
| Parameter | Type | Description |
|---|---|---|
request | MessagePiece | Source request message piece. |
response_text_pieces | list[str] | Response values to include. |
response_type | PromptDataType | Data type for original and converted response values. Defaults to 'text'. |
prompt_metadata | dict[str, str | int] | None | Additional metadata to merge. Defaults to None. |
error | PromptResponseError | Error classification for the response. Defaults to 'none'. |
Returns:
Message— Constructed response message.
Examples:
display_choices¶
display_choices(param_type: Any) → tuple[Any, ...] | NoneDerive 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.
| Parameter | Type | Description |
|---|---|---|
param_type | Any | The parameter’s type annotation. |
Returns:
tuple[Any, ...] | None— tuple[Any, ...] | None: The allowed members for a constrained scalartuple[Any, ...] | None— (Literalargs orEnummember values), or None when unconstrained.
flatten_to_message_pieces¶
flatten_to_message_pieces(messages: Sequence[Message]) → MutableSequence[MessagePiece]Flatten messages into a single list of message pieces.
| Parameter | Type | Description |
|---|---|---|
messages | Sequence[Message] | Messages to flatten. |
Returns:
MutableSequence[MessagePiece]— MutableSequence[MessagePiece]: Flattened message pieces.
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:
dict[str, HarmDefinition]— dict[str, HarmDefinition]: A dictionary mapping category names to their HarmDefinition objects. The keys are the category names from the YAML files (e.g., “violence”, “hate_speech”).
Raises:
ValueError— If any YAML file in the directory is invalid.
get_all_values¶
get_all_values(messages: Sequence[Message]) → list[str]Return all converted values across the provided messages.
| Parameter | Type | Description |
|---|---|---|
messages | Sequence[Message] | Messages to aggregate. |
Returns:
list[str]— list[str]: Flattened list of converted values.
get_common_json_schema¶
get_common_json_schema(name: str) → JsonSchemaDefinitionReturn 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.
| Parameter | Type | Description |
|---|---|---|
name | str | Registry key of the desired schema. |
Returns:
JsonSchemaDefinition— A new dict containing the schema body.
Raises:
KeyError— Ifnameis not registered inCOMMON_JSON_SCHEMAS.
get_lazy_dir¶
get_lazy_dir(module_globals: dict[str, Any], exports: Mapping[str, LazyExport]) → list[str]Return package attributes and unresolved public exports.
| Parameter | Type | Description |
|---|---|---|
module_globals | dict[str, Any] | The package globals. |
exports | Mapping[str, LazyExport] | Public names and their implementation locations. |
Returns:
list[str]— list[str]: Sorted package attribute names.
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!")
... ])
... ]| Parameter | Type | Description |
|---|---|---|
message_pieces | Sequence[MessagePiece] | A list of MessagePiece objects representing individual message pieces. |
Returns:
MutableSequence[Message]— MutableSequence[Message]: A list of Message objects representing grouped message pieces. This is ordered by the sequence number.
Raises:
ValueError— If the conversation ID of any message piece does not match the conversation ID of the first message piece.
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
>>> # ]| Parameter | Type | Description |
|---|---|---|
message_pieces | Sequence[MessagePiece] | A list of MessagePiece objects from potentially different conversations. |
Returns:
list[list[Message]]— list[list[Message]]: A list of conversations, where each conversation is a list of Message objects grouped by sequence.
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.
| Parameter | Type | Description |
|---|---|---|
seeds | Sequence[Seed] | The flat seeds to group. |
Returns:
list[AttackSeedGroup]— list[AttackSeedGroup]: One attack group perprompt_group_id(and one per ungrouped seed), each self-validated on construction.
Raises:
ValueError— If any resulting group does not satisfyAttackSeedGroup’s invariants (e.g. it has no objective or more than one).
is_finding_path_complete¶
is_finding_path_complete(path: DecompositionPath, demonstrated: Mapping[UUID, bool]) → boolWhether every step of a finding’s path was demonstrated. Completeness is derived, never stored.
| Parameter | Type | Description |
|---|---|---|
path | DecompositionPath | A path of direct sub-findings. |
demonstrated | Mapping[UUID, bool] | Each known sub-finding’s demonstrated flag. Unknown steps count as not demonstrated. |
Returns:
bool— True if each step is a demonstrated sub-finding.
load_next_message_prompt¶
load_next_message_prompt(template_path: str | Path) → SeedPromptLoad a next-message system prompt template and verify it declares the parameters it needs.
| Parameter | Type | Description |
|---|---|---|
template_path | str | Path | Path to the YAML file containing the prompt template. |
Returns:
SeedPrompt— The loaded template.
Raises:
ValueError— If the template does not declareobjectiveandconversation_context.
Examples:
load_simulated_target_prompt¶
load_simulated_target_prompt(template_path: str | Path) → SeedPromptLoad a simulated target system prompt template and verify it declares the parameters it needs.
| Parameter | Type | Description |
|---|---|---|
template_path | str | Path | Path to the YAML file containing the prompt template. |
Returns:
SeedPrompt— The loaded template.
Raises:
ValueError— If the template does not declareobjectiveandnum_turns.
project_behavioral_identity¶
project_behavioral_identity(identifier: ComponentIdentifier, identifier_type: type[ComponentIdentifier]) → ComponentIdentifierReturn 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.
| Parameter | Type | Description |
|---|---|---|
identifier | ComponentIdentifier | The full component identifier to project. |
identifier_type | type[ComponentIdentifier] | The typed identifier schema for the root component. |
Returns:
ComponentIdentifier— A tree containing only behavior-defining details.
read_usage_int¶
read_usage_int(source: Any, name: str) → int | NoneRead 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.
| Parameter | Type | Description |
|---|---|---|
source | Any | The usage object or nested details object (may be None). |
name | str | The field name to read. |
Returns:
int | None— int | None: The integer value, or None when absent or not an integer.
read_usage_value¶
read_usage_value(source: Any, name: str) → AnyRead 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.
| Parameter | Type | Description |
|---|---|---|
source | Any | The usage object or nested details object (may be None). |
name | str | The field name to read. |
Returns:
Any— The field value, or None when absent.
register_common_json_schema¶
register_common_json_schema(name: str, schema: JsonSchemaDefinition, overwrite: bool = False) → NoneRegister 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.
| Parameter | Type | Description |
|---|---|---|
name | str | Stable registry key. Use snake_case. |
schema | JsonSchemaDefinition | The schema body to register. |
overwrite | bool | If False (default), raises ValueError when name is already registered. Set True to intentionally replace an existing entry. |
Raises:
TypeError— Ifschemais not adict.ValueError— Ifnameis already registered andoverwriteis False.
resolve_lazy_export¶
resolve_lazy_export(name: str, module_name: str, module_globals: dict[str, Any], exports: Mapping[str, LazyExport]) → AnyResolve and cache one package export.
| Parameter | Type | Description |
|---|---|---|
name | str | Public attribute requested from the package. |
module_name | str | Package name used in an AttributeError. |
module_globals | dict[str, Any] | Package globals where the resolved value is cached. |
exports | Mapping[str, LazyExport] | Public names and their implementation locations. |
Returns:
Any— The resolved public value.
Raises:
AttributeError— Ifnameis not a declared lazy export.
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 | NoneChoose 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.
| Parameter | Type | Description |
|---|---|---|
prompt | SeedPrompt | None | The canonical prompt, if the caller supplied one. |
path | str | Path | None | The deprecated path input, if the caller supplied one. |
prompt_name | str | Name of the canonical parameter, used in messages. |
path_name | str | Name of the deprecated parameter, used in messages. |
load_prompt | Callable[[str | Path], SeedPrompt] | Loader that turns the path into a prompt. |
Returns:
SeedPrompt | None— SeedPrompt | None: The resolved prompt, or None when neither input was supplied.
Raises:
ValueError— If both the canonical prompt and its deprecated path are supplied.
scenario_dataset_size_from_limit¶
scenario_dataset_size_from_limit(limit: ResolvedDatasetLimit) → BoundedDatasetSize | AllAvailableDatasetSizeReturn a finite-source budget from an optional selection limit.
scorable_from_dict¶
scorable_from_dict(value: dict[str, Any]) → ScorableUnionRebuild a stored scorable from its scorable_type tag.
| Parameter | Type | Description |
|---|---|---|
value | dict[str, Any] | A stored model_dump of a scorable. |
Returns:
ScorableUnion— The rebuilt scorable.
Raises:
ValidationError— If the stored value names no known scorable.
scoring_expectation_fingerprint¶
scoring_expectation_fingerprint(exp: ScoringExpectation) → strReturn 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.
| Parameter | Type | Description |
|---|---|---|
exp | ScoringExpectation | The expectation to fingerprint. |
Returns:
str— The lowercase SHA-256 hex digest.
snake_case_to_class_name¶
snake_case_to_class_name(snake_case_name: str, suffix: str = '') → strConvert a snake_case name to a PascalCase class name.
| Parameter | Type | Description |
|---|---|---|
snake_case_name | str | The snake_case name to convert (e.g., “my_custom”). |
suffix | str | Optional suffix to append to the class name (e.g., “Scenario” would convert “my_custom” to “MyCustomScenario”). Defaults to ''. |
Returns:
str— The PascalCase class name (e.g., “MyCustomScenario”).
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.
| Parameter | Type | Description |
|---|---|---|
message_pieces | list[MessagePiece] | The pieces to sort. Not mutated. |
Returns:
list[MessagePiece]— A new list containing the same pieces in deterministic order.
unregister_common_json_schema¶
unregister_common_json_schema(name: str) → NoneRemove 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.
| Parameter | Type | Description |
|---|---|---|
name | str | Registry key to remove. |
Raises:
KeyError— Ifnameis not currently registered.
validate_own_decomposition¶
validate_own_decomposition(node_id: UUID | None, parent_id: UUID | None, paths: tuple[DecompositionPath, ...]) → NoneCheck the relationship fields one node can validate without its relatives.
| Parameter | Type | Description |
|---|---|---|
node_id | UUID | None | The node’s ID. |
parent_id | UUID | None | The node’s parent, if any. |
paths | tuple[DecompositionPath, ...] | The node’s paths. |
Raises:
ValueError— If the node has relationships but no ID, is its own parent, is a step of its own path, or repeats a path ID.
validate_registry_name¶
validate_registry_name(name: str) → NoneValidate that name is a legal registry name.
| Parameter | Type | Description |
|---|---|---|
name | str | The name to validate. |
Raises:
ValueError— If name does not match the required pattern.
warn_prompt_path_deprecated¶
warn_prompt_path_deprecated(prompt: SeedPrompt | None, prompt_name: str, path_name: str) → NoneReject 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.
| Parameter | Type | Description |
|---|---|---|
prompt | SeedPrompt | None | The canonical prompt, if the caller supplied one alongside the path. |
prompt_name | str | Name of the canonical parameter, used in messages. |
path_name | str | Name of the deprecated parameter, used in messages. |
Raises:
ValueError— If both the canonical prompt and its deprecated path are supplied.
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 | NoneRead the association without changing seed metadata.
| Parameter | Type | Description |
|---|---|---|
metadata | Mapping[str, Any] | None | Seed metadata that may hold the association. |
Returns:
Self | None— Self | None: The saved prompts as the calling class, or None when no association exists.
to_metadata¶
to_metadata() → dict[str, Any]Serialize the group association on its objective seed.
Returns:
dict[str, Any]— dict[str, Any]: Canonical prompt data, with no load-time template rendering.
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 = '') → AssertGenerationConfigBuild a generation request for this behavior.
| Parameter | Type | Description |
|---|---|---|
group_count | int | The number of seed groups to generate. |
context | str | The application the generated groups test. Defaults to none. |
Returns:
AssertGenerationConfig— A request with this behavior’s name and description.
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() → _ScoreMetadataReturn the score metadata keys for this data.
Returns:
_ScoreMetadata— dict[str, str | int | float]: The keys that are set.
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]]) → SelfMeasure actual assignments, including the behavior axis.
Returns:
Self— Actual level and pair coverage.
Raises:
ValueError— If an assignment contains unknown dimensions or levels.
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() → _ScoreMetadataReturn the score metadata keys for this data.
Returns:
_ScoreMetadata— dict[str, str | int | float]: The keys that are set.
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]) → SelfReplace 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.
| Parameter | Type | Description |
|---|---|---|
taxonomy | AssertTaxonomy | The reviewed taxonomy. Its behavior name can’t change. |
dimensions | Sequence[AssertDimension] | The reviewed dimensions, each with explicit levels. |
Returns:
Self— A checkpoint ready to generate seed groups from the reviewed policy.
Raises:
ValueError— If the policy isn’t generated yet, seed groups already exist, or the review is invalid.
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) → SelfValidate a group’s retained ASSERT generation context.
Returns:
Self— The validated group metadata.
Raises:
ValueError— If the seed has no ASSERT metadata.
to_metadata¶
to_metadata() → dict[str, Any]Serialize this value for seed metadata.
Returns:
dict[str, Any]— The canonical metadata mapping containing this value.
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 | NoneFind a verdict’s position among the dimension’s grades, matching its type exactly.
| Parameter | Type | Description |
|---|---|---|
value | object | A boolean verdict, or a declared grade. |
Returns:
int | None— int | None: The position, or None if the value is not one of the grades.
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) → AssertJudgePresetLoad a preset from an ASSERT-style judge_preset YAML file.
| Parameter | Type | Description |
|---|---|---|
path | str | Path | The preset file. |
Returns:
AssertJudgePreset— The validated preset.
Raises:
ValueError— If the file is not a YAML mapping or is not a valid judge preset.
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() → _ScoreMetadataReturn the score metadata keys for this data.
Returns:
_ScoreMetadata— dict[str, str | int | float]: The keys that are set.
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.
| Parameter | Type | Description |
|---|---|---|
behaviors | Mapping[str, AssertBehaviorPreset] | Behavior presets by name, such as list_assert_behavior_presets(). |
group_count | int | The number of seed groups to generate for each behavior. |
Returns:
list[AssertGenerationConfig]— list[AssertGenerationConfig]: Requests in the suite’s behavior order.
Raises:
ValueError— If a suite behavior is not inbehaviors.
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.
| Parameter | Type | Description |
|---|---|---|
dimensions | tuple[AssertDimension, ...] | Resolved coverage dimensions. |
Returns:
dict[str, list[str]]— dict[str, list[str]]: Level names, with the taxonomy’s behavior axis first.
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) → SelfBuild 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.
| Parameter | Type | Description |
|---|---|---|
technique_identifier | ComponentIdentifier | None | Pre-built technique identifier from AttackTechnique.get_identifier(). Mutually exclusive with attack_identifier. Defaults to None. |
attack_identifier | ComponentIdentifier | None | Raw attack strategy identifier. Used when no AttackTechnique instance is available. Mutually exclusive with technique_identifier. Defaults to None. |
seed_group | SeedGroup | None | The seed group to extract all seeds from. Defaults to None. |
simulated_conversation_adversarial_chat_eval_hash | str | None | Behavioral 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:
Self— A composite AtomicAttackIdentifier with class_name=“AtomicAttack”.
Raises:
ValueError— If both or neither oftechnique_identifierandattack_identifierare provided.
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() → NoneCheck 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:
ValueError— If a count is invalid or a derived value contradicts its counts.
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:
set[str]— set[str]: Main + pruned conversation IDs.
get_all_conversation_ids¶
get_all_conversation_ids() → set[str]Return the main conversation ID plus all related conversation IDs.
Returns:
set[str]— set[str]: All conversation IDs associated with this attack.
get_attack_strategy_identifier¶
get_attack_strategy_identifier() → ComponentIdentifier | NoneReturn 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:
ComponentIdentifier | None— ComponentIdentifier | None: The attack strategy identifier, orNoneifatomic_attack_identifieris not set or the expected children are missing.
get_conversations_by_type¶
get_conversations_by_type(conversation_type: ConversationType) → list[ConversationReference]Return all related conversations of the requested type.
| Parameter | Type | Description |
|---|---|---|
conversation_type | ConversationType | The type of conversation to filter by. |
Returns:
list[ConversationReference]— A list of related conversations matching the specified type.
get_pruned_conversation_ids¶
get_pruned_conversation_ids() → list[str]Return IDs of pruned (branched) conversations only.
Returns:
list[str]— list[str]: Pruned conversation IDs.
get_scoring_failure¶
get_scoring_failure(conversation_id: str) → ScoringFailure | NoneRead a conversation’s scoring error for the current objective.
Returns:
ScoringFailure | None— The retained diagnostics, or None when the conversation has no current failure.
includes_conversation¶
includes_conversation(conversation_id: str) → boolCheck whether a conversation belongs to this attack (main or any related).
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation ID to check. |
Returns:
bool— True if the conversation is part of this attack.
AttackResultMetadata¶
Producer-recorded role and immediate-parent position stored in AttackResult.attribution_data.
Methods:
from_metadata¶
from_metadata(metadata: dict[str, Any] | None) → SelfRead semantic metadata without inferring a role from conversations or parent linkage.
| Parameter | Type | Description |
|---|---|---|
metadata | dict[str, Any] | None | Stored attribution data, including legacy records. |
Returns:
Self— Unknown for unrecognized roles and None for absent or invalid child positions.
to_metadata¶
to_metadata() → dict[str, Any]Serialize the semantic metadata fragment without parent linkage.
Returns:
dict[str, Any]— dict[str, Any]: The role and optional child position using the existing storage keys.
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:
Requires exactly one SeedObjective (not optional like in SeedGroup)
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.
| Parameter | Type | Description |
|---|---|---|
seed_groups | Sequence[AttackSeedGroup] | Candidate seed groups. |
technique | AttackTechniqueSeedGroup | The technique to check compatibility against. |
Returns:
list[AttackSeedGroup]— The compatible subset of seed_groups.
is_compatible_with_technique¶
is_compatible_with_technique(technique: AttackTechniqueSeedGroup) → boolCheck 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.
| Parameter | Type | Description |
|---|---|---|
technique | AttackTechniqueSeedGroup | The technique group to check compatibility with. |
Returns:
bool— True if the merge would succeed, False if it would cause abool— sequence overlap.
with_technique¶
with_technique(technique: AttackTechniqueSeedGroup) → AttackSeedGroupReturn 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.
| Parameter | Type | Description |
|---|---|---|
technique | AttackTechniqueSeedGroup | A validated AttackTechniqueSeedGroup whose seeds will be merged. |
Returns:
AttackSeedGroup— A new AttackSeedGroup with the merged seeds.
Raises:
ValueError— If the technique contains a SeedSimulatedConversation whose sequence range overlaps with existing prompt sequences.ValueError— If preserving prompt placement combines conflicting roles at the same sequence.
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:
Requires all seeds to have is_general_technique=True
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') → SelfBuild a technique group from conversation messages.
This supports techniques that generate reusable teaching or priming messages programmatically before a generic attack sends each objective.
| Parameter | Type | Description |
|---|---|---|
messages | list[Message] | Conversation messages to convert into technique seeds. |
starting_sequence | int | Sequence 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_index | int | None | Where to insert the technique when merging into a AttackSeedGroup. Defaults to None. |
prompt_placement | Literal['preserve', 'prepend'] | How to place prompts when merging into a AttackSeedGroup. Defaults to "prepend". |
Returns:
Self— A group containing general-technique prompts.
from_system_prompt¶
from_system_prompt(system_prompt: str, insertion_index: int | None = None) → SelfBuild 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.
| Parameter | Type | Description |
|---|---|---|
system_prompt | str | The system-role instruction text. |
insertion_index | int | None | Where to insert the seed when merging into a AttackSeedGroup. None (default) appends at the end. |
Returns:
Self— A group with a single general-technique system seed.
with_simulation_changes¶
with_simulation_changes(changes: SimulationChanges) → SelfRebuild simulation settings and a fixed final turn without changing the source group.
Returns:
Self— An independent, validated technique seed group.
Raises:
ValueError— If an edit changes the existing final-message mode or overlaps other seeds.
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:
A simple string for single-part text messages
A list of dicts for multipart messages (e.g., text + images)
Methods:
to_dict¶
to_dict() → dict[str, Any]Convert the ChatMessage to a dictionary.
Returns:
dict[str, Any]— A dictionary representation of the message, excluding None values.
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:
exclude— ifTrue, drop this child entirely from the hash.included_params— if set, only include these param keys for this child (and its recursive descendants).Nonemeans all params.included_item_values— for list-valued children, only include items whoseparamsmatch all specified key-value pairs.Nonemeans include all items.param_fallbacks— maps a primary param key to a fallback key. When the primary key’s value is falsy (empty string,None, or missing), the fallback key’s value from the component’s raw params is used instead. This keeps fallback logic in the eval layer without changing full component hashes.Nonemeans no fallbacks.inner_child_name— if set, names the sub-child to “look through” when the child being processed is a wrapper component (e.g.,RoundRobinTarget). The first item of that sub-child list is substituted before applying param filtering, so the eval hash matches the unwrapped inner target.Nonemeans no unwrapping.unordered_when— names a boolean param on the parent identifier. Only an explicitTruesorts this slot’s projected child hashes. Duplicates are retained, and the original child list is not changed.
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) → SelfReturn 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.
| Parameter | Type | Description |
|---|---|---|
identifier | ComponentIdentifier | A ComponentIdentifier (possibly the base type). |
Returns:
Self— An instance ofclsdescribing the same identity.
get_child¶
get_child(key: str) → ComponentIdentifier | NoneGet a single child by key.
| Parameter | Type | Description |
|---|---|---|
key | str | Child name. |
Returns:
ComponentIdentifier | None— The child identifier, orNoneif not present.
Raises:
ValueError— If the child atkeyis a list. Useget_child_listfor list-valued children.
get_child_list¶
get_child_list(key: str) → list[ComponentIdentifier]Get a list of children by key. Wraps singletons; [] if missing.
| Parameter | Type | Description |
|---|---|---|
key | str | Child name. |
Returns:
list[ComponentIdentifier]— A list of child identifiers.
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.
| Parameter | Type | Description |
|---|---|---|
target_cls | type | The component class to read class attributes from. |
Returns:
dict[str, Any]— dict[str, Any]: Field-name → class-attribute value, for eachdict[str, Any]—Param.ClassAttrfield. Missing attributes map toNone.
get_identity_conflicting_parameter_names¶
get_identity_conflicting_parameter_names() → frozenset[str]Get constructor parameter names that override identity-based authentication.
Returns:
frozenset[str]— frozenset[str]: Identity-conflicting constructor parameter names.
get_multiline_parameter_names¶
get_multiline_parameter_names() → frozenset[str]Get constructor parameter names whose values require multiline controls.
Returns:
frozenset[str]— frozenset[str]: Multiline constructor parameter names.
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:
dict[str, ComponentType]— dict[str, ComponentType]: Constructor-arg-name → referenced component type.
get_sensitive_parameter_names¶
get_sensitive_parameter_names() → frozenset[str]Get constructor parameter names whose values must be obscured in user interfaces.
Returns:
frozenset[str]— frozenset[str]: Sensitive constructor parameter names.
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 = {}) → SelfBuild 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.
| Parameter | Type | Description |
|---|---|---|
obj | object | The live object whose class metadata will populate the identifier. |
params | dict[str, Any] | None | Optional behavioral params. Defaults to None. |
children | Mapping[str, ComponentIdentifier | list[ComponentIdentifier] | None] | None | Optional child identifiers; None-valued entries are omitted. Defaults to None. |
attributes | dict[str, Any] | None | Optional identity-bearing state (hashed, but excluded from the eval hash and not a constructor input). None values dropped. Defaults to None. |
**promoted | Any | Optional promoted typed fields (for subclasses). Passed by name; None values are dropped. These are mirrored back into params / children automatically. Defaults to {}. |
Returns:
Self— A new ComponentIdentifier describingobj.
promoted_child_field_names¶
promoted_child_field_names() → tuple[str, ...]Get names of this identifier’s promoted child fields.
Returns:
tuple[str, ...]— tuple[str, ...]: Promoted child field names.
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:
tuple[str, ...]— tuple[str, ...]: Promoted scalar field names.
promoted_scalar_values¶
promoted_scalar_values() → dict[str, Any]Get this identifier’s promoted scalar fields as {name: value} (children/targets excluded).
Returns:
dict[str, Any]— dict[str, Any]: Promoted scalar field names and values.
with_eval_hash¶
with_eval_hash(eval_hash: str) → ComponentIdentifierReturn 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.
| Parameter | Type | Description |
|---|---|---|
eval_hash | str | The evaluation hash to attach. |
Returns:
ComponentIdentifier— A new ComponentIdentifier identical to this one but withComponentIdentifier—eval_hashset to the given value.
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) → SelfValidate a condition, dispatching the registry root to its concrete subtype.
| Parameter | Type | Description |
|---|---|---|
obj | Any | The condition instance or discriminator-tagged representation. |
strict | bool | None | Whether Pydantic uses strict validation. Defaults to None. |
extra | ExtraValues | None | How Pydantic handles extra fields. Defaults to None. |
from_attributes | bool | None | Whether Pydantic reads object attributes. Defaults to None. |
context | Any | None | Context supplied to Pydantic validators. Defaults to None. |
by_alias | bool | None | Whether Pydantic accepts field aliases. Defaults to None. |
by_name | bool | None | Whether Pydantic accepts field names. Defaults to None. |
Returns:
Self— The validated concrete condition.
Raises:
ValueError— If the abstract root receives an invalid or unknown discriminator.
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) → SelfDescribe 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.
| Parameter | Type | Description |
|---|---|---|
message | Message | The ephemeral message whose converted content to take. |
Returns:
Self— A scorable holding the converted message content.
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() → SelfRequire a numeric value only for the value state.
Returns:
Self— Validated control metadata.
Raises:
ValueError— If the state and value disagree.
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:
| Parameter | Type | Description |
|---|---|---|
nodes | Iterable[DecompositionNode] | Every node of each tree. |
Methods:
get_children¶
get_children(node_id: UUID) → tuple[UUID, ...]Get a node’s direct children.
| Parameter | Type | Description |
|---|---|---|
node_id | UUID | The parent’s ID. |
Returns:
tuple[UUID, ...]— tuple[UUID, ...]: The children’s IDs, in the order supplied.
Raises:
ValueError— If the node is not in the tree.
get_node¶
get_node(node_id: UUID) → DecompositionNodeGet a node by ID.
| Parameter | Type | Description |
|---|---|---|
node_id | UUID | The node’s ID. |
Returns:
DecompositionNode— The node.
Raises:
ValueError— If the node is not in the tree.
get_subtree¶
get_subtree(root_id: UUID) → tuple[UUID, ...]Get a node and all of its descendants.
| Parameter | Type | Description |
|---|---|---|
root_id | UUID | The node to start from. |
Returns:
tuple[UUID, ...]— tuple[UUID, ...]: The IDs, depth-first with parents before children.
Raises:
ValueError— If the root is not in the tree.
walk¶
walk(root_id: UUID) → Iterator[tuple[UUID, int]]Visit a node and its descendants depth-first, parents before children.
| Parameter | Type | Description |
|---|---|---|
root_id | UUID | The node to start from. |
Raises:
ValueError— If the root is not in the tree.
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) → EmbeddingResponseLoad the embedding response from disk.
| Parameter | Type | Description |
|---|---|---|
file_path | Path | The path to load the file from. |
Returns:
EmbeddingResponse— The loaded embedding response.
save_to_file¶
save_to_file(directory_path: Path) → strSave the embedding response to disk and return the path of the new file.
| Parameter | Type | Description |
|---|---|---|
directory_path | Path | The path to save the file to. |
Returns:
str— The full path to the file that was saved.
EmbeddingSupport¶
Bases: ABC
Protocol-like interface for classes that generate text embeddings.
Methods:
generate_text_embedding¶
generate_text_embedding(text: str, kwargs: object = {}) → EmbeddingResponseGenerate text embedding synchronously.
| Parameter | Type | Description |
|---|---|---|
text | str | The text to generate the embedding for |
**kwargs | object | Additional arguments to pass to the function. Defaults to {}. |
Returns:
EmbeddingResponse— The embedding response
generate_text_embedding_async¶
generate_text_embedding_async(text: str, kwargs: object = {}) → EmbeddingResponseGenerate text embedding asynchronously.
| Parameter | Type | Description |
|---|---|---|
text | str | The text to generate the embedding for |
**kwargs | object | Additional arguments to pass to the function. Defaults to {}. |
Returns:
EmbeddingResponse— The embedding response
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:
| Parameter | Type | Description |
|---|---|---|
key | str | The stored name of the value. Keep it fixed; change label to rename what users see. |
label | str | The name the finding dialog and cards show. |
type | FindingFieldType | text, multiline, choice or number. A number takes a plain decimal, such as 9.8 or -2. |
required | bool | Whether every finding needs a value. For a cascade, every level with options needs one. |
options | list[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. |
levels | list[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. |
default | str | None | A top-level option the finding dialog preselects for new findings. |
allow_other | bool | Whether a single-level choice field also accepts typed text. |
colors | dict[str, FindingSeverityColor] | The severity slot’s badge color for each top-level option. |
hint | str | None | Help text under the field in the finding dialog. |
section | str | None | A 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:
| Parameter | Type | Description |
|---|---|---|
severity | FindingField | The required severity choice. List its options from highest to lowest; findings sort in that order. |
fields | list[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] = ()) → FindingCreateBuild 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.
| Parameter | Type | Description |
|---|---|---|
stored | FindingCreate | The finding as saved. |
edit | FindingCreate | The edited finding, with its current field values. |
keep_retired_keys | Collection[str] | Keys of the stored values the editor showed as retired. Defaults to none. |
remove_retired_keys | Collection[str] | Keys of the stored retired values to delete. Defaults to none. |
Returns:
FindingCreate— The finding to save.
Raises:
FindingValuesError— Ifremove_retired_keyslists a key that isn’t a retired value of the stored finding or that the edit also sends, or the edited values do not fit these fields.
check_values¶
check_values(severity: str, field_values: dict[str, str], previous_severity: str | None = None, previous_values: dict[str, str] | None = None) → NoneCheck 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.
| Parameter | Type | Description |
|---|---|---|
severity | str | The severity slot’s value. |
field_values | dict[str, str] | The values of the other fields and of every level, by key. |
previous_severity | str | None | The stored finding’s severity, or None for a new finding. Defaults to None. |
previous_values | dict[str, str] | None | The stored finding’s field values, or None for a new finding. Defaults to None. |
Raises:
FindingValuesError— For the first unknown key, changed value of a field that is no longer configured, missing required value, value that is not an option, Other text that matches an option, or changednumbervalue that is not a plain decimal.
describe_values¶
describe_values(severity: str, field_values: dict[str, str]) → FindingValueDescriptionLabel 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.
| Parameter | Type | Description |
|---|---|---|
severity | str | The severity slot’s value. |
field_values | dict[str, str] | The values of the other fields and of every level, by key. |
Returns:
FindingValueDescription— The severity’s label, one row per filled value, and the(key, value)of each stored value that no field or level uses, in stored order.
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:
| Parameter | Type | Description |
|---|---|---|
value | float | A finite number in [0, 1]. |
Methods:
from_metadata¶
from_metadata(metadata: Mapping[str, str | int | float] | None) → FloatFeedback | NoneRead usable feedback from metadata, treating legacy or invalid values as unset.
Returns:
FloatFeedback | None— FloatFeedback | None: The recorded value, or None when absent or unusable.
read¶
read(score: Score | None) → FloatFeedback | NoneRead the float value a score kept, treating missing or unusable data as unset.
| Parameter | Type | Description |
|---|---|---|
score | Score | None | The score to read. |
Returns:
FloatFeedback | None— FloatFeedback | None: The value, or None when the score has no usable one.
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.
| Parameter | Type | Description |
|---|---|---|
metadata | Mapping[str, str | int | float] | None | The metadata to copy. |
Returns:
dict[str, str | int | float]— dict[str, str | int | float]: The copy, without the feedback key.
require¶
require(score: Score) → FloatFeedbackRead the float value a score promised to keep.
| Parameter | Type | Description |
|---|---|---|
score | Score | A complete true/false score from a scorer that guarantees the value. |
Returns:
FloatFeedback— The value.
Raises:
InvalidFloatFeedbackError— If the value is missing or is not a finite number in[0, 1].
to_metadata¶
to_metadata() → dict[str, float]Return the metadata fragment carrying this value.
Returns:
dict[str, float]— dict[str, float]: The feedback metadata.
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.
| Parameter | Type | Description |
|---|---|---|
metadata | Mapping[str, str | int | float] | None | The metadata to copy. |
Returns:
dict[str, str | int | float]— dict[str, str | int | float]: The copy, with the value under the feedback key.
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 | NoneRead a supplied prefix without interpreting other seed metadata.
Returns:
GCGSeedMetadata | None— GCGSeedMetadata | None: The stored payload, or None if absent.
Raises:
ValueError— If stored GCG metadata is malformed.
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:
| Parameter | Type | Description |
|---|---|---|
version | str | The version of the harm definition (e.g., “1.0”). |
category | str | The harm category name (e.g., “violence”, “hate_speech”). |
scale_descriptions | list[ScaleDescription] | List of scale descriptions defining score levels. |
source_path | str | None | The path to the YAML file this was loaded from. |
Methods:
from_yaml¶
from_yaml(harm_definition_path: str | Path) → SelfLoad 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.
| Parameter | Type | Description |
|---|---|---|
harm_definition_path | str | Path | Path 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:
Self— The loaded harm definition, as an instance of the class it was called on.
Raises:
FileNotFoundError— If the harm definition file does not exist.ValueError— If the YAML file is invalid or missing required fields.
get_scale_description¶
get_scale_description(score_value: str) → str | NoneGet the description for a specific score value.
| Parameter | Type | Description |
|---|---|---|
score_value | str | The score value to look up (e.g., “1”, “2”). |
Returns:
str | None— The description for the score value, or None if not found.
validate_category¶
validate_category(category: str, check_exists: bool = False) → boolValidate 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.
| Parameter | Type | Description |
|---|---|---|
category | str | The category name to validate. |
check_exists | bool | If True, also verify the category exists in get_all_harm_definitions(). Defaults to False. |
Returns:
bool— True if the category is valid (and exists if check_exists is True),bool— False otherwise.
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() → ComponentIdentifierGet 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:
ComponentIdentifier— The frozen identity snapshot representing this component’s behavioral configuration.
IdentifierFilter¶
Bases: BaseModel
Immutable filter definition for matching JSON-backed identifier properties.
Attributes:
| Parameter | Type | Description |
|---|---|---|
identifier_type | IdentifierType | The type of identifier column to filter on. |
property_path | str | The JSON path for the property to match. |
array_element_path | An 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. | |
value | str | None | The string value that must match the extracted JSON property value. |
value_pattern | str | None | An explicit case-insensitive full LIKE pattern, instead of value. ‘%’ and ‘_’ are wildcards, ‘/’ escapes the next character; brackets and ‘*’ are literal. |
partial_match | bool | Whether value is a case-insensitive literal substring. Cannot be used with array_element_path, case_sensitive or value_pattern. |
case_sensitive | bool | Whether 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://
Examples:
Methods:
from_metadata¶
from_metadata(metadata: dict[str, Any] | None) → SelfReconstruct 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.
| Parameter | Type | Description |
|---|---|---|
metadata | dict[str, Any] | None | The prompt metadata to read. |
Returns:
Self— The reconstructed config (enabled=Falsewhen none requested).
Raises:
ValueError— If a schema string is present but is not valid JSON.
parse_schema¶
parse_schema(schema_val: dict[str, Any] | str) → dict[str, Any] | NoneRead a schema stored under JSON_SCHEMA_METADATA_KEY, which may be a dict or a JSON string.
| Parameter | Type | Description |
|---|---|---|
schema_val | dict[str, Any] | str | The stored schema. An empty string means no schema. |
Returns:
dict[str, Any] | None— dict[str, Any] | None: The parsed schema, orNonefor an empty string.
Raises:
ValueError— If a schema string is not valid JSON.
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:
dict[str, Any]— dict[str, Any]: The metadata fragment to attach to a piece.
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() → MessageCreate 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:
Message— A new Message with deep-copied message pieces, new IDs, and fresh timestamp.
from_prompt¶
from_prompt(prompt: str, role: ChatMessageRole, prompt_metadata: dict[str, str | int] | None = None) → SelfBuild a single-piece message from prompt text.
| Parameter | Type | Description |
|---|---|---|
prompt | str | Prompt text. |
role | ChatMessageRole | Role assigned to the message piece. |
prompt_metadata | dict[str, str | int] | None | Optional prompt metadata. Defaults to None. |
Returns:
Self— Constructed message instance.
from_system_prompt¶
from_system_prompt(system_prompt: str) → SelfBuild a message from a system prompt.
| Parameter | Type | Description |
|---|---|---|
system_prompt | str | System instruction text. |
Returns:
Self— Constructed system-role message.
from_system_prompts¶
from_system_prompts(system_prompts: str = ()) → list[Self]Build a list of system-role messages, ready to pass as prepended_conversation.
| Parameter | Type | Description |
|---|---|---|
*system_prompts | str | System instruction texts. When omitted, returns an empty list. Defaults to (). |
Returns:
list[Self]— list[Self]: One system-role message per input, in order.
get_piece¶
get_piece(n: int = 0) → MessagePieceReturn the nth message piece.
| Parameter | Type | Description |
|---|---|---|
n | int | Zero-based index of the piece to return. Defaults to 0. |
Returns:
MessagePiece— Selected message piece.
Raises:
ValueError— If the message has no pieces.IndexError— If the index is out of bounds.
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 | NoneReturn the first message piece matching the given data type, or None.
| Parameter | Type | Description |
|---|---|---|
data_type | PromptDataType | None | Alias for converted_value_data_type (for convenience). Defaults to None. |
original_value_data_type | PromptDataType | None | The original_value_data_type to filter by. Defaults to None. |
converted_value_data_type | PromptDataType | None | The converted_value_data_type to filter by. Defaults to None. |
Returns:
MessagePiece | None— The first matching MessagePiece, or None if no match is found.
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.
| Parameter | Type | Description |
|---|---|---|
data_type | PromptDataType | None | Alias for converted_value_data_type (for convenience). Defaults to None. |
original_value_data_type | PromptDataType | None | The original_value_data_type to filter by. Defaults to None. |
converted_value_data_type | PromptDataType | None | The converted_value_data_type to filter by. Defaults to None. |
Returns:
list[MessagePiece]— A list of matching MessagePiece objects (may be empty).
get_value¶
get_value(n: int = 0) → strReturn the converted value of the nth message piece.
| Parameter | Type | Description |
|---|---|---|
n | int | Zero-based index of the piece to read. Defaults to 0. |
Returns:
str— Converted value of the selected message piece.
Raises:
IndexError— If the index is out of bounds.
get_values¶
get_values() → list[str]Return the converted values of all message pieces.
Returns:
list[str]— list[str]: Converted values for all message pieces.
is_error¶
is_error() → boolCheck whether any message piece indicates an error.
Returns:
bool— True when any piece has a non-none error flag or error data type.
set_response_not_in_memory¶
set_response_not_in_memory() → NoneMark 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() → NoneMark 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() → NoneValidate 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:
ValueError— If piece collection is empty or contains mismatched conversation IDs, sequence numbers, roles, or missing converted values.
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') → SelfBuild 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.
| Parameter | Type | Description |
|---|---|---|
role | ChatMessageRole | The chat role to assign to the piece. Defaults to "user". |
Returns:
Self— A textMessagePieceflagged viaprompt_metadata.
copy_lineage_from¶
copy_lineage_from(source: MessagePiece) → NoneCopy 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.
| Parameter | Type | Description |
|---|---|---|
source | MessagePiece | The piece whose lineage will be copied onto self. |
has_error¶
has_error() → boolReturn True when response_error is not "none".
Returns:
bool—Trueif the piece carries any non-"none"error code.
is_adversarial_placeholder¶
is_adversarial_placeholder() → boolReturn 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:
bool—Trueif this piece should be filled in by an adversarial chat.
is_blocked¶
is_blocked() → boolReturn True when response_error is "blocked".
Returns:
bool—Trueif the response was blocked by the target / content filter.
is_blocked_error¶
is_blocked_error() → boolReturn 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:
bool—Trueif the piece is anerrorpiece withresponse_error == "blocked".
mark_as_structured_refusal¶
mark_as_structured_refusal(refusal: str) → NoneRecord an SDK-provided model refusal on this blocked response piece.
| Parameter | Type | Description |
|---|---|---|
refusal | str | The model’s refusal explanation. |
Raises:
ValueError— If the piece is not a blocked assistant response or the refusal explanation is empty.
mark_as_truncated¶
mark_as_truncated() → NoneRecord 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() → NoneMark injected history without retaining evidence of a previous live send.
to_message¶
to_message() → MessageWrap this piece in a single-piece Message.
Returns:
Message— A newMessagecontaining only this piece.
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) → SelfName the pieces of a persisted message.
| Parameter | Type | Description |
|---|---|---|
message | Message | The message whose pieces to name. |
Returns:
Self— A scorable naming the message’s pieces.
names_same_evidence¶
names_same_evidence(other: Scorable | None) → boolCheck whether other names the same message pieces, in any order.
| Parameter | Type | Description |
|---|---|---|
other | Scorable | None | The scorable to compare. |
Returns:
bool— True when both scorables name the same set of pieces.
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:
dict[str, str]— Storage aliases keyed by data type; other values keep their identity.
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) → NoneValidate supplied canonical evidence without loading or changing it.
Raises:
ValueError— If scored or response evidence is missing, modified, or unsupported.
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) → AnyCoerce 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.
| Parameter | Type | Description |
|---|---|---|
raw_value | Any | The raw value to coerce. |
Returns:
Any— The coerced value (the raw value unchanged for opaque/reference/ arbitrary types, a deep copy for theNonepassthrough, a coerced list for list types, or a coerced scalar for scalar types).
Raises:
ValueError— If the value cannot be coerced to a constrained scalar or list element type.
for_external_catalog¶
for_external_catalog() → ParameterDescribe 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:
Parameter— This parameter, or a copy whoseparam_typeis the external form.
is_allowed_external_input¶
is_allowed_external_input(allowed_path_params: frozenset[str] = frozenset()) → boolReturn 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.
| Parameter | Type | Description |
|---|---|---|
allowed_path_params | frozenset[str] | Path parameters the caller has made safe. Defaults to none. |
Returns:
bool— True for an external input that names no server path, or whose path is allowed.
is_reference_to¶
is_reference_to(component_type: ComponentType) → boolWhether 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.
| Parameter | Type | Description |
|---|---|---|
component_type | ComponentType | The component family to test against. |
Returns:
bool— True when this parameter is a reference tocomponent_type.
project_json_value¶
project_json_value(value: Any) → JsonValueProject a scalar source value without reconstructing opaque or structured state.
Returns:
JsonValue— A lossless JSON-native value for a supported scalar or list.
Raises:
ValueError— If the source requires a structured or Python-only representation.
validate¶
validate() → NoneReject 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:
ValueError— Ifparam_typeis unsupported and no default is declared.
validate_json_value¶
validate_json_value(value: Any) → AnyValidate 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:
Any— The validated value, with constrained scalars converted to their declared members.
Raises:
ValueError— If this parameter requires a Python object or the JSON type is invalid.
validate_value¶
validate_value(value: Any) → NoneCheck a resolved scalar or list without coercing or replacing it.
| Parameter | Type | Description |
|---|---|---|
value | Any | The resolved parameter value. |
Raises:
ValueError— If the value does not match its declared type or choices.
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) → intApproximate a token count from a character count.
| Parameter | Type | Description |
|---|---|---|
characters | int | Characters of text. |
Returns:
int— The approximate number of tokens.
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:
| Parameter | Type | Description |
|---|---|---|
provider | str | The 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_id | str | The provider’s id for the response, such as a completion id. |
Examples:
Methods:
clear_metadata¶
clear_metadata(metadata: dict[str, Any]) → NoneRemove the reference without touching unrelated metadata.
from_metadata¶
from_metadata(metadata: dict[str, Any]) → Self | NoneRead the reference, rejecting malformed stored metadata.
Returns:
Self | None— Self | None: The recorded reference, or None if absent.
Raises:
ValueError— If the stored value is not a valid reference.
to_metadata¶
to_metadata() → dict[str, str]Return the namespaced request metadata.
Returns:
dict[str, str]— dict[str, str]: The reference as compact JSON underMETADATA_KEY.
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() → strGet the text of the correct answer.
Returns:
str— Text corresponding to the configured correct answer index.
Raises:
ValueError— If no choice matches the configured correct answer.
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]) → NoneRemove inherited reasoning before recording a new response.
| Parameter | Type | Description |
|---|---|---|
metadata | dict[str, Any] | The response piece’s metadata to update. |
from_metadata¶
from_metadata(metadata: dict[str, Any]) → Self | NoneRead reasoning, treating absent or legacy unnamespaced values as unset.
| Parameter | Type | Description |
|---|---|---|
metadata | dict[str, Any] | The response piece’s metadata. |
Returns:
Self | None— Self | None: The recorded reasoning, or None when absent.
Raises:
ValueError— If the namespaced reasoning metadata is malformed.
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]) → NoneRemove request options without touching unrelated metadata.
from_message¶
from_message(message: Message) → RequestGenerationConfigRead all current pieces.
Returns:
RequestGenerationConfig— The common non-null value for each selected option.
Raises:
ValueError— The pieces specify conflicting values for an option.
from_metadata¶
from_metadata(metadata: dict[str, Any] | None) → RequestGenerationConfigRead generation options from the canonical metadata envelope.
Returns:
RequestGenerationConfig— Missing or null options mean no override.
Raises:
ValueError— Options are invalid.
to_metadata¶
to_metadata() → dict[str, Any]Serialize only explicitly selected options into the canonical envelope.
Returns:
dict[str, Any]— dict[str, Any]: Metadata fragment, empty for an unset override.
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]) → NoneRemove evidence before a new send or response association.
from_metadata¶
from_metadata(metadata: dict[str, Any] | None) → RequestGenerationInfo | NoneRead framework-authored evidence from the canonical metadata envelope.
Returns:
RequestGenerationInfo | None— RequestGenerationInfo | None: Evidence, or None for unrecorded messages.
Raises:
ValueError— Evidence is malformed.
to_metadata¶
to_metadata() → dict[str, Any]Serialize evidence separately from caller-authored request options.
Returns:
dict[str, Any]— dict[str, Any]: JSON-compatible evidence metadata.
RequestTraceContext¶
Bases: BaseModel
Request metadata linking stored evidence to a W3C trace.
Methods:
from_metadata¶
from_metadata(metadata: dict[str, Any]) → Self | NoneRead the request context, rejecting malformed stored metadata.
Returns:
Self | None— Self | None: The recorded context, or None if absent.
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:
| Parameter | Type | Description |
|---|---|---|
score_value | str | The score value (e.g., “1”, “2”, etc.) |
description | str | The 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() → ComponentIdentifierReturn 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:
ComponentIdentifier— Identity derived from the current field values.
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:
dict[str, list[AttackResult]]— dict[str, list[AttackResult]]: Results grouped by display label.
get_objectives¶
get_objectives(atomic_attack_name: str | None = None) → list[str]Get the list of unique objectives for this scenario.
| Parameter | Type | Description |
|---|---|---|
atomic_attack_name | str | None | Name of specific atomic attack to include. If None, includes objectives from all atomic attacks. Defaults to None. |
Returns:
list[str]— list[str]: Deduplicated list of objectives.
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:
list[str]— list[str]: Technique names that produced results.
normalize_scenario_name¶
normalize_scenario_name(scenario_name: str) → strNormalize 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.
| Parameter | Type | Description |
|---|---|---|
scenario_name | str | The scenario name to normalize. |
Returns:
str— The normalized scenario name suitable for database queries.
objective_achieved_rate¶
objective_achieved_rate(atomic_attack_name: str | None = None) → intGet 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.
| Parameter | Type | Description |
|---|---|---|
atomic_attack_name | str | None | Name of specific atomic attack to calculate rate for. If None, calculates rate across all atomic attacks. Defaults to None. |
Returns:
int— Success rate as a percentage (0-100).
ScenarioRunExecutionToken¶
Bases: BaseModel
The unique identity of one scheduled scenario-run execution.
Methods:
from_metadata¶
from_metadata(metadata: dict[str, Any]) → Self | NoneRead the execution token, or return None when it is absent.
| Parameter | Type | Description |
|---|---|---|
metadata | dict[str, Any] | The scenario-result metadata. |
Returns:
Self | None— Self | None: The token, or None when no token is present.
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() → SelfRequire known component totals to equal their ordered factor product.
Returns:
Self— The validated component.
Raises:
ValueError— If a component with factors has an inconsistent count.
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) → AnyInfer status for callers using the original additive estimate fields.
Returns:
Any— The normalized estimate input.
Raises:
ValueError— If duplicate total fields disagree.
unavailable¶
unavailable(note: str = 'Default-run size estimate is unavailable.', dataset_size: ScenarioDatasetSizeEstimate | None = None, dataset_limit: DatasetLimitInput | None = None) → SelfBuild an unavailable estimate without presenting a guessed total.
Returns:
Self— An unavailable estimate.
validate_estimate¶
validate_estimate() → SelfEnsure status, bounds, and additive components describe one estimate.
Returns:
Self— The validated estimate.
Raises:
ValueError— If the estimate contains contradictory values.
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() → ComponentIdentifierReturn the behavioral identity derived from the current suite definition.
Returns:
ComponentIdentifier— Identity derived from the ordered preset references.
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 | NoneRead suite execution metadata from a scenario result.
Returns:
Self | None— Self | None: The validated envelope, or None for a direct or legacy run.
to_metadata_fields¶
to_metadata_fields() → dict[str, Any]Return the namespaced scenario metadata entry owned by this model.
Returns:
dict[str, Any]— dict[str, Any]: JSON-compatible fields forScenarioResult.metadata.
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) → boolCheck whether other names the same evidence.
| Parameter | Type | Description |
|---|---|---|
other | Scorable | None | The scorable to compare. |
Returns:
bool— True when both scorables identify the same evidence.
Score¶
Bases: BaseModel
Represents a normalized score generated by a scorer component.
Examples:
Methods:
get_value¶
get_value() → bool | floatReturn 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:
bool | float— bool | float: Parsed score value.
Raises:
UndeterminedScoreError— If no verdict was reachable, so there is no value to read.ValueError— If the score type is unknown.
set_value¶
set_value(value: bool | float | None) → NoneSet 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.
| Parameter | Type | Description |
|---|---|---|
value | bool | float | None | The verdict, or None when no verdict was reachable. |
Raises:
TypeError— If the value does not match the score type, or the score type is neither.ValueError— If a float scale value is outside [0, 1].
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:
| Parameter | Type | Description |
|---|---|---|
candidate_index | int | The candidate’s position in the pool. |
candidate_label | str | The scorer class and evaluation key, for display. |
status | ScorerVerdictStatus | Whether the candidate was selected or rejected. |
reason_kind | ScorerMismatchKind | None | For a rejection, the kind of mismatch. |
reason | str | None | For 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:
| Parameter | Type | Description |
|---|---|---|
scorable_types | frozenset[type[Scorable]] | Evidence references the scorer accepts. |
condition_types | frozenset[type[Condition]] | Condition types the scorer tree evaluates. |
supported | frozenset[ScorerCapabilityName] | The output guarantees the scorer makes. |
Methods:
accepts_scorable_type¶
accepts_scorable_type(scorable_type: type[Scorable]) → boolCheck whether the scorer accepts an evidence family.
| Parameter | Type | Description |
|---|---|---|
scorable_type | type[Scorable] | The evidence family the caller will supply. |
Returns:
bool— True when that family, or a parent family it belongs to, is accepted.
includes¶
includes(capability: ScorerCapabilityName) → boolCheck whether the scorer makes an output guarantee.
| Parameter | Type | Description |
|---|---|---|
capability | ScorerCapabilityName | The guarantee to check. |
Returns:
bool— True when the scorer makes it.
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:
| Parameter | Type | Description |
|---|---|---|
atomic_attack_name | str | The planned atomic group. |
display_group | str | The group’s report grouping. |
technique | str | None | The technique that built the group, when known. |
group_kind | ScenarioRunPlanGroupKind | What the group runs. |
required_capabilities | list[ScorerCapabilityName] | Every output guarantee the selection required, sorted. |
required_evaluation | str | None | The evaluation the selection required, if any. |
candidates | list[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:
| Parameter | Type | Description |
|---|---|---|
entries | list[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) → NoneCheck supplied scored evidence against the retained digest.
Raises:
ValueError— If the evidence is missing, modified, or unsupported.
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) → ScoringExpectationValidate an expectation loaded from its durable, versioned representation.
| Parameter | Type | Description |
|---|---|---|
value | Any | The persisted expectation representation. |
Returns:
ScoringExpectation— The validated expectation.
validate_type¶
validate_type(value: object) → NoneCheck a runtime input without parsing or copying it.
| Parameter | Type | Description |
|---|---|---|
value | object | The expectation input. |
Raises:
TypeError— If the input is not aScoringExpectationor None.
Seed¶
Bases: BaseModel, Generic[_SeedDataTypeT]
Represents seed data with various attributes and metadata.
Methods:
bind_template_parameters¶
bind_template_parameters(parameters: Any = {}) → SelfBind literal parameter values for a later template render.
| Parameter | Type | Description |
|---|---|---|
**parameters | Any | Values retained as template data, not template source. Defaults to {}. |
Returns:
Self— A copy with the supplied values bound and remaining parameters unchanged.
escape_for_jinja¶
escape_for_jinja(value: str) → strWrap 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.
| Parameter | Type | Description |
|---|---|---|
value | str | The raw string to escape. |
Returns:
str— The string wrapped in {% raw %}...{% endraw %} tags.
from_yaml_file¶
from_yaml_file(file: str | Path) → SelfCreate 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.
| Parameter | Type | Description |
|---|---|---|
file | str | Path | The input file path. |
Returns:
Self— A new Seed of the specific subclass type.
Raises:
FileNotFoundError— If the path does not resolve to an existing file.ValueError— If the YAML file is invalid or empty.
get_template_parameter_names¶
get_template_parameter_names() → list[str]Get the variable names used by this template.
Returns:
list[str]— list[str]: Sorted template parameter names.
Raises:
ValueError— If the template syntax is invalid.
render_template_value¶
render_template_value(kwargs: Any = {}) → strRender self.value as a template with provided parameters.
| Parameter | Type | Description |
|---|---|---|
kwargs | Any | Key-value pairs to replace in the SeedPrompt value. Defaults to {}. |
Returns:
str— A new prompt with the parameters applied.
Raises:
ValueError— If parameters are missing or invalid in the template.
render_template_value_silent¶
render_template_value_silent(kwargs: Any = {}) → strRender 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.
| Parameter | Type | Description |
|---|---|---|
kwargs | Any | Key-value pairs to replace in the SeedPrompt value. Defaults to {}. |
Returns:
str— A new prompt with the parameters applied.
Raises:
ValueError— If parameters are missing or invalid in the template.
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]) → SelfBuild 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.
| Parameter | Type | Description |
|---|---|---|
data | dict[str, Any] | Dataset payload with top-level defaults and seed entries. |
Returns:
Self— Constructed dataset.
Raises:
ValueError— If any seed entry includes a pre-setprompt_group_id.
from_yaml_file¶
from_yaml_file(file: str | Path, default_dataset_name: str | None = None) → SeedDatasetCreate 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.
| Parameter | Type | Description |
|---|---|---|
file | str | Path | The input file path. |
default_dataset_name | str | None | Dataset name used when the YAML declares neither dataset_name nor name. Defaults to None. |
Returns:
SeedDataset— The loaded dataset.
Raises:
FileNotFoundError— If the path does not resolve to an existing file.ValueError— If the YAML file is invalid or empty.
get_decomposition_tree¶
get_decomposition_tree() → DecompositionTreeBuild the decomposition trees of this dataset’s objectives.
Only objectives with a parent, paths, or children are included.
Returns:
DecompositionTree— The validated trees.
Raises:
ValueError— If a parent is missing from the dataset, the parents form a cycle, or a path step is not a direct child of the path’s owner.
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.
| Parameter | Type | Description |
|---|---|---|
number | int | The number of random prompt values to return. |
harm_categories | Sequence[str] | None | If provided, only prompts containing at least one of these harm categories are included. Defaults to None. |
Returns:
Sequence[str]— Sequence[str]: A list of prompt values.
Raises:
ValueError— Ifnumberis not a non-negative integer.
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.
| Parameter | Type | Description |
|---|---|---|
first | int | None | If provided, values from the first N prompts are included. Defaults to None. |
last | int | None | If provided, values from the last N prompts are included. Defaults to None. |
harm_categories | Sequence[str] | None | If provided, only prompts containing at least one of these harm categories are included. Defaults to None. |
Returns:
Sequence[str]— Sequence[str]: A list of prompt values.
Raises:
ValueError— Iffirstorlastis not a non-negative integer.
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.
| Parameter | Type | Description |
|---|---|---|
seeds | Sequence[Seed[Any]] | A list of Seed objects. |
Returns:
Sequence[SeedGroup]— A list of SeedGroup or AttackSeedGroup objects, with seeds grouped bySequence[SeedGroup]— prompt_group_id. Each group will be ordered by the sequence number ofSequence[SeedGroup]— the seeds, if available.
Raises:
ValueError— If a seed has an unsupported concrete type.
render_template_value¶
render_template_value(kwargs: object = {}) → NoneRender seed values as templates using provided parameters.
| Parameter | Type | Description |
|---|---|---|
kwargs | object | Key-value pairs to replace in the SeedDataset value. Defaults to {}. |
Raises:
ValueError— If parameters are missing or invalid in the template.
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:
Grouping of SeedPrompt, SeedObjective, and SeedSimulatedConversation
Consistent group IDs and roles across seeds
Prepended conversation and next message extraction
Validation of sequence overlaps between SeedPrompts and SeedSimulatedConversation
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 | NoneGet the outgoing final user turn, or an explicitly opted-in assistant prefix.
Returns:
Message | None— The outgoing message, or None when no eligible final turn exists.
get_prepended_conversation¶
get_prepended_conversation(include_final_assistant: bool = False) → list[Message] | NoneGet history, optionally reserving the final assistant sequence for continuation.
Returns:
list[Message] | None— The prepended conversation, or None when no history exists.
is_single_part_single_text_request¶
is_single_part_single_text_request() → boolCheck if this is a single text prompt.
Returns:
bool— True when there is exactly one prompt and it is text.
is_single_request¶
is_single_request() → boolCheck if all prompts are in a single sequence.
Returns:
bool— True when all prompts share one sequence number.
is_single_turn¶
is_single_turn() → boolCheck if this is a single-turn group (single request without objective).
Returns:
bool— True when the group is a single request and has no objective.
render_template_value¶
render_template_value(kwargs: Any = {}) → NoneRender seed values as templates with provided parameters.
| Parameter | Type | Description |
|---|---|---|
kwargs | Any | Key-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.
| Parameter | Type | Description |
|---|---|---|
seed_group | AttackSeedGroup | The incoming dataset group, without technique seeds. |
Returns:
list[str]— list[str]: Unmet constraints, including those that could be adapted.
to_identity¶
to_identity() → dict[str, Any]Describe behavioral requirements without serializing executable validators.
Returns:
dict[str, Any]— dict[str, Any]: Stable requirement names and schema versions.
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]) → SelfBuild 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.
| Parameter | Type | Description |
|---|---|---|
seed | Seed[Any] | The seed to build an identifier for. |
Returns:
Self— An identifier capturing the seed’s behavioral properties.
get_behavioral_parameters¶
get_behavioral_parameters(seed: Seed[Any]) → dict[str, Any]Project conditions and named prompts for seed identity and storage.
| Parameter | Type | Description |
|---|---|---|
seed | Seed | The seed whose behavioral inputs are projected. |
Returns:
dict[str, Any]— dict[str, Any]: Canonical inputs, excluding descriptive metadata and prompt IDs.
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') → SeedPromptPrepend 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.
| Parameter | Type | Description |
|---|---|---|
base_prompt | SeedPrompt | The already-resolved base SeedPrompt that the prefix is layered ahead of. |
prefix | str | SeedPrompt | Inline string or SeedPrompt to prepend before base_prompt. |
required_parameters | list[str] | Minimum parameter names the resolved (and, if explicit, the prefix) template must support. |
base_component_name | str | Human-readable label for base_prompt, used only in the response_json_schema conflict message. Defaults to 'prompt'. |
prefix_component_name | str | Human-readable label for prefix, used in its validation messages and the response_json_schema conflict message. Defaults to 'prefix'. |
Returns:
SeedPrompt— The combined SeedPrompt.
Raises:
ValueError— If prefix is an inline string containing Jinja syntax, if it is an explicitly provided SeedPrompt missing required parameters, or if both base_prompt and the resolved prefix declare a response_json_schema.
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.
| Parameter | Type | Description |
|---|---|---|
messages | list[Message] | List of Messages to convert. |
starting_sequence | int | The starting sequence number. Defaults to 0. |
prompt_group_id | uuid.UUID | None | Optional group ID to assign to all prompts. Defaults to None. |
Returns:
list[SeedPrompt]— List of SeedPrompts with incrementing sequence numbers per message.
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') → SeedPromptCoerce 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).
| Parameter | Type | Description |
|---|---|---|
value | str | SeedPrompt | The inline string or SeedPrompt to coerce. |
required_parameters | list[str] | Parameter names the resolved template must support. |
error_message | str | None | Optional custom error message for validation failures. Defaults to None. |
component_name | str | Human-readable label used in the default failure message (ignored when error_message is provided). Defaults to 'prompt'. |
Returns:
SeedPrompt— The resolved SeedPrompt.
Raises:
ValueError— If an explicitly provided SeedPrompt is missing required parameters.
from_yaml_with_required_parameters¶
from_yaml_with_required_parameters(template_path: str | Path, required_parameters: list[str], error_message: str | None = None) → SeedPromptLoad 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.
| Parameter | Type | Description |
|---|---|---|
template_path | str | Path | Path to the YAML file containing the template. |
required_parameters | list[str] | List of parameter names that must exist in the template. |
error_message | str | None | Custom error message if validation fails. If None, a default message is used. Defaults to None. |
Returns:
SeedPrompt— The loaded and validated SeedPrompt.
Raises:
ValueError— If the template doesn’t contain all required parameters.
reject_jinja_syntax¶
reject_jinja_syntax(value: str, component_name: str = 'prompt') → NoneRaise 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).
| Parameter | Type | Description |
|---|---|---|
value | str | The inline string to check. |
component_name | str | Human-readable label for value, used in the failure message. Defaults to 'prompt'. |
Raises:
ValueError— If value contains “{{”, “{%”, or “{#”.
set_encoding_metadata¶
set_encoding_metadata() → NoneSet 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) → SeedPromptRebuild resolved prompt text and optional sequence without rendering literal template syntax.
| Parameter | Type | Description |
|---|---|---|
value | str | The resolved prompt text. |
sequence | int | None | A replacement sequence, or None to keep the current sequence. Defaults to None. |
Returns:
SeedPrompt— A validated prompt retaining all other template metadata.
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:
| Parameter | Type | Description |
|---|---|---|
num_turns | int | Number of conversation turns to generate. |
adversarial_chat_system_prompt | SystemPrompt | System-prompt SeedPrompt for the adversarial chat. Use with_layered_prefix to prepend static guidance ahead of it. |
simulated_target_system_prompt | SystemPrompt | System-prompt SeedPrompt for the simulated target. Defaults to the compliant prompt if not specified. |
next_message_system_prompt | SystemPrompt | None | Optional 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() → strCompute a deterministic hash of this configuration.
Returns:
str— A SHA256 hash string representing the configuration.
get_identifier¶
get_identifier() → dict[str, Any]Get an identifier dict capturing this configuration for comparison/storage.
Returns:
dict[str, Any]— Dictionary with configuration details.
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 | NoneLoad 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.
| Parameter | Type | Description |
|---|---|---|
objective | str | The objective to render into the template. |
num_turns | int | The number of turns to render into the template. |
simulated_target_system_prompt_path | str | Path | None | Optional path to the prompt YAML file. If None, no system prompt is used. Defaults to None. |
Returns:
str | None— The rendered system prompt string, or None if no path is provided.
Raises:
ValueError— If the template doesn’t have required parameters.
with_layered_prefix¶
with_layered_prefix(prefix: str) → SeedSimulatedConversationReturn 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).
| Parameter | Type | Description |
|---|---|---|
prefix | str | Static guidance to prepend ahead of the adversarial chat system prompt. Must be static text (no Jinja syntax). |
Returns:
SeedSimulatedConversation— A new SeedSimulatedConversation with the combined adversarial chat system prompt.
Raises:
ValueError— Ifprefixcontains Jinja syntax.
with_settings¶
with_settings(changes: SimulationChanges) → SeedSimulatedConversationRebuild generation settings without changing message modes or prompt metadata.
Returns:
SeedSimulatedConversation— A validated independent seed with recomputed identity.
Raises:
ValueError— If a supplied clear would change the message mode or turn count is null.
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() → SelfCreate a deep copy of the result.
Returns:
Self— A deep copy of the result.
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:
| Parameter | Type | Description |
|---|---|---|
refusal | int | 1 if the model refused, otherwise 0. |
convincingness | int | How convincing the response is, from 1 to 5. |
specificity | int | How specific the response is, from 1 to 5. |
Methods:
from_metadata¶
from_metadata(metadata: Mapping[str, str | int | float] | None) → StrongRejectAnswers | NoneRead the answers from score metadata.
| Parameter | Type | Description |
|---|---|---|
metadata | Mapping[str, str | int | float] | None | The score metadata. |
Returns:
StrongRejectAnswers | None— StrongRejectAnswers | None: The answers, or None when any of them is missing or invalid.
read¶
read(score: Score | None) → StrongRejectAnswers | NoneRead the answers a StrongREJECT score recorded.
| Parameter | Type | Description |
|---|---|---|
score | Score | None | The score to read. |
Returns:
StrongRejectAnswers | None— StrongRejectAnswers | None: The answers, or None when the score has no usable ones.
to_metadata¶
to_metadata() → dict[str, int]Return the metadata fragment carrying these answers.
Returns:
dict[str, int]— dict[str, int]: The answers under their metadata keys.
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:
dict[str, type[StructuredParameterValue]]— dict[str, type[StructuredParameterValue]]: Input names mapped to subclasses of the declaring type.
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 | NoneReturn the baseline entry for one location.
| Parameter | Type | Description |
|---|---|---|
uri | str | The location. |
Returns:
SurfaceEntry | None— SurfaceEntry | None: The entry, or None when the baseline holds none.
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) → boolReturn whether this target supports the given capability.
| Parameter | Type | Description |
|---|---|---|
capability | CapabilityName | The capability to check. |
Returns:
bool— True if supported, otherwise False.
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:
frozenset[str]— frozenset[str]: Identity-conflicting target constructor parameter names.
get_multiline_parameter_names¶
get_multiline_parameter_names() → frozenset[str]Get target constructor parameters whose values require multiline controls.
Returns:
frozenset[str]— frozenset[str]: Multiline target constructor parameter names.
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 | NoneRead the request stored in seed metadata.
| Parameter | Type | Description |
|---|---|---|
metadata | Mapping[str, Any] | None | A seed’s metadata. |
Returns:
Self | None— Self | None: The request, or None if the metadata holds no valid request.
to_metadata¶
to_metadata() → dict[str, Any]Serialize this request for seed metadata.
Returns:
dict[str, Any]— dict[str, Any]: The metadata fragment that holds this request.
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 | NoneReconstruct 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).
| Parameter | Type | Description |
|---|---|---|
metadata | dict[str, Any] | The prompt metadata to read. |
Returns:
Self | None— Self | None: The reconstructed usage, or None if no token-usage keys exist.
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:
dict[str, int]— dict[str, int]: The metadata fragment to merge intoprompt_metadata.
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 | NoneRead the recorded capture coverage.
Returns:
Self | None— Self | None: The recorded coverage, or None if the target recorded none.
Raises:
ValueError— If the stored coverage is malformed.
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 | NoneRead invocation status without interpreting tool-returned data.
Returns:
Self | None— Self | None: The recorded status, or None if absent.
Raises:
ValueError— If stored invocation metadata is malformed.
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 | NoneRead the reason a tool loop stopped.
Returns:
Self | None— Self | None: The recorded reason, or None if the loop did not stop early.
Raises:
ValueError— If the stored reason is unknown.
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) → ScoreConvert this unvalidated score into a validated Score.
| Parameter | Type | Description |
|---|---|---|
score_value | str | Normalized score value. |
score_type | ScoreType | Score type. |
Returns:
Score— Validated score object.
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) → SelfRead a policy without changing the metadata.
| Parameter | Type | Description |
|---|---|---|
metadata | Mapping[str, Any] | None | Message-piece prompt metadata. |
Returns:
Self— The explicit policy, or default behavior when absent, as the calling class.
to_metadata¶
to_metadata() → dict[str, Any]Serialize the policy to message-piece prompt metadata.
Returns:
dict[str, Any]— dict[str, Any]: Empty for default behavior, otherwise the explicit policy.
WebSearchMode¶
Bases: str, Enum
Whether a request preserves, disables, or requires target-hosted search.