Provide functionality for storing and retrieving conversation history and embeddings.
This package defines the core MemoryInterface and concrete implementations for different storage backends.
Functions¶
data_serializer_factory¶
data_serializer_factory(data_type: PromptDataType, value: str | None = None, extension: str | None = None, category: AllowedCategories) → DataTypeSerializerCreate a DataTypeSerializer instance.
| Parameter | Type | Description |
|---|---|---|
data_type | str | The type of the data (e.g., ‘text’, ‘image_path’, ‘audio_path’). |
value | str | The data value to be serialized. Defaults to None. |
extension | str | None | The file extension, if applicable. Defaults to None. |
category | AllowedCategories | The category or context for the data (e.g., ‘seed-prompt-entries’). |
Returns:
DataTypeSerializer— An instance of the appropriate serializer.
Raises:
ValueError— If the category is not provided or invalid.
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.
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.
set_message_piece_sha256_async¶
set_message_piece_sha256_async(message_piece: MessagePiece) → NoneCompute and assign SHA256 hash values for a message piece’s original and converted payloads.
Async because blob payloads may need to be fetched. Must be called explicitly after the message piece is constructed and its values are finalized.
| Parameter | Type | Description |
|---|---|---|
message_piece | MessagePiece | The message piece to populate with SHA256 values. |
set_seed_sha256_async¶
set_seed_sha256_async(seed: Seed[Any]) → NoneCompute and assign the SHA256 hash value for a seed’s value.
Should be called after the seed value is serialized to text, as file paths used in
the value may have changed from local to memory storage paths. Async due to blob retrieval.
| Parameter | Type | Description |
|---|---|---|
seed | Seed | The seed to populate with its SHA256 value. |
AttackResultEntry¶
Bases: Base
Represents the attack result data in the database.
Attributes:
| Parameter | Type | Description |
|---|---|---|
__tablename__ | str | The name of the database table. |
__table_args__ | dict | Additional arguments for the database table. |
id | Uuid | The unique identifier for the attack result entry. |
conversation_id | str | The unique identifier of the conversation that produced this result. |
objective | str | Natural-language description of the attacker’s objective. |
atomic_attack_identifier | dict[str, Any] | None | Composite identifier of the attack (technique, seeds, etc.). |
objective_sha256 | str | The SHA256 hash of the objective. |
last_response_id | Uuid | Foreign key to the last response MessagePiece. |
automated_score_id | Uuid | Foreign key to the automated score ScoreEntry. |
human_score_id | Uuid | Foreign key to the human score ScoreEntry. |
executed_turns | int | Total number of turns that were executed. |
execution_time_ms | int | Total execution time of the attack in milliseconds. |
outcome | AttackOutcome | The outcome of the attack, indicating success, failure, or undetermined. |
outcome_reason | str | Optional reason for the outcome, providing additional context. |
attack_metadata | dict[str, Any] | Metadata can be included as key-value pairs to provide extra context. |
operator | str | None | Operator responsible for the attack. |
operation | str | None | Operation associated with the attack. |
labels | dict[str, str] | Optional labels associated with the attack result entry. |
targeted_harm_categories | list[str] | Harm categories this attack targeted. |
pruned_conversation_ids | list[str] | List of conversation IDs that were pruned from the attack. |
adversarial_chat_conversation_ids | list[str] | List of conversation IDs used for adversarial chat. |
preparation_conversation_ids | list[str] | List of conversations used to prepare the attack. |
timestamp | DateTime | The timestamp of the attack result entry. |
last_response | PromptMemoryEntry | Relationship to the last response prompt memory entry. |
automated_score | ScoreEntry | Relationship to the automated score entry. |
human_score | ScoreEntry | Relationship to the human score entry. |
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
entry | AttackResult | The attack result object to convert into a database entry. |
Methods:
filter_json_serializable_metadata¶
filter_json_serializable_metadata(metadata: dict[str, Any]) → dict[str, Any]Filter a dictionary to only include JSON-serializable values.
This function iterates through the metadata dictionary and keeps only values that can be serialized to JSON, discarding any non-serializable objects.
| Parameter | Type | Description |
|---|---|---|
metadata | dict[str, Any] | Dictionary with potentially non-serializable values |
Returns:
dict[str, Any]— Dictionary with only JSON-serializable values
get_attack_result¶
get_attack_result() → AttackResultConvert this database entry back into an AttackResult object.
Returns:
AttackResult— The reconstructed attack result including related conversations and scores.
AttackResultKeysetCursor¶
Bases: NamedTuple
Keyset (seek) anchor identifying the last attack result on a page.
Captures the recency ordering tuple — the row timestamp (the attack’s last-updated
time; see AttackResultEntry.timestamp) and the unique attack_result_id — so the
next page can seek to rows strictly after this one under the timestamp DESC, id DESC
ordering. Unlike a numeric offset — which shifts every later row when a row is inserted or
deleted between page loads — a keyset anchor stays pinned to its row, so inserts and
deletions elsewhere no longer skip or duplicate results at the page boundary.
Methods:
from_attack_result¶
from_attack_result(result: AttackResult) → AttackResultKeysetCursorBuild the keyset anchor for result (typically the last row of a page).
Returns:
AttackResultKeysetCursor— Anchor capturing the result’s recency sort key.
AudioPathDataTypeSerializer¶
Bases: DataTypeSerializer
Serializer for audio path values stored on disk.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
category | str | Data category folder name. |
prompt_text | str | None | Optional existing audio path. Defaults to None. |
extension | str | None | Optional audio extension. Defaults to None. |
Methods:
data_on_disk¶
data_on_disk() → boolIndicate whether this serializer persists data on disk.
Returns:
bool— Always True for audio path serializers.
AzureBlobStorageIO¶
Bases: StorageIO
Implementation of StorageIO for Azure Blob Storage.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
container_url | str | None | Azure Blob container URL. Defaults to None. |
sas_token | str | None | Optional SAS token. Defaults to None. |
blob_content_type | SupportedContentType | Blob content type for uploads. Defaults to SupportedContentType.PLAIN_TEXT. |
Methods:
canonical_path¶
canonical_path(path: str) → strResolve URLs and relative names against this adapter’s configured container.
Returns:
str— The effective blob identity, without SAS parameters.
create_directory_if_not_exists_async¶
create_directory_if_not_exists_async(directory_path: Path | str) → NoneLog a no-op directory creation for Azure Blob Storage.
| Parameter | Type | Description |
|---|---|---|
directory_path | Path | str | Requested directory path. |
delete_file_async¶
delete_file_async(path: Path | str) → NoneDelete one blob created by the caller.
is_file_async¶
is_file_async(path: Path | str) → boolCheck whether the path refers to a file (blob) in Azure Blob Storage.
| Parameter | Type | Description |
|---|---|---|
path | Path | str | Blob URL or path to test. |
Returns:
bool— True when the blob exists and has non-zero content size.
parse_blob_url¶
parse_blob_url(file_path: str) → tuple[str, str]Parse a blob URL to extract the container and blob name.
| Parameter | Type | Description |
|---|---|---|
file_path | str | Full blob URL. |
Returns:
tuple[str, str]— tuple[str, str]: Container name and blob name.
Raises:
ValueError— If file_path is not a valid blob URL.
path_exists_async¶
path_exists_async(path: Path | str) → boolCheck whether a given path exists in the Azure Blob Storage container.
| Parameter | Type | Description |
|---|---|---|
path | Path | str | Blob URL or path to test. |
Returns:
bool— True when the path exists.
read_file_async¶
read_file_async(path: Path | str) → bytesAsynchronously reads the content of a file (blob) from Azure Blob Storage.
If the provided path is a full URL
(e.g., https://account.blob.core.windows.net/container/dir1/dir2/sample.png),
it extracts the relative blob path (e.g., dir1/dir2/sample.png) to correctly access the blob.
If a relative path is provided, it will use it as-is.
| Parameter | Type | Description |
|---|---|---|
path | str | The path to the file (blob) in Azure Blob Storage. This can be either a full URL or a relative path. |
Returns:
bytes— The content of the file (blob) as bytes.
write_file_async¶
write_file_async(path: Path | str, data: bytes) → NoneWrite data to Azure Blob Storage at the specified path.
If the provided path is a full URL, the blob name is extracted from it.
If a relative path is provided, it is used as the blob name directly.
| Parameter | Type | Description |
|---|---|---|
path | Path | str | Full blob URL or relative blob path. |
data | bytes | The data to write. |
write_stream_async¶
write_stream_async(path: Path | str, chunks: AsyncIterable[bytes]) → NoneStream a generated blob as opaque bytes, never replacing an existing blob.
AzureSQLMemory¶
Bases: MemoryInterface
A class to manage conversation memory using Azure SQL Server as the backend database. It leverages SQLAlchemy Base models for creating tables and provides CRUD operations to interact with the tables.
This class encapsulates the setup of the database connection, table creation based on SQLAlchemy models, and session management to perform database operations.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
connection_string | str | None | The connection string for the Azure Sql Database. If not provided, it falls back to the ‘AZURE_SQL_DB_CONNECTION_STRING’ environment variable. Defaults to None. |
results_container_url | str | None | The URL to an Azure Storage Container. If not provided, it falls back to the ‘AZURE_STORAGE_ACCOUNT_DB_DATA_CONTAINER_URL’ environment variable. Defaults to None. |
results_sas_token | str | None | The Shared Access Signature (SAS) token for the storage container. If not provided, falls back to the ‘AZURE_STORAGE_ACCOUNT_DB_DATA_SAS_TOKEN’ environment variable. Defaults to None. |
verbose | bool | Whether to enable verbose logging for the database engine. Defaults to False. |
skip_schema_migration | bool | Whether to skip schema migration. Defaults to True. Set to False to explicitly migrate a non-production database during initialization. |
silent | bool | If True, suppresses schema migration console output. Defaults to False. |
Methods:
dispose_loop_resources_async¶
dispose_loop_resources_async() → NoneClose the current loop’s engine and its owned Azure credential.
BinaryPathDataTypeSerializer¶
Bases: DataTypeSerializer
Serializer for generic binary path values stored on disk.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
category | str | The category or context for the data. |
prompt_text | str | None | The binary file path or identifier. Defaults to None. |
extension | str | None | The file extension, defaults to ‘bin’. |
Methods:
data_on_disk¶
data_on_disk() → boolIndicate whether this serializer persists data on disk.
Returns:
bool— Always True for binary path serializers.
CentralMemory¶
Provide a centralized memory instance across the framework. The provided memory instance will be reused for future calls.
Examples:
Methods:
get_memory_instance¶
get_memory_instance() → MemoryInterfaceReturn a centralized memory instance.
Returns:
MemoryInterface— The singleton memory instance.
Raises:
ValueError— If the central memory instance has not been set.
set_memory_instance¶
set_memory_instance(passed_memory: MemoryInterface) → NoneSet a provided memory instance as the central instance for subsequent calls.
| Parameter | Type | Description |
|---|---|---|
passed_memory | MemoryInterface | The memory instance to set as the central instance. |
DataTypeSerializer¶
Bases: abc.ABC
Abstract base class for data type normalizers.
Responsible for reading and saving multi-modal data types to local disk or Azure Storage Account.
Methods:
data_on_disk¶
data_on_disk() → boolIndicate whether the data is stored on disk.
Returns:
bool— True when data is persisted on disk.
get_data_filename_async¶
get_data_filename_async(file_name: str | None = None) → Path | strGenerate or retrieve a unique filename for the data file.
| Parameter | Type | Description |
|---|---|---|
file_name | str | None | Optional file name override. Defaults to None. |
Returns:
Path | str— Path | str: Full storage path for the generated data file.
Raises:
TypeError— If the serializer is not configured for on-disk data.RuntimeError— If required data subdirectory information is missing.
get_extension¶
get_extension(file_path: str) → str | NoneGet the file extension from the file path.
| Parameter | Type | Description |
|---|---|---|
file_path | str | Input file path. |
Returns:
str | None— str | None: File extension (including dot) or None if unavailable.
get_mime_type¶
get_mime_type(file_path: str) → str | NoneGet the MIME type of the file path.
| Parameter | Type | Description |
|---|---|---|
file_path | str | Input file path. |
Returns:
str | None— str | None: MIME type if detectable; otherwise None.
get_sha256_async¶
get_sha256_async() → strCompute SHA256 hash for this serializer’s current value.
Returns:
str— Hex digest of the computed SHA256 hash.
Raises:
FileNotFoundError— If on-disk data path does not exist.ValueError— If in-memory data cannot be converted to bytes.
read_data_async¶
read_data_async() → bytesRead data from storage.
Returns:
bytes— The data read from storage.
Raises:
TypeError— If the serializer does not represent on-disk data.RuntimeError— If no value is set.FileNotFoundError— If the referenced file does not exist.
read_data_base64_async¶
read_data_base64_async() → strRead data from storage and return it as a base64 string.
Returns:
str— Base64-encoded data.
save_b64_image_async¶
save_b64_image_async(data: str | bytes, output_filename: str | None = None) → NoneSave a base64-encoded image to storage.
| Parameter | Type | Description |
|---|---|---|
data | str | bytes | string or bytes with base64 data |
output_filename | (optional, str) | filename to store image as. Defaults to UUID if not provided |
Raises:
RuntimeError— If storage IO is not initialized.
save_data_async¶
save_data_async(data: bytes, output_filename: str | None = None) → NoneSave data to storage.
| Parameter | Type | Description |
|---|---|---|
data | bytes | bytes: The data to be saved. |
output_filename | (optional, str) | filename to store data as. Defaults to UUID if not provided |
Raises:
RuntimeError— If storage IO is not initialized.
save_formatted_audio_async¶
save_formatted_audio_async(data: bytes, num_channels: int = 1, sample_width: int = 2, sample_rate: int = 16000, output_filename: str | None = None) → NoneSave PCM16 or similarly formatted audio data to storage.
| Parameter | Type | Description |
|---|---|---|
data | bytes | bytes with audio data |
output_filename | (optional, str) | filename to store audio as. Defaults to UUID if not provided |
num_channels | (optional, int) | number of channels in audio data. Defaults to 1 |
sample_width | (optional, int) | sample width in bytes. Defaults to 2 |
sample_rate | (optional, int) | sample rate in Hz. Defaults to 16000 |
Raises:
RuntimeError— If storage IO is not initialized.ValueError— If a non-WAV file path was already reserved for this serializer.
save_stream_async¶
save_stream_async(chunks: AsyncIterable[bytes]) → NonePersist a bounded multipart stream through the configured storage backend.
Raises:
RuntimeError— If results storage is not initialized.
DiskStorageIO¶
Bases: StorageIO
Implementation of StorageIO for local disk storage.
Methods:
create_directory_if_not_exists_async¶
create_directory_if_not_exists_async(path: Path | str) → NoneAsynchronously creates a directory if it doesn’t exist on the local disk.
| Parameter | Type | Description |
|---|---|---|
path | Path | The directory path to create. |
delete_file_async¶
delete_file_async(path: Path | str) → NoneDelete one file, not its containing directory.
is_file_async¶
is_file_async(path: Path | str) → boolCheck whether the given path is a file (not a directory).
| Parameter | Type | Description |
|---|---|---|
path | Path | The path to check. |
Returns:
bool— True if the path is a file, False otherwise.
path_exists_async¶
path_exists_async(path: Path | str) → boolCheck whether a path exists on the local disk.
| Parameter | Type | Description |
|---|---|---|
path | Path | The path to check. |
Returns:
bool— True if the path exists, False otherwise.
read_file_async¶
read_file_async(path: Path | str) → bytesAsynchronously reads a file from the local disk.
| Parameter | Type | Description |
|---|---|---|
path | Path | str | The path to the file. |
Returns:
bytes— The content of the file.
write_file_async¶
write_file_async(path: Path | str, data: bytes) → NoneAsynchronously writes data to a file on the local disk.
| Parameter | Type | Description |
|---|---|---|
path | Path | The path to the file. |
data | bytes | The content to write to the file. |
write_stream_async¶
write_stream_async(path: Path | str, chunks: AsyncIterable[bytes]) → NoneCreate a generated upload file without overwriting existing bytes.
EmbeddingDataEntry¶
Bases: Base
Represents the embedding data associated with conversation entries in the database. Each embedding is linked to a specific conversation entry via an id.
Attributes:
| Parameter | Type | Description |
|---|---|---|
id | Uuid | The primary key, which is a foreign key referencing the UUID in the PromptMemoryEntries table. |
embedding | ARRAY(Float | An array of floats representing the embedding vector. |
embedding_type_name | String | The name or type of the embedding, indicating the model or method used. |
ErrorDataTypeSerializer¶
Bases: DataTypeSerializer
Serializer for error payloads stored as in-memory text.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
prompt_text | str | Error payload text. |
Methods:
data_on_disk¶
data_on_disk() → boolIndicate whether this serializer persists data on disk.
Returns:
bool— Always False for error serializers.
ImagePathDataTypeSerializer¶
Bases: DataTypeSerializer
Serializer for image path values stored on disk.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
category | str | Data category folder name. |
prompt_text | str | None | Optional existing image path. Defaults to None. |
extension | str | None | Optional image extension. Defaults to None. |
Methods:
data_on_disk¶
data_on_disk() → boolIndicate whether this serializer persists data on disk.
Returns:
bool— Always True for image path serializers.
MemoryEmbedding¶
The MemoryEmbedding class is responsible for encoding the memory embeddings.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
embedding_model | EmbeddingSupport | None | The embedding model used to generate text embeddings. If not provided, a ValueError is raised. Defaults to None. |
Methods:
generate_embedding_memory_data¶
generate_embedding_memory_data(message_piece: MessagePiece) → EmbeddingDataEntryGenerate metadata for a message piece.
| Parameter | Type | Description |
|---|---|---|
message_piece | MessagePiece | the message piece for which to generate a text embedding |
Returns:
EmbeddingDataEntry— The generated metadata.
Raises:
ValueError— If the message piece is not of type text.
MemoryInterface¶
Bases: abc.ABC
Abstract interface for conversation memory storage systems.
This interface defines the contract for storing and retrieving chat messages and conversation history. Implementations can use different storage backends such as files, databases, or cloud storage services.
Text substring filters are case-insensitive and literal. Pattern companions accept full LIKE patterns: ‘%’ and ‘_’ are wildcards, ‘/’ escapes the next character, and brackets, ‘*’ and backslashes are literal. Patterns are not automatically wrapped in ‘%’. A dangling escape or a literal/pattern conflict raises ValueError. Existing exact filters and ordinary empty-query behavior remain unchanged; an explicit empty pattern matches empty text.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
embedding_model | Any | None | If set, this includes embeddings in the memory entries which are extremely useful for comparing chat messages and similarities, but also includes overhead. Defaults to None. |
Methods:
add_attack_results_to_memory¶
add_attack_results_to_memory(attack_results: Sequence[AttackResult]) → NoneUse add_attack_results_to_memory_async.
This synchronous API is deprecated and can block the caller.
add_attack_results_to_memory_async¶
add_attack_results_to_memory_async(attack_results: Sequence[AttackResult]) → NoneInsert a list of attack results into the memory storage. The database model automatically calculates objective_sha256 for consistency.
Raises:
SQLAlchemyError— If the database transaction fails.
add_conversation_branches_to_attack¶
add_conversation_branches_to_attack(attack_result_id: str, conversations: Sequence[Conversation], message_pieces: Sequence[MessagePiece], source_conversation: Conversation | None = None, new_attack: AttackResult | None = None, expected_fields: Mapping[str, Any] | None = None, update_fields: Mapping[str, Any] | None = None, request_fingerprint: str | None = None, replace_conversation_pieces: Mapping[str, Sequence[MessagePiece]] | None = None) → boolUse add_conversation_branches_to_attack_async.
This synchronous API is deprecated and can block the caller.
Returns:
bool— The operation result.
add_conversation_branches_to_attack_async¶
add_conversation_branches_to_attack_async(attack_result_id: str, conversations: Sequence[Conversation], message_pieces: Sequence[MessagePiece], source_conversation: Conversation | None = None, new_attack: AttackResult | None = None, expected_fields: Mapping[str, Any] | None = None, update_fields: Mapping[str, Any] | None = None, request_fingerprint: str | None = None, replace_conversation_pieces: Mapping[str, Sequence[MessagePiece]] | None = None) → boolAtomically store initial or related conversations, pieces, and attack references.
The caller prepares the copies. This method only persists them, preserving the usual
conversation and message insertion invariants. A supplied source must still be an
active objective conversation when the transaction acquires the attack’s write lock.
Supply new_attack to create the attack in the same transaction. An optional
request fingerprint makes retries with the same conversation IDs idempotent.
Returns:
bool— True for an insert; False for an identical retry or a missing destination.
Raises:
ValueError— If the source is unrelated, branch IDs repeat, or pieces belong elsewhere.AttackStateConflictError— An expected field or creation identity changed.SQLAlchemyError— If persistence fails; the complete preparation is rolled back.
add_conversation_retry¶
add_conversation_retry(conversation_id: str, sequence: int, reason: ConversationRetryReason) → NoneUse add_conversation_retry_async.
This synchronous API is deprecated and can block the caller.
add_conversation_retry_async¶
add_conversation_retry_async(conversation_id: str, sequence: int, reason: ConversationRetryReason) → NoneAppend a retry record to the conversation-scoped metadata for conversation_id.
Records that a turn had to be retried (e.g. because its response failed JSON
validation and was rolled back out of memory). The conversation’s Conversations
row is updated in place; if no row exists yet it is created. This is distinct from
the insert-only _insert_conversation.
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation whose turn was retried. |
sequence | int | The sequence the retried turn’s request occupies. |
reason | ConversationRetryReason | Why the turn was retried. |
Raises:
SQLAlchemyError— If the database update fails; the transaction is rolled back first.
add_conversation_to_memory¶
add_conversation_to_memory(conversation: Conversation) → NoneUse add_conversation_to_memory_async.
This synchronous API is deprecated and can block the caller.
add_conversation_to_memory_async¶
add_conversation_to_memory_async(conversation: Conversation) → NoneRegister a conversation in memory, recording its conversation-scoped metadata.
A conversation is a first-class entity held with a single target. Build a
Conversation when it is created and call this once (before, or independently
of, adding its messages) to record the target it is held with. Message writes
(add_message_to_memory / add_message_pieces_to_memory) deliberately do
not take a target, so that conversation ownership is expressed in a single place
rather than threaded through every write.
Registration is idempotent only for an identical conversation: re-registering the
same conversation_id with the same target identity is a no-op, even across
PyRIT versions (so repeated per-turn registration is safe). Re-registering an existing
conversation_id with a different target is a conflict and raises ValueError -- a conversation is held
with exactly one target and is never re-targeted.
The caller supplies ownership through conversation.attack_result_id.
Registering a conversation that belongs to a different execution raises ValueError.
| Parameter | Type | Description |
|---|---|---|
conversation | Conversation | The conversation metadata to record, carrying the conversation_id and the target it is held with (if known). |
Raises:
ValueError— Ifconversation_idis empty, or if a conversation with the same id already exists with a different target or belongs to a different attack execution.
add_finding_async¶
add_finding_async(finding: Finding, evidence: FindingEvidence | None = None) → FindingSave a finding, and optionally its evidence, in one transaction.
A sub-finding’s parent must be in the same operation. A new finding has no sub-findings yet, so its paths
are set afterwards with replace_finding_paths_async.
Returns:
Finding— The saved finding, or the finding already saved with this ID.
Raises:
LookupError— If the finding’s Operation does not exist.FindingHierarchyError— If the finding has paths, or its parent is not in its Operation.IntegrityError— If the insert fails for a reason other than a taken ID.
add_finding_evidence_async¶
add_finding_evidence_async(evidence: FindingEvidence) → FindingEvidenceLink a saved attack result to a finding, if the finding still exists.
The insert runs before the existence check so the write lock is held when the finding is checked, and a concurrent delete can’t leave an orphan.
Returns:
FindingEvidence— The saved evidence, or the existing link for the same finding and attack result.
Raises:
LookupError— If the finding does not exist.IntegrityError— If the insert fails for a reason other than a duplicate link.
add_message_pieces_to_memory¶
add_message_pieces_to_memory(message_pieces: Sequence[MessagePiece]) → NoneUse add_message_pieces_to_memory_async.
This synchronous API is deprecated and can block the caller.
add_message_pieces_to_memory_async¶
add_message_pieces_to_memory_async(message_pieces: Sequence[MessagePiece]) → NoneInsert a list of message pieces into the memory storage.
Pieces flagged via MessagePiece.not_in_memory = True are silently filtered
out so callers don’t need to track persistence policy themselves. Every
remaining piece must carry a non-empty conversation_id (the memory layer
never invents one -- see _validate_persistable_conversation_ids).
Conversation-scoped metadata (the target a conversation is held with) is not
recorded here; register it once via add_conversation_to_memory when the
conversation is created.
This is a template method: subclasses implement only the backend-specific
_add_message_pieces_to_memory and inherit the filtering and validation
steps so no subclass can forget to run them.
| Parameter | Type | Description |
|---|---|---|
message_pieces | Sequence[MessagePiece] | The pieces to persist. |
add_message_to_memory¶
add_message_to_memory(request: Message) → NoneUse add_message_to_memory_async.
This synchronous API is deprecated and can block the caller.
add_message_to_memory_async¶
add_message_to_memory_async(request: Message) → NoneInsert a list of message pieces into the memory storage.
Automatically updates the sequence to be the next number in the conversation. If necessary, generates embedding data for applicable entries
| Parameter | Type | Description |
|---|---|---|
request | Message | The message to add to the memory. |
add_operation_async¶
add_operation_async(operation: Operation) → OperationSave an operation. Names are unique, ignoring case and surrounding whitespace.
Returns:
Operation— The saved operation, or the existing one when the name is taken.
Raises:
IntegrityError— If the insert fails for a reason other than a taken name.
add_planned_scenario_result_async¶
add_planned_scenario_result_async(scenario_result: ScenarioResult, seed_groups_by_dataset: Mapping[str, Sequence[AttackSeedGroup]]) → NoneInsert a new scenario result together with the seed groups its run planned.
Resume rebuilds the run from these groups, so later dataset changes don’t affect it.
| Parameter | Type | Description |
|---|---|---|
scenario_result | ScenarioResult | The new scenario result. |
seed_groups_by_dataset | Mapping[str, Sequence[AttackSeedGroup]] | The planned population, by dataset name, in the order the run was built from. |
Raises:
SQLAlchemyError— If the result, its identifier graph, or its seed groups cannot be persisted.
add_prepared_seed_batch_async¶
add_prepared_seed_batch_async(batch: PreparedSeedBatch) → NoneInsert prepared seeds with normal deduplication, without preparing them again.
| Parameter | Type | Description |
|---|---|---|
batch | PreparedSeedBatch | The snapshot returned by prepare_seed_batch_async. |
add_prompt_generations_async¶
add_prompt_generations_async(generations: Sequence[PromptGenerationRecord]) → NoneSave new prompt generations together, holding each one’s dataset name.
Each generation is checked after the ones before it are written, so the database’s own name comparison also rejects two members of one batch that it treats as the same name.
| Parameter | Type | Description |
|---|---|---|
generations | Sequence[PromptGenerationRecord] | The generations to save. |
Raises:
DatasetNameConflictError— If a dataset name is used by stored seeds, a staging upload, another unfinished generation, or an earlier member of the batch. Nothing is saved.
add_scenario_results_to_memory¶
add_scenario_results_to_memory(scenario_results: Sequence[ScenarioResult]) → NoneUse add_scenario_results_to_memory_async.
This synchronous API is deprecated and can block the caller.
add_scenario_results_to_memory_async¶
add_scenario_results_to_memory_async(scenario_results: Sequence[ScenarioResult]) → NoneInsert a list of scenario results into the memory storage.
| Parameter | Type | Description |
|---|---|---|
scenario_results | Sequence[ScenarioResult] | Sequence of ScenarioResult objects to store in the database. |
Raises:
SQLAlchemyError— If a scenario result or identifier graph cannot be persisted.
add_scores_to_memory¶
add_scores_to_memory(scores: Sequence[Score], observations: Sequence[Observation] = (), intermediate_scores: Sequence[Score] = ()) → NoneUse add_scores_to_memory_async.
This synchronous API is deprecated and can block the caller.
add_scores_to_memory_async¶
add_scores_to_memory_async(scores: Sequence[Score], observations: Sequence[Observation] = (), intermediate_scores: Sequence[Score] = ()) → NonePrepare file-backed loose content, then persist scores and observations.
intermediate_scores are results of nested scorers at any depth. They share the
transaction but are excluded from default score queries.
Raises:
ValueError— If an observation does not match its scored content.
add_seed_datasets_to_memory_async¶
add_seed_datasets_to_memory_async(datasets: Sequence[SeedDataset], added_by: str) → NoneInsert a list of seed datasets into the memory storage.
| Parameter | Type | Description |
|---|---|---|
datasets | Sequence[SeedDataset] | A list of seed datasets to insert. |
added_by | str | The user who added the datasets. |
add_seed_groups_to_memory_async¶
add_seed_groups_to_memory_async(prompt_groups: Sequence[SeedGroup], added_by: str | None = None) → NoneInsert a list of seed groups into the memory storage.
| Parameter | Type | Description |
|---|---|---|
prompt_groups | Sequence[SeedGroup] | A list of prompt groups to insert. |
added_by | str | The user who added the prompt groups. Defaults to None. |
Raises:
ValueError— If a seed group does not have at least one seed.ValueError— If seed group IDs are inconsistent within the same seed group.
add_seeds_to_memory_async¶
add_seeds_to_memory_async(seeds: Sequence[Seed[Any]], added_by: str | None = None) → NoneInsert a list of seeds into the memory storage.
Seeds already present in storage are skipped by execution identity: value hash, dataset,
seed type, data type, role (None counts as user), general-technique flag, response schema,
and behavioral inputs. Non-execution metadata such as harm categories or descriptions is not part of that
identity, so a metadata-only edit does not create a duplicate and sending a seed standalone
or inside a singleton group deduplicates the same way. Retained multi-seed groups keep their
complete membership; they are compared as complete groups by full member identity, including
roles, sequence, metadata, and behavioral inputs, so shared content cannot strip members from
a different conversation. Duplicates within seeds are all inserted, because the check
looks at what storage held when the call started.
When a stored seed is copied to a new group, its caller-visible ID is updated after
successful insertion; a copy that would otherwise reuse the stored group ID is moved to a
new group so editing it cannot alter the original group.
Decomposition trees, including prompts grouped with their objectives, deduplicate as complete units by execution identity, group membership, parent links, and ordered path steps. Descriptive metadata and path labels do not change tree identity: re-importing updates that metadata in place, keeping the original import attribution and timestamps. Caller seed, group, parent, and path IDs are remapped to the stored IDs only after a successful write. Changes to content, behavioral inputs, group sequence, or tree structure store a separate tree.
| Parameter | Type | Description |
|---|---|---|
seeds | Sequence[Seed] | A list of seeds to insert. |
added_by | str | The user who added the seeds. Defaults to None. |
Raises:
ValueError— If the ‘added_by’ attribute is not set for each prompt.
cleanup¶
cleanup() → NoneEnsure cleanup on process exit.
cleanup_dataset_media_async¶
cleanup_dataset_media_async(operation_id: uuid.UUID, abandon_upload: bool = False) → dict[str, object]Retry owned-media cleanup.
Returns:
dict[str, object]— dict[str, object]: Durable, non-sensitive cleanup status.
commit_dataset_mutation_async¶
commit_dataset_mutation_async(upload_id: uuid.UUID, expected_version: str, delete_ids: Sequence[uuid.UUID], prepare_seeds: Callable[[dict[uuid.UUID, SeedRecord]], list[SeedUnion]], write_media: Callable[[list[SeedUnion]], Awaitable[None]], max_records: int, max_bytes: int) → dict[str, Any]Commit exact inserts/replacements/deletions with final-group and state validation.
Returns:
dict[str, Any]— dict[str, Any]: Exact committed counts, IDs, population and version.
commit_dataset_upload_async¶
commit_dataset_upload_async(upload_id: uuid.UUID, seeds: Sequence[SeedUnion], write_media: Callable[[], Awaitable[None]]) → boolAtomically publish all storage-ready seeds without deduplication or replacement.
Returns:
bool— Whether native ownership was released after the successful commit.
commit_prompt_generation_dataset_async¶
commit_prompt_generation_dataset_async(generation: PromptGenerationRecord, expected_execution_id: uuid.UUID, dataset: SeedDataset, added_by: str) → boolCreate a generation’s dataset and record its completion in one transaction.
The dataset is created only: seeds are inserted as they are, never deduplicated or added to an existing dataset. A generation therefore never has a saved dataset with an unfinished record.
| Parameter | Type | Description |
|---|---|---|
generation | PromptGenerationRecord | The completed generation to store. |
expected_execution_id | uuid.UUID | The run attempt that must still own the running generation. |
dataset | SeedDataset | The dataset to create, named generation.dataset_name. |
added_by | str | Who the seeds are attributed to. |
Returns:
bool— True if the dataset and the generation were saved, False if the generation is missing, isn’t running, or another run attempt owns it. Nothing is saved then.
Raises:
ValueError— If the dataset is empty or a seed belongs to another dataset.DatasetNameConflictError— If stored seeds, a staging upload, or another generation use the dataset name. Nothing is saved.RuntimeError— If the database does not return a cursor result.
delete_conversation_pieces_after_sequence¶
delete_conversation_pieces_after_sequence(conversation_id: str, sequence: int) → intUse delete_conversation_pieces_after_sequence_async.
This synchronous API is deprecated and can block the caller.
Returns:
int— The operation result.
delete_conversation_pieces_after_sequence_async¶
delete_conversation_pieces_after_sequence_async(conversation_id: str, sequence: int) → intDelete all message pieces in a conversation whose sequence is greater than sequence.
Rolls a conversation back to a baseline so a failed turn can be resent on a clean
history. Dependent EmbeddingData rows for the deleted pieces are removed first to
avoid orphaned foreign keys. Pieces at or below sequence (e.g. the system prompt
and any prior good turns) are left intact.
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation to roll back. |
sequence | int | The baseline sequence; pieces with a greater sequence are deleted. |
Returns:
int— The number ofPromptMemoryEntriesdeleted.
Raises:
SQLAlchemyError— If the deletion fails; the transaction is rolled back first.
delete_dataset_async¶
delete_dataset_async(dataset_name: str) → uuid.UUIDDelete exact-name stored seeds and journal cleanup of API-owned media.
Returns:
uuid.UUID— uuid.UUID: The durable deletion identifier.
delete_finding_async¶
delete_finding_async(operation_id: uuid.UUID, finding_id: uuid.UUID) → NonePermanently remove a finding within its operation, with all of its sub-findings, their paths, and evidence.
Raises:
LookupError— If the finding does not belong to the operation.FindingHierarchyError— If the finding is a step of its parent’s paths.
delete_finding_evidence_async¶
delete_finding_evidence_async(finding_id: uuid.UUID, evidence_id: uuid.UUID) → NoneUnlink evidence from a finding. The attack result is kept.
Raises:
LookupError— If the evidence does not belong to the finding.RuntimeError— If the database does not return a cursor result.
delete_operation_async¶
delete_operation_async(operation_id: uuid.UUID) → NonePermanently remove an Operation that no findings, attacks, or scenario runs refer to by ID.
Activity attributed only by a deprecated Operation name does not prevent deletion and is unchanged.
Raises:
LookupError— If the Operation does not exist.OperationInUseError— If findings, attacks, or scenario runs refer to the Operation by ID.RuntimeError— If the database does not return a cursor result.
delete_prompt_generation_async¶
delete_prompt_generation_async(generation_id: uuid.UUID, expected_statuses: Collection[PromptGenerationStatus]) → boolDelete a generation only while it is in one of expected_statuses. Its dataset is kept.
| Parameter | Type | Description |
|---|---|---|
generation_id | uuid.UUID | The generation to delete. |
expected_statuses | Collection[PromptGenerationStatus] | Statuses the generation may be in. |
Returns:
bool— True if the generation was deleted, False if it is missing or in another status.
Raises:
ValueError— Ifexpected_statusesis empty.RuntimeError— If the database does not return a cursor result.
disable_embedding¶
disable_embedding() → NoneDisable embedding functionality for the memory interface.
Sets the memory_embedding attribute to None, disabling any embedding operations.
dispose_engine¶
dispose_engine() → NoneUse dispose_engine_async.
This synchronous API is deprecated and can block the caller.
dispose_engine_async¶
dispose_engine_async() → NoneDispose async and legacy resources after operations have finished.
Raises:
RuntimeError— If another event loop still owns memory resources.
dispose_loop_resources_async¶
dispose_loop_resources_async() → NoneClose resources before their owning event loop stops.
duplicate_conversation¶
duplicate_conversation(conversation_id: str, attack_result_id: str | None = None) → strUse duplicate_conversation_async.
This synchronous API is deprecated and can block the caller.
Returns:
str— The operation result.
duplicate_conversation_async¶
duplicate_conversation_async(conversation_id: str, attack_result_id: str | None = None) → strDuplicate a conversation for reuse.
This can be useful when an attack strategy requires branching out from a particular point in the conversation. One cannot continue both branches with the same conversation ID since that would corrupt the memory. Instead, one needs to duplicate the conversation and continue with the new conversation ID.
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation ID with existing conversations. |
attack_result_id | str | None | Destination owner. Defaults to the source owner. |
Returns:
str— The uuid for the new conversation.
duplicate_conversation_excluding_last_turn¶
duplicate_conversation_excluding_last_turn(conversation_id: str, attack_result_id: str | None = None) → strUse duplicate_conversation_excluding_last_turn_async.
This synchronous API is deprecated and can block the caller.
Returns:
str— The operation result.
duplicate_conversation_excluding_last_turn_async¶
duplicate_conversation_excluding_last_turn_async(conversation_id: str, attack_result_id: str | None = None) → strDuplicate a conversation, excluding the last turn. In this case, last turn is defined as before the last user request (e.g. if there is half a turn, it just removes that half).
This can be useful when an attack strategy requires back tracking the last prompt/response pair.
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation ID with existing conversations. |
attack_result_id | str | None | Destination owner. Defaults to the source owner. |
Returns:
str— The uuid for the new conversation.
duplicate_messages¶
duplicate_messages(messages: Sequence[Message]) → tuple[str, Sequence[MessagePiece]]This synchronous API is deprecated and can block the caller.
Returns:
tuple[str, Sequence[MessagePiece]]— tuple[str, Sequence[MessagePiece]]: The operation result.
duplicate_messages_async¶
duplicate_messages_async(messages: Sequence[Message]) → tuple[str, Sequence[MessagePiece]]Duplicate messages with a new conversation ID.
Each duplicated piece gets a fresh id and timestamp while
preserving original_prompt_id for tracking lineage.
| Parameter | Type | Description |
|---|---|---|
messages | Sequence[Message] | The messages to duplicate. |
Returns:
tuple[str, Sequence[MessagePiece]]— Tuple of (new_conversation_id, duplicated_message_pieces).
enable_embedding¶
enable_embedding(embedding_model: Any | None = None) → NoneEnable embedding functionality for the memory interface.
| Parameter | Type | Description |
|---|---|---|
embedding_model | Any | None | Optional embedding model to use. If not provided, attempts to create a default embedding model from environment variables. Defaults to None. |
Raises:
ValueError— If no embedding model is provided and required environment variables are not set.
filter_seed_candidates_async¶
filter_seed_candidates_async(seeds: Sequence[Seed[Any]], filters: Mapping[str, Any]) → list[Seed[Any]]Apply the backend’s seed predicates to storage-ready candidates without storing them.
Use prepare_seed_batch_async before this read so storage-derived fields have
the same values as persisted rows.
Returns:
list[Seed[Any]]— list[Seed]: Matching candidates in input order, with their original identities.
Raises:
ValueError— If literal and pattern filters conflict or a pattern has an unpaired escape.
get_all_embeddings¶
get_all_embeddings() → Sequence[EmbeddingDataEntry]This synchronous API is deprecated and can block the caller.
Returns:
Sequence[EmbeddingDataEntry]— Sequence[EmbeddingDataEntry]: The operation result.
get_all_embeddings_async¶
get_all_embeddings_async() → Sequence[EmbeddingDataEntry]Load all EmbeddingData from the memory storage handler.
Returns:
Sequence[EmbeddingDataEntry]— Sequence[EmbeddingDataEntry]: All stored embedding entries.
get_atomic_attack_identifiers¶
get_atomic_attack_identifiers(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, attack_technique_identifier_hash: str | None = None) → Sequence[AtomicAttackIdentifier]Use get_atomic_attack_identifiers_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[AtomicAttackIdentifier]— Sequence[AtomicAttackIdentifier]: The operation result.
get_atomic_attack_identifiers_async¶
get_atomic_attack_identifiers_async(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, attack_technique_identifier_hash: str | None = None) → Sequence[AtomicAttackIdentifier]Retrieve atomic attack identifiers using exact normalized-column filters.
| Parameter | Type | Description |
|---|---|---|
identifier_hashes | Sequence[str] | None | Content hashes to include. Defaults to None. |
class_name | str | None | Component class name to match. Defaults to None. |
attack_technique_identifier_hash | str | None | Attack technique hash to match. Defaults to None. |
Returns:
Sequence[AtomicAttackIdentifier]— Sequence[AtomicAttackIdentifier]: Matching identifiers ordered by content hash.
get_attack_conversation_page_async¶
get_attack_conversation_page_async(attack_result_id: str, offset: int = 0, limit: int = 50, conversation_id: str | None = None) → AttackConversationPage | NoneRead one bounded page of stored main and pruned conversation references.
Returns:
AttackConversationPage | None— AttackConversationPage | None: Saved references and ordering revision, or an absent attack.
get_attack_identifiers¶
get_attack_identifiers(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, adversarial_system_prompt: str | None = None, adversarial_seed_prompt: str | None = None, objective_target_hash: str | None = None, adversarial_chat_hash: str | None = None, objective_scorer_hash: str | None = None) → Sequence[AttackIdentifier]Use get_attack_identifiers_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[AttackIdentifier]— Sequence[AttackIdentifier]: The operation result.
get_attack_identifiers_async¶
get_attack_identifiers_async(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, adversarial_system_prompt: str | None = None, adversarial_seed_prompt: str | None = None, objective_target_hash: str | None = None, adversarial_chat_hash: str | None = None, objective_scorer_hash: str | None = None) → Sequence[AttackIdentifier]Retrieve attack identifiers using exact normalized-column filters.
| Parameter | Type | Description |
|---|---|---|
identifier_hashes | Sequence[str] | None | Content hashes to include. Defaults to None. |
class_name | str | None | Component class name to match. Defaults to None. |
adversarial_system_prompt | str | None | Adversarial system prompt to match. Defaults to None. |
adversarial_seed_prompt | str | None | Adversarial seed prompt to match. Defaults to None. |
objective_target_hash | str | None | Objective target hash to match. Defaults to None. |
adversarial_chat_hash | str | None | Adversarial chat target hash to match. Defaults to None. |
objective_scorer_hash | str | None | Objective scorer hash to match. Defaults to None. |
Returns:
Sequence[AttackIdentifier]— Sequence[AttackIdentifier]: Matching identifiers ordered by content hash.
get_attack_result_conversations_async¶
get_attack_result_conversations_async(attack_result_id: str) → list[Conversation]Read the conversations owned by one attack execution.
These include its objective conversation and any adversarial, scoring, converter and branch conversations created while it ran. A child attack’s conversations belong to the child’s result.
| Parameter | Type | Description |
|---|---|---|
attack_result_id | str | The ID of the attack result the execution produced. |
Returns:
list[Conversation]— The owned conversations’ metadata, ordered by conversation ID.
get_attack_result_for_conversation_async¶
get_attack_result_for_conversation_async(conversation_id: str) → AttackResult | NoneRead the newest result that references a main or pruned conversation.
This also works for upgraded history without a conversation-to-attack link. Internal conversation references are not included.
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation ID to resolve. |
Returns:
AttackResult | None— AttackResult | None: The newest referring result, or None if none exists.
get_attack_results¶
get_attack_results(attack_result_ids: Sequence[str] | None = None, conversation_id: str | None = None, objective: str | None = None, objective_pattern: str | None = None, objective_sha256: Sequence[str] | None = None, outcome: str | None = None, attack_classes: Sequence[str] | None = None, atomic_attack_eval_hashes: Sequence[str] | None = None, converter_classes: Sequence[str] | None = None, converter_classes_match: Literal['all', 'any'] = 'all', has_converters: bool | None = None, include_scenario_attacks: bool = True, labels: Mapping[str, str | Sequence[str]] | None = None, operator: str | Sequence[str] | None = None, operation: str | Sequence[str] | None = None, operation_ids: Sequence[uuid.UUID] | None = None, targeted_harm_categories: Sequence[str] | None = None, identifier_filters: Sequence[IdentifierFilter] | None = None, scenario_result_id: str | None = None, result_selection: AttackResultSelection = AttackResultSelection.LATEST_PER_CONVERSATION, min_turns: int | None = None, max_turns: int | None = None, limit: int | None = None, after: AttackResultKeysetCursor | None = None) → Sequence[AttackResult]This synchronous API is deprecated and can block the caller.
Returns:
Sequence[AttackResult]— Sequence[AttackResult]: The operation result.
get_attack_results_async¶
get_attack_results_async(attack_result_ids: Sequence[str] | None = None, conversation_id: str | None = None, objective: str | None = None, objective_pattern: str | None = None, objective_sha256: Sequence[str] | None = None, outcome: str | None = None, attack_classes: Sequence[str] | None = None, atomic_attack_eval_hashes: Sequence[str] | None = None, converter_classes: Sequence[str] | None = None, converter_classes_match: Literal['all', 'any'] = 'all', has_converters: bool | None = None, include_scenario_attacks: bool = True, labels: Mapping[str, str | Sequence[str]] | None = None, operator: str | Sequence[str] | None = None, operation: str | Sequence[str] | None = None, operation_ids: Sequence[uuid.UUID] | None = None, targeted_harm_categories: Sequence[str] | None = None, identifier_filters: Sequence[IdentifierFilter] | None = None, scenario_result_id: str | None = None, result_selection: AttackResultSelection = AttackResultSelection.LATEST_PER_CONVERSATION, min_turns: int | None = None, max_turns: int | None = None, limit: int | None = None, after: AttackResultKeysetCursor | None = None) → Sequence[AttackResult]Retrieve a list of AttackResult objects based on the specified filters.
| Parameter | Type | Description |
|---|---|---|
attack_result_ids | Sequence[str] | None | A list of attack result IDs. Defaults to None. |
conversation_id | str | None | The conversation ID to filter by. Defaults to None. |
objective | str | None | Case-insensitive literal objective substring. Defaults to None. |
objective_pattern | str | None | Full case-insensitive LIKE pattern. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
objective_sha256 | Sequence[str] | None | A list of objective SHA256 hashes to filter by. Defaults to None. |
outcome | str | None | The outcome to filter by (success, failure, undetermined). Defaults to None. |
attack_classes | Sequence[str] | None | Filter by exact attack class_name in atomic_attack_identifier. Returns attacks matching ANY of the listed class names (OR logic, case-sensitive). An empty sequence applies no filter. Defaults to None. |
atomic_attack_eval_hashes | Sequence[str] | None | Filter by behavioral equivalence hash on atomic_attack_identifier.eval_hash (auto-stamped on persistence by AtomicAttackEvaluationIdentifier). Returns results matching ANY of the listed hashes (OR logic, case-sensitive). Designed for ASR aggregation by technique configuration. An empty sequence applies no filter. Defaults to None. |
converter_classes | Sequence[str] | None | Filter by converter class names. Combination semantics for multiple entries are controlled by converter_classes_match. An empty sequence filters to attacks that used no converters; None applies no filter. To filter by presence/absence of any converter explicitly, use the has_converters parameter instead. Defaults to None. |
converter_classes_match | Literal['all', 'any'] | How to combine multiple entries in converter_classes. "all" (default) matches attacks that used every listed converter (AND, case-insensitive). "any" matches attacks that used at least one listed converter (OR, case-insensitive). Ignored when converter_classes has fewer than 2 entries or is empty. |
has_converters | bool | None | Filter by converter presence. True returns only attacks that used at least one converter. False returns only attacks that used no converters. None applies no filter. Defaults to None. |
include_scenario_attacks | bool | Whether to include attacks created as part of scenario runs. Defaults to True. |
labels | Mapping[str, str | Sequence[str]] | None | Filter results by arbitrary attack labels. The legacy operator and operation aliases are accepted through PyRIT 1.3 and normalized to dedicated filters. Entries are AND-combined across label names; within a single entry, a string value is an equality match and a sequence value is an OR match over the listed values. An empty sequence applies no filter for that label. Defaults to None. |
operator | str | Sequence[str] | None | Filter by dedicated operator values. Defaults to None. |
operation | str | Sequence[str] | None | Filter by dedicated operation values. Defaults to None. |
operation_ids | Sequence[uuid.UUID] | None | Filter by saved Operation IDs. Legacy rows that only carry an operation name never match. Defaults to None. |
targeted_harm_categories | Sequence[str] | None | Filter results by the harm categories targeted by the attack (stored on AttackResultEntry.targeted_harm_categories, auto-populated from the attack’s SeedGroup). Returns attacks targeting ANY of the listed categories (OR logic, case-insensitive). An empty sequence applies no filter. Defaults to None. |
identifier_filters | Sequence[IdentifierFilter] | None | A sequence of IdentifierFilter objects that allows filtering by various attack identifier JSON properties. Defaults to None. |
scenario_result_id | str | None | Filter to attack results linked to a specific scenario via the AttackResultEntry.attribution_parent_id foreign key. Combined with outcome=AttackOutcome.ERROR this is the replacement for the removed per-scenario error_attack_result_ids manifest. Defaults to None. |
result_selection | AttackResultSelection | Return each distinct saved result ID with ALL_RESULTS, or the newest matching result per conversation with LATEST_PER_CONVERSATION. The default preserves existing callers. Defaults to AttackResultSelection.LATEST_PER_CONVERSATION. |
min_turns | int | None | If set, only return attacks whose executed_turns is greater than or equal to this value. Applied after result selection, so the latest-per-conversation mode never resurfaces an older duplicate. Defaults to None. |
max_turns | int | None | If set, only return attacks whose executed_turns is less than or equal to this value. Applied after result selection, mirroring min_turns. Defaults to None. |
limit | int | None | Maximum number of selected attack results to return, ordered by recency. When either limit or after is provided, selection and pagination happen in the database; only LATEST_PER_CONVERSATION uses a NOT EXISTS anti-join. Defaults to None. |
after | AttackResultKeysetCursor | None | Keyset (seek) anchor from a previous page. When provided, only results ordered strictly after the anchor under the recency sort are returned, giving insert/delete-stable pagination without a drifting numeric offset. Defaults to None (start at the first page). |
Returns:
Sequence[AttackResult]— Sequence[AttackResult]: A list of AttackResult objects that match the specified filters.
Raises:
ValueError— Ifresult_selectionis not a supported selection mode.ValueError— If any label key contains characters outside the allowlist[A-Za-z0-9_.-]+.ValueError— Iflimitorafteris combined withattack_result_idsorobjective_sha256(id-batched lookups do not support SQL pagination).
get_attack_technique_identifiers¶
get_attack_technique_identifiers(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, attack_identifier_hash: str | None = None) → Sequence[AttackTechniqueIdentifier]Use get_attack_technique_identifiers_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[AttackTechniqueIdentifier]— Sequence[AttackTechniqueIdentifier]: The operation result.
get_attack_technique_identifiers_async¶
get_attack_technique_identifiers_async(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, attack_identifier_hash: str | None = None) → Sequence[AttackTechniqueIdentifier]Retrieve attack technique identifiers using exact normalized-column filters.
| Parameter | Type | Description |
|---|---|---|
identifier_hashes | Sequence[str] | None | Content hashes to include. Defaults to None. |
class_name | str | None | Component class name to match. Defaults to None. |
attack_identifier_hash | str | None | Attack identifier hash to match. Defaults to None. |
Returns:
Sequence[AttackTechniqueIdentifier]— Sequence[AttackTechniqueIdentifier]: Matching identifiers ordered by content hash.
get_conversation_message_page_async¶
get_conversation_message_page_async(conversation_id: str, cursor: MessagePieceKeysetCursor | None = None, limit: int = 100) → ConversationMessagePageRead canonical saved messages with continuation through every message piece.
Returns:
ConversationMessagePage— One bounded piece page grouped into canonical messages.
get_conversation_messages¶
get_conversation_messages(conversation_id: str) → MutableSequence[Message]Use get_conversation_messages_async.
This synchronous API is deprecated and can block the caller.
Returns:
MutableSequence[Message]— MutableSequence[Message]: The operation result.
get_conversation_messages_async¶
get_conversation_messages_async(conversation_id: str) → MutableSequence[Message]Retrieve a list of Message objects that have the specified conversation ID.
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation ID to match. |
Returns:
MutableSequence[Message]— MutableSequence[Message]: A list of chat memory entries with the specified conversation ID.
Raises:
ValueError— If conversation_id is empty or None. A falsy id would cause the underlying get_message_pieces filter to be skipped, silently returning pieces from every conversation in memory.
get_conversation_metadata_async¶
get_conversation_metadata_async(conversation_id: str) → Conversation | NoneRead the stored metadata for one conversation.
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation to look up. |
Returns:
Conversation | None— Conversation metadata, or None if the conversation is not stored.
get_conversation_stats¶
get_conversation_stats(conversation_ids: Sequence[str]) → dict[str, ConversationStats]Use get_conversation_stats_async.
This synchronous API is deprecated and can block the caller.
Returns:
dict[str, ConversationStats]— dict[str, ‘ConversationStats’]: The operation result.
get_conversation_stats_async¶
get_conversation_stats_async(conversation_ids: Sequence[str]) → dict[str, ConversationStats]Return lightweight aggregate statistics for one or more conversations.
Computes per-conversation message count (distinct sequence numbers), a truncated last-message preview, the first non-empty labels dict, and the earliest message timestamp (timezone-aware UTC) using efficient SQL aggregation instead of loading full pieces.
| Parameter | Type | Description |
|---|---|---|
conversation_ids | Sequence[str] | The conversation IDs to query. |
Returns:
dict[str, ConversationStats]— Mapping from conversation_id to ConversationStats.dict[str, ConversationStats]— Conversations with no pieces are omitted from the result.
get_converter_identifiers¶
get_converter_identifiers(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, supported_input_types: Sequence[str] | None = None, supported_output_types: Sequence[str] | None = None, converter_target_hash: str | None = None, sub_converter_hash: str | None = None) → Sequence[ConverterIdentifier]Use get_converter_identifiers_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[ConverterIdentifier]— Sequence[ConverterIdentifier]: The operation result.
get_converter_identifiers_async¶
get_converter_identifiers_async(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, supported_input_types: Sequence[str] | None = None, supported_output_types: Sequence[str] | None = None, converter_target_hash: str | None = None, sub_converter_hash: str | None = None) → Sequence[ConverterIdentifier]Retrieve converter identifiers using exact normalized-column filters.
| Parameter | Type | Description |
|---|---|---|
identifier_hashes | Sequence[str] | None | Content hashes to include. Defaults to None. |
class_name | str | None | Component class name to match. Defaults to None. |
supported_input_types | Sequence[str] | None | Input types to match exactly, in any order. Defaults to None. |
supported_output_types | Sequence[str] | None | Output types to match exactly, in any order. Defaults to None. |
converter_target_hash | str | None | Converter target hash to match. Defaults to None. |
sub_converter_hash | str | None | Nested converter hash to match. Defaults to None. |
Returns:
Sequence[ConverterIdentifier]— Sequence[ConverterIdentifier]: Matching identifiers ordered by content hash.
get_dataset_editing_snapshot_async¶
get_dataset_editing_snapshot_async(dataset_name: str) → DatasetEditingSnapshotRead records and a complete content token from one participating-writer snapshot.
Returns:
DatasetEditingSnapshot— Inert records and their content token.
get_finding_async¶
get_finding_async(operation_id: uuid.UUID, finding_id: uuid.UUID) → Finding | NoneRead a finding only within its owning operation.
Returns:
Finding | None— Finding | None: The matching finding, if present.
get_finding_child_counts_async¶
get_finding_child_counts_async(finding_ids: Sequence[uuid.UUID]) → dict[uuid.UUID, int]Count the direct sub-findings of several findings.
Returns:
dict[uuid.UUID, int]— dict[uuid.UUID, int]: Counts for findings that have sub-findings.
get_finding_evidence_async¶
get_finding_evidence_async(finding_id: uuid.UUID, limit: int, offset: int) → list[FindingEvidence]Read one page of a finding’s evidence, most recently linked first.
Returns:
list[FindingEvidence]— list[FindingEvidence]: The evidence on the page.
Raises:
ValueError— If the page bounds are invalid.
get_finding_evidence_by_source_async¶
get_finding_evidence_by_source_async(finding_id: uuid.UUID, attack_result_id: uuid.UUID) → FindingEvidence | NoneRead the evidence linking a finding to a saved attack result.
Returns:
FindingEvidence | None— FindingEvidence | None: The evidence, if linked.
get_finding_evidence_counts_async¶
get_finding_evidence_counts_async(finding_ids: Sequence[uuid.UUID]) → dict[uuid.UUID, int]Count evidence for several findings in one query.
Returns:
dict[uuid.UUID, int]— dict[uuid.UUID, int]: Counts for findings that have evidence.
get_finding_evidence_for_findings_async¶
get_finding_evidence_for_findings_async(finding_ids: Sequence[uuid.UUID]) → dict[uuid.UUID, list[FindingEvidence]]Read all evidence of several findings, most recently linked first.
Returns:
dict[uuid.UUID, list[FindingEvidence]]— dict[uuid.UUID, list[FindingEvidence]]: Evidence for findings that have evidence.
get_finding_severity_counts_async¶
get_finding_severity_counts_async() → dict[uuid.UUID, dict[str, int]]Count every operation’s findings by severity in one query.
Returns:
dict[uuid.UUID, dict[str, int]]— dict[uuid.UUID, dict[str, int]]: Counts for operations with findings.
get_finding_subtrees_async¶
get_finding_subtrees_async(operation_id: uuid.UUID, finding_ids: Sequence[uuid.UUID], severity_order: Sequence[str] = _DEFAULT_SEVERITY_ORDER) → list[Finding]Read findings of one operation together with all of their sub-findings, at any depth.
Membership, parents, and paths come from one transaction that holds the operation’s finding lock, which every finding change takes, so a concurrent change lands wholly before or after this read and every path step is in the result.
IDs that are not in the operation are omitted.
| Parameter | Type | Description |
|---|---|---|
operation_id | uuid.UUID | The operation whose findings to read. |
finding_ids | Sequence[uuid.UUID] | The findings whose subtrees to read. |
severity_order | Sequence[str] | Severity keys from highest to lowest, as for get_findings_async. Defaults to the default finding fields’ order. |
Returns:
list[Finding]— list[Finding]: Each finding once, in the same order asget_findings_async.
get_findings_async¶
get_findings_async(operation_id: uuid.UUID | None = None, limit: int = 20, offset: int = 0, title_query: str | None = None, severity_order: Sequence[str] = _DEFAULT_SEVERITY_ORDER, title_pattern: str | None = None, parent_finding_id: uuid.UUID | None = None, top_level_only: bool = False) → list[Finding]Read one page of findings in severity_order, then newest first.
Without a parent or top-level filter, every finding is listed, including sub-findings. A parent’s direct sub-findings are listed oldest first instead, the order a decomposition is usually written in.
| Parameter | Type | Description |
|---|---|---|
operation_id | uuid.UUID | None | The operation whose findings to read. Defaults to None, which reads findings from every operation. |
limit | int | Maximum number of findings to return. Defaults to 20. |
offset | int | Number of findings to skip. Defaults to 0. |
title_query | str | None | Case-insensitive text the title must contain. Wildcard characters match literally. Defaults to None. |
severity_order | Sequence[str] | Severity keys from highest to lowest. Stored values that aren’t listed sort after them. Defaults to the default finding fields’ order, as in PyRIT 1.2. An empty order sorts newest first. |
title_pattern | str | None | Full LIKE pattern instead of title_query. Defaults to None. |
parent_finding_id | uuid.UUID | None | Only the direct sub-findings of this finding, oldest first. Defaults to None. |
top_level_only | bool | Only findings without a parent. Defaults to False. |
Returns:
list[Finding]— list[Finding]: The findings on the page.
Raises:
ValueError— If the page bounds or pattern are invalid, both title filters are supplied, or both a parent and the top level are requested.
get_findings_by_ids_async¶
get_findings_by_ids_async(operation_id: uuid.UUID, finding_ids: Sequence[uuid.UUID], severity_order: Sequence[str] = _DEFAULT_SEVERITY_ORDER) → list[Finding]Read selected findings of one operation in severity_order, then newest first.
IDs that are not in the operation are omitted.
| Parameter | Type | Description |
|---|---|---|
operation_id | uuid.UUID | The operation whose findings to read. |
finding_ids | Sequence[uuid.UUID] | The findings to read. |
severity_order | Sequence[str] | Severity keys from highest to lowest, as for get_findings_async. Defaults to the default finding fields’ order. |
Returns:
list[Finding]— list[Finding]: The selected findings, in the same order asget_findings_async.
get_findings_for_attack_result_async¶
get_findings_for_attack_result_async(attack_result_id: uuid.UUID, severity_order: Sequence[str] = _DEFAULT_SEVERITY_ORDER) → list[tuple[Finding, FindingEvidence]]Read every finding that links an attack result as evidence, in severity_order, then newest first.
| Parameter | Type | Description |
|---|---|---|
attack_result_id | uuid.UUID | The attack result the findings link as evidence. |
severity_order | Sequence[str] | Severity keys from highest to lowest, as for get_findings_async. Defaults to the default finding fields’ order. |
Returns:
list[tuple[Finding, FindingEvidence]]— list[tuple[Finding, FindingEvidence]]: Each linked finding with the evidence that links it.
get_message_pieces¶
get_message_pieces(role: str | None = None, conversation_id: str | uuid.UUID | None = None, prompt_ids: Sequence[str | uuid.UUID] | None = None, labels: dict[str, str] | None = None, prompt_metadata: dict[str, str | int] | None = None, sent_after: datetime | None = None, sent_before: datetime | None = None, original_values: Sequence[str] | None = None, converted_values: Sequence[str] | None = None, data_type: str | None = None, not_data_type: str | None = None, converted_value_sha256: Sequence[str] | None = None, identifier_filters: Sequence[IdentifierFilter] | None = None, attack_result_id: str | None = None) → Sequence[MessagePiece]This synchronous API is deprecated and can block the caller.
Returns:
Sequence[MessagePiece]— Sequence[MessagePiece]: The operation result.
get_message_pieces_async¶
get_message_pieces_async(role: str | None = None, conversation_id: str | uuid.UUID | None = None, prompt_ids: Sequence[str | uuid.UUID] | None = None, labels: dict[str, str] | None = None, prompt_metadata: dict[str, str | int] | None = None, sent_after: datetime | None = None, sent_before: datetime | None = None, original_values: Sequence[str] | None = None, converted_values: Sequence[str] | None = None, data_type: str | None = None, not_data_type: str | None = None, converted_value_sha256: Sequence[str] | None = None, identifier_filters: Sequence[IdentifierFilter] | None = None, attack_result_id: str | None = None) → Sequence[MessagePiece]Retrieve a list of MessagePiece objects based on the specified filters.
| Parameter | Type | Description |
|---|---|---|
role | str | None | The role of the prompt. Defaults to None. |
conversation_id | str | uuid.UUID | None | The ID of the conversation. Defaults to None. |
prompt_ids | Sequence[str] | Sequence[uuid.UUID] | None | A list of prompt IDs. Defaults to None. |
labels | dict[str, str] | None | Deprecated. Labels live on attack results, so query get_attack_results_async(labels=...) and fetch their conversations instead. Defaults to None. |
prompt_metadata | dict[str, str | int] | None | The metadata associated with the prompt. Defaults to None. |
sent_after | datetime | None | Filter for prompts sent after this datetime. Defaults to None. |
sent_before | datetime | None | Filter for prompts sent before this datetime. Defaults to None. |
original_values | Sequence[str] | None | A list of original values. Defaults to None. |
converted_values | Sequence[str] | None | A list of converted values. Defaults to None. |
data_type | str | None | The data type to filter by. Defaults to None. |
not_data_type | str | None | The data type to exclude. Defaults to None. |
converted_value_sha256 | Sequence[str] | None | A list of SHA256 hashes of converted values. Defaults to None. |
identifier_filters | Sequence[IdentifierFilter] | None | A sequence of IdentifierFilter objects that allow filtering by various identifier JSON properties. Defaults to None. |
attack_result_id | str | None | Only return pieces from conversations owned by the attack execution that produced this result. Defaults to None. |
Returns:
Sequence[MessagePiece]— Sequence[MessagePiece]: A list of MessagePiece objects that match the specified filters.
Raises:
Exception— If there is an error retrieving the prompts, an exception is logged and an empty list is returned.
get_observations¶
get_observations(observation_ids: Sequence[uuid.UUID | str]) → list[Observation]This synchronous API is deprecated and can block the caller.
Returns:
list[Observation]— list[Observation]: The operation result.
get_observations_async¶
get_observations_async(observation_ids: Sequence[uuid.UUID | str]) → list[Observation]Load observations by ID.
| Parameter | Type | Description |
|---|---|---|
observation_ids | Sequence[uuid.UUID | str] | Observation IDs to load. |
Returns:
list[Observation]— list[Observation]: Stored observations in the requested order. Missing IDs are omitted.
get_operation_usage_async¶
get_operation_usage_async(operation_id: uuid.UUID) → OperationUsageCount the findings, attacks, and scenario runs that refer to an Operation by ID, in one indexed query.
Returns:
OperationUsage— The counts, which are all zero for an unknown ID.
get_operations_async¶
get_operations_async(operation_ids: Sequence[uuid.UUID] | None = None, name: str | None = None) → list[Operation]Read operations ordered by name, optionally matching IDs or a name regardless of case and spacing.
Returns:
list[Operation]— list[Operation]: The matching operations.
get_planned_seed_groups_async¶
get_planned_seed_groups_async(scenario_result_id: str) → dict[str, list[AttackSeedGroup]]Return the seed groups a scenario run planned, as stored when the run was created.
| Parameter | Type | Description |
|---|---|---|
scenario_result_id | str | The scenario result ID. |
Returns:
dict[str, list[AttackSeedGroup]]— dict[str, list[AttackSeedGroup]]: The planned population by dataset name, in planned order. Empty when the run planned no groups or was created before they were stored.
get_prompt_generation_async¶
get_prompt_generation_async(generation_id: uuid.UUID) → PromptGenerationRecord | NoneRead one prompt generation.
| Parameter | Type | Description |
|---|---|---|
generation_id | uuid.UUID | The generation to read. |
Returns:
PromptGenerationRecord | None— PromptGenerationRecord | None: The generation, or None if it doesn’t exist.
get_prompt_generations_async¶
get_prompt_generations_async() → list[PromptGenerationRecord]Read every prompt generation, newest first.
Generations created at the same time, such as the members of one batch, keep their batch order: by batch position, first member first, and then by ID.
Returns:
list[PromptGenerationRecord]— list[PromptGenerationRecord]: The generations.
get_prompt_scores¶
get_prompt_scores(role: str | None = None, conversation_id: str | uuid.UUID | None = None, prompt_ids: Sequence[str | uuid.UUID] | None = None, labels: dict[str, str] | None = None, prompt_metadata: dict[str, str | int] | None = None, sent_after: datetime | None = None, sent_before: datetime | None = None, original_values: Sequence[str] | None = None, converted_values: Sequence[str] | None = None, data_type: str | None = None, not_data_type: str | None = None, converted_value_sha256: Sequence[str] | None = None, include_intermediate: bool = False) → Sequence[Score]This synchronous API is deprecated and can block the caller.
Returns:
Sequence[Score]— Sequence[Score]: The operation result.
get_prompt_scores_async¶
get_prompt_scores_async(role: str | None = None, conversation_id: str | uuid.UUID | None = None, prompt_ids: Sequence[str | uuid.UUID] | None = None, labels: dict[str, str] | None = None, prompt_metadata: dict[str, str | int] | None = None, sent_after: datetime | None = None, sent_before: datetime | None = None, original_values: Sequence[str] | None = None, converted_values: Sequence[str] | None = None, data_type: str | None = None, not_data_type: str | None = None, converted_value_sha256: Sequence[str] | None = None, include_intermediate: bool = False) → Sequence[Score]Retrieve scores attached to message pieces based on the specified filters.
| Parameter | Type | Description |
|---|---|---|
role | str | None | The role of the prompt. Defaults to None. |
conversation_id | str | uuid.UUID | None | The ID of the conversation. Defaults to None. |
prompt_ids | Sequence[str] | Sequence[uuid.UUID] | None | A list of prompt IDs. Defaults to None. |
labels | dict[str, str] | None | Deprecated. Labels live on attack results, so query get_attack_results_async(labels=...) and fetch their conversations instead. Defaults to None. |
prompt_metadata | dict[str, str | int] | None | The metadata associated with the prompt. Defaults to None. |
sent_after | datetime | None | Filter for prompts sent after this datetime. Defaults to None. |
sent_before | datetime | None | Filter for prompts sent before this datetime. Defaults to None. |
original_values | Sequence[str] | None | A list of original values. Defaults to None. |
converted_values | Sequence[str] | None | A list of converted values. Defaults to None. |
data_type | str | None | The data type to filter by. Defaults to None. |
not_data_type | str | None | The data type to exclude. Defaults to None. |
converted_value_sha256 | Sequence[str] | None | A list of SHA256 hashes of converted values. Defaults to None. |
include_intermediate | bool | Include nested judgments instead of only public root results. Defaults to False. |
Returns:
Sequence[Score]— Sequence[Score]: A list of scores extracted from the message pieces.
get_request_from_response¶
get_request_from_response(response: Message) → MessageUse get_request_from_response_async.
This synchronous API is deprecated and can block the caller.
Returns:
Message— The operation result.
get_request_from_response_async¶
get_request_from_response_async(response: Message) → MessageRetrieve the request that produced the given response.
Returns the latest preceding outbound request of any role, skipping target-generated tool messages. For unmarked history, returns the last user message or, if absent, the immediately preceding message.
| Parameter | Type | Description |
|---|---|---|
response | Message | The response message object to match. |
Returns:
Message— The corresponding message object.
Raises:
ValueError— If the response is not from an assistant role or has no preceding request.
get_scenario_attack_result_deltas¶
get_scenario_attack_result_deltas(scenario_result_id: str, cursor: AttackResultKeysetCursor | None = None, limit: int = 100) → tuple[list[ScenarioAttackResultDelta], bool]Use get_scenario_attack_result_deltas_async.
This synchronous API is deprecated and can block the caller.
Returns:
tuple[list[ScenarioAttackResultDelta], bool]— tuple[list[ScenarioAttackResultDelta], bool]: The operation result.
get_scenario_attack_result_deltas_async¶
get_scenario_attack_result_deltas_async(scenario_result_id: str, cursor: AttackResultKeysetCursor | None = None, limit: int = 100) → tuple[list[ScenarioAttackResultDelta], bool]Return bounded scenario-linked result deltas in ascending keyset order.
This projection selects only progress fields and the linked objective score. It never hydrates ORM relationships, prompt rows, or a full ScenarioResult.
Returns:
tuple[list[ScenarioAttackResultDelta], bool]— tuple[list[ScenarioAttackResultDelta], bool]: The page and whether more rows exist.
Raises:
ValueError— If the limit or cursor identifiers are invalid.
get_scenario_attack_result_deltas_by_ids_async¶
get_scenario_attack_result_deltas_by_ids_async(scenario_result_id: str, attack_result_ids: Sequence[str]) → list[ScenarioAttackResultDelta]Return lightweight scenario-linked result deltas for specific attack results in a single query.
Ensures child results belonging to other scenarios or non-existent IDs are isolated safely.
| Parameter | Type | Description |
|---|---|---|
scenario_result_id | str | The ID of the scenario run. |
attack_result_ids | Sequence[str] | Sequence of attack result IDs to retrieve. |
Returns:
list[ScenarioAttackResultDelta]— list[ScenarioAttackResultDelta]: The matched deltas.
get_scenario_history_aggregates¶
get_scenario_history_aggregates(scenario_result_ids: Sequence[str], plan_scenario_ids: Sequence[str] = ()) → dict[str, ScenarioHistoryAggregate]Use get_scenario_history_aggregates_async.
This synchronous API is deprecated and can block the caller.
Returns:
dict[str, ScenarioHistoryAggregate]— dict[str, ScenarioHistoryAggregate]: The operation result.
get_scenario_history_aggregates_async¶
get_scenario_history_aggregates_async(scenario_result_ids: Sequence[str], plan_scenario_ids: Sequence[str] = ()) → dict[str, ScenarioHistoryAggregate]Return one attempt aggregate per requested scenario run.
Persisted attempts are grouped into logical work units before being counted, so
retries and errored re-runs of the same objective collapse into a single unit.
For every scenario listed in plan_scenario_ids the persisted run plan resolves
those units: attempts are matched to their planned atomic group and seed group
(remapping objective-hash attribution onto the planned seed group ID), and attempts
that resolve to no planned unit are excluded from the counters. Scenarios outside
plan_scenario_ids keep the persisted attribution as the unit identity and count
every unit, which is the legacy behavior for runs without a usable plan.
| Parameter | Type | Description |
|---|---|---|
scenario_result_ids | Sequence[str] | Scenario run IDs to aggregate. |
plan_scenario_ids | Sequence[str] | Subset of scenario_result_ids whose persisted run plan should resolve and filter units. Defaults to (). |
Returns:
dict[str, ScenarioHistoryAggregate]— dict[str, ScenarioHistoryAggregate]: One aggregate per requested scenario ID.
get_scenario_identifiers¶
get_scenario_identifiers(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, version: int | None = None, techniques: Sequence[str] | None = None, datasets: Sequence[str] | None = None, objective_target_hash: str | None = None, objective_scorer_hash: str | None = None) → Sequence[ScenarioIdentifier]Use get_scenario_identifiers_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[ScenarioIdentifier]— Sequence[ScenarioIdentifier]: The operation result.
get_scenario_identifiers_async¶
get_scenario_identifiers_async(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, version: int | None = None, techniques: Sequence[str] | None = None, datasets: Sequence[str] | None = None, objective_target_hash: str | None = None, objective_scorer_hash: str | None = None) → Sequence[ScenarioIdentifier]Retrieve scenario identifiers using exact normalized-column filters.
| Parameter | Type | Description |
|---|---|---|
identifier_hashes | Sequence[str] | None | Content hashes to include. Defaults to None. |
class_name | str | None | Component class name to match. Defaults to None. |
version | int | None | Scenario definition version to match. Defaults to None. |
techniques | Sequence[str] | None | Technique names to match exactly, in any order. Defaults to None. |
datasets | Sequence[str] | None | Dataset names to match exactly, in any order. Defaults to None. |
objective_target_hash | str | None | Objective target hash to match. Defaults to None. |
objective_scorer_hash | str | None | Objective scorer hash to match. Defaults to None. |
Returns:
Sequence[ScenarioIdentifier]— Sequence[ScenarioIdentifier]: Matching identifiers ordered by content hash.
get_scenario_recount_summaries_async¶
get_scenario_recount_summaries_async(scenario_result_id: str, cursor: AttackResultKeysetCursor | None = None, limit: int = 500) → tuple[list[ScenarioAttemptSeedSummary], bool]Return bounded scenario attempt seed summaries in ascending keyset order for recount.
This projection selects only the minimal scalar fields needed for execution-unit matching and recount metrics. Never loads scores, prompt entries, retry events, or large conversation payloads.
Returns:
tuple[list[ScenarioAttemptSeedSummary], bool]— tuple[list[ScenarioAttemptSeedSummary], bool]: The page and whether more rows exist.
Raises:
ValueError— If the limit is invalid.
get_scenario_result_header¶
get_scenario_result_header(scenario_result_id: str) → ScenarioResult | NoneUse get_scenario_result_header_async.
This synchronous API is deprecated and can block the caller.
Returns:
ScenarioResult | None— ScenarioResult | None: The operation result.
get_scenario_result_header_async¶
get_scenario_result_header_async(scenario_result_id: str) → ScenarioResult | NoneReturn one ScenarioResult header without hydrating linked attack results.
get_scenario_results¶
get_scenario_results(scenario_result_ids: Sequence[str] | None = None, scenario_name: str | None = None, scenario_name_pattern: str | None = None, scenario_version: int | None = None, pyrit_version: str | None = None, added_after: datetime | None = None, added_before: datetime | None = None, labels: dict[str, str] | None = None, objective_target_endpoint: str | None = None, objective_target_endpoint_pattern: str | None = None, objective_target_model_name: str | None = None, objective_target_model_name_pattern: str | None = None, identifier_filters: Sequence[IdentifierFilter] | None = None, limit: int | None = None) → Sequence[ScenarioResult]Use get_scenario_results_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[ScenarioResult]— Sequence[ScenarioResult]: The operation result.
get_scenario_results_async¶
get_scenario_results_async(scenario_result_ids: Sequence[str] | None = None, scenario_name: str | None = None, scenario_name_pattern: str | None = None, scenario_version: int | None = None, pyrit_version: str | None = None, added_after: datetime | None = None, added_before: datetime | None = None, labels: dict[str, str] | None = None, objective_target_endpoint: str | None = None, objective_target_endpoint_pattern: str | None = None, objective_target_model_name: str | None = None, objective_target_model_name_pattern: str | None = None, identifier_filters: Sequence[IdentifierFilter] | None = None, limit: int | None = None) → Sequence[ScenarioResult]Retrieve a list of ScenarioResult objects based on the specified filters.
Results are always ordered by completion_time descending (most recent first).
| Parameter | Type | Description |
|---|---|---|
scenario_result_ids | Sequence[str] | None | A list of scenario result IDs. Defaults to None. |
scenario_name | str | None | Case-insensitive literal scenario name substring. No alias normalization is applied. Defaults to None. |
scenario_name_pattern | str | None | Full case-insensitive LIKE pattern. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
scenario_version | int | None | The scenario version to filter by. Defaults to None. |
pyrit_version | str | None | The PyRIT version to filter by. Defaults to None. |
added_after | datetime | None | Filter for scenarios completed after this datetime. Defaults to None. |
added_before | datetime | None | Filter for scenarios completed before this datetime. Defaults to None. |
labels | dict[str, str] | None | A dictionary of memory labels to filter by. Defaults to None. |
objective_target_endpoint | str | None | Filter for scenarios where the objective_target_identifier has an endpoint attribute containing this value (case-insensitive). Defaults to None. |
objective_target_endpoint_pattern | str | None | Full case-insensitive LIKE pattern. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
objective_target_model_name | str | None | Filter for scenarios where the objective_target_identifier has a model_name attribute containing this value (case-insensitive). Defaults to None. |
objective_target_model_name_pattern | str | None | Full case-insensitive LIKE pattern. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
identifier_filters | Sequence[IdentifierFilter] | None | A sequence of IdentifierFilter objects that allows filtering by identifier JSON properties. Defaults to None. |
limit | int | None | Maximum number of results to return. Defaults to None (no limit). |
Returns:
Sequence[ScenarioResult]— Sequence[ScenarioResult]: A list of ScenarioResult objects that match the specified filters, ordered by completion_time descending.
get_scenario_root_deltas_async¶
get_scenario_root_deltas_async(scenario_result_id: str, cursor: AttackResultKeysetCursor | None = None, limit: int = 100) → tuple[list[ScenarioAttackResultDelta], bool]Page true run-scoped roots without hydrating progress or discovering ancestors in Python.
Returns:
tuple[list[ScenarioAttackResultDelta], bool]— tuple[list[ScenarioAttackResultDelta], bool]: Root deltas and whether another page exists.
get_scenario_run_history_page¶
get_scenario_run_history_page(scenario_names: Sequence[str] | None = None, statuses: Sequence[str] | None = None, labels: Mapping[str, str | Sequence[str]] | None = None, operation_ids: Sequence[uuid.UUID] | None = None, reference_id: uuid.UUID | None = None, cursor: ScenarioHistoryKeysetCursor | None = None, limit: int = 100, sort_by: Literal['created_at', 'activity'] = 'created_at') → tuple[list[ScenarioHistoryRunRecord], dict[str, ScenarioHistoryAggregate], bool]Use get_scenario_run_history_page_async.
This synchronous API is deprecated and can block the caller.
Returns:
tuple[list[ScenarioHistoryRunRecord], dict[str, ScenarioHistoryAggregate], bool]— tuple[list[ScenarioHistoryRunRecord], dict[str, ScenarioHistoryAggregate], bool]: The operation result.
get_scenario_run_history_page_async¶
get_scenario_run_history_page_async(scenario_names: Sequence[str] | None = None, statuses: Sequence[str] | None = None, labels: Mapping[str, str | Sequence[str]] | None = None, operation_ids: Sequence[uuid.UUID] | None = None, reference_id: uuid.UUID | None = None, cursor: ScenarioHistoryKeysetCursor | None = None, limit: int = 100, sort_by: Literal['created_at', 'activity'] = 'created_at') → tuple[list[ScenarioHistoryRunRecord], dict[str, ScenarioHistoryAggregate], bool]Return one descending scenario-history page and its database-side attempt metrics.
Only selected ScenarioResult columns and the linked AttackResult columns required for aggregate counts are read. Full ORM result objects and their relationships are never hydrated, and attempt metrics are reduced to one aggregate row per history row inside the database.
Returns:
tuple[list[ScenarioHistoryRunRecord], dict[str, ScenarioHistoryAggregate], bool]— tuple[list[ScenarioHistoryRunRecord], dict[str, ScenarioHistoryAggregate], bool]: Page headers, attempt aggregates keyed by scenario ID, and whether another page exists.
Raises:
ValueError— If the limit, cursor ID, sort mode, or label keys are invalid.
get_scenario_run_state_page¶
get_scenario_run_state_page(states: Sequence[ScenarioRunState], after_id: str | None = None, limit: int = 500) → tuple[list[ScenarioRunStateRecord], bool]Use get_scenario_run_state_page_async.
This synchronous API is deprecated and can block the caller.
Returns:
tuple[list[ScenarioRunStateRecord], bool]— tuple[list[ScenarioRunStateRecord], bool]: The operation result.
get_scenario_run_state_page_async¶
get_scenario_run_state_page_async(states: Sequence[ScenarioRunState], after_id: str | None = None, limit: int = 500) → tuple[list[ScenarioRunStateRecord], bool]Return one bounded ID/state page without hydrating ScenarioResults or AttackResults.
Returns:
tuple[list[ScenarioRunStateRecord], bool]— tuple[list[ScenarioRunStateRecord], bool]: State records and whether another page exists.
Raises:
ValueError— If the limit or cursor ID is invalid.
get_scorable_content¶
get_scorable_content(content_ids: Sequence[uuid.UUID | str]) → dict[uuid.UUID, ContentScorable]Use get_scorable_content_async.
This synchronous API is deprecated and can block the caller.
Returns:
dict[uuid.UUID, ContentScorable]— dict[uuid.UUID, ContentScorable]: The operation result.
get_scorable_content_async¶
get_scorable_content_async(content_ids: Sequence[uuid.UUID | str]) → dict[uuid.UUID, ContentScorable]Load the loose content that stored scores are anchored on.
| Parameter | Type | Description |
|---|---|---|
content_ids | Sequence[uuid.UUID | str] | The ids named by ContentEntryScorable anchors. |
Returns:
dict[uuid.UUID, ContentScorable]— dict[uuid.UUID, ContentScorable]: The content by id, omitting ids with no row.
get_scorable_content_hashes¶
get_scorable_content_hashes(content_ids: Sequence[uuid.UUID | str]) → dict[uuid.UUID, str]Use get_scorable_content_hashes_async.
This synchronous API is deprecated and can block the caller.
Returns:
dict[uuid.UUID, str]— dict[uuid.UUID, str]: The operation result.
get_scorable_content_hashes_async¶
get_scorable_content_hashes_async(content_ids: Sequence[uuid.UUID | str]) → dict[uuid.UUID, str]Load the immutable content digest for stored score anchors.
Returns:
dict[uuid.UUID, str]— dict[uuid.UUID, str]: SHA-256 digests by content ID.
get_scorer_identifiers¶
get_scorer_identifiers(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, scorer_type: str | None = None, score_aggregator: str | None = None, prompt_target_hash: str | None = None) → Sequence[ScorerIdentifier]Use get_scorer_identifiers_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[ScorerIdentifier]— Sequence[ScorerIdentifier]: The operation result.
get_scorer_identifiers_async¶
get_scorer_identifiers_async(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, scorer_type: str | None = None, score_aggregator: str | None = None, prompt_target_hash: str | None = None) → Sequence[ScorerIdentifier]Retrieve scorer identifiers using exact normalized-column filters.
| Parameter | Type | Description |
|---|---|---|
identifier_hashes | Sequence[str] | None | Content hashes to include. Defaults to None. |
class_name | str | None | Component class name to match. Defaults to None. |
scorer_type | str | None | Scorer type to match. Defaults to None. |
score_aggregator | str | None | Score aggregator to match. Defaults to None. |
prompt_target_hash | str | None | Scorer target hash to match. Defaults to None. |
Returns:
Sequence[ScorerIdentifier]— Sequence[ScorerIdentifier]: Matching identifiers ordered by content hash.
get_scores¶
get_scores(score_ids: Sequence[str] | None = None, score_type: str | None = None, score_category: str | Sequence[str] | None = None, sent_after: datetime | None = None, sent_before: datetime | None = None, identifier_filters: Sequence[IdentifierFilter] | None = None, include_intermediate: bool = False) → Sequence[Score]Use get_scores_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[Score]— Sequence[Score]: The operation result.
get_scores_async¶
get_scores_async(score_ids: Sequence[str] | None = None, score_type: str | None = None, score_category: str | Sequence[str] | None = None, sent_after: datetime | None = None, sent_before: datetime | None = None, identifier_filters: Sequence[IdentifierFilter] | None = None, include_intermediate: bool = False) → Sequence[Score]Retrieve a list of Score objects based on the specified filters.
| Parameter | Type | Description |
|---|---|---|
score_ids | Sequence[str] | None | A list of score IDs to filter by. Defaults to None. |
score_type | str | None | The type of the score to filter by. Defaults to None. |
score_category | str | Sequence[str] | None | Return scores that list this category, or every category of a sequence. Names match whole and case-insensitively. Defaults to None. |
sent_after | datetime | None | Filter for scores sent after this datetime. Defaults to None. |
sent_before | datetime | None | Filter for scores sent before this datetime. Defaults to None. |
identifier_filters | Sequence[IdentifierFilter] | None | A sequence of IdentifierFilter objects that allows filtering by various scorer identifier JSON properties. Defaults to None. |
include_intermediate | bool | Include nested results. Explicit IDs always include them. Defaults to False. |
Returns:
Sequence[Score]— Sequence[Score]: A list of Score objects that match the specified filters.
get_seed_dataset_group_profiles_async¶
get_seed_dataset_group_profiles_async(metadata_keys: Sequence[str] = ()) → Sequence[SeedDatasetGroupProfile]Read compressed group structure without hydrating seeds, policies, or prompt values.
Returns:
Sequence[SeedDatasetGroupProfile]— Sequence[SeedDatasetGroupProfile]: Counts of groups sharing the same stored structural facts.
get_seed_dataset_names¶
get_seed_dataset_names() → Sequence[str]Use get_seed_dataset_names_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[str]— Sequence[str]: The operation result.
get_seed_dataset_names_async¶
get_seed_dataset_names_async() → Sequence[str]Return a list of all seed dataset names in the memory storage.
Returns:
Sequence[str]— Sequence[str]: A list of unique dataset names.
get_seed_dataset_summaries¶
get_seed_dataset_summaries() → Sequence[SeedDatasetSummary]Use get_seed_dataset_summaries_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[SeedDatasetSummary]— Sequence[SeedDatasetSummary]: The operation result.
get_seed_dataset_summaries_async¶
get_seed_dataset_summaries_async() → Sequence[SeedDatasetSummary]Return aggregate metadata for datasets already loaded in memory.
The queries intentionally project only dataset metadata and counts. Seed values and media are never hydrated, so callers can build dataset cards without materializing every prompt or fetching providers.
Named dataset grouping and metadata matching stay on the original collated dataset_name column. NULL and empty names are aggregated separately into the unnamed population so their shared logical groups are counted exactly once.
Returns:
Sequence[SeedDatasetSummary]— Sequence[SeedDatasetSummary]: One summary for each stored dataset, includingSequence[SeedDatasetSummary]— a single deterministic entry for seeds without a dataset name.
get_seed_decomposition_async¶
get_seed_decomposition_async(objective_id: uuid.UUID) → Sequence[SeedObjective]Retrieve a stored objective and every objective decomposed beneath it.
Use build_objective_decomposition_tree(result, root_id=objective_id) to walk the children
and paths; the returned objective keeps its stored parent link even when it is not a root.
Prompts grouped with these objectives can be read with get_seeds_async(prompt_group_ids=...).
| Parameter | Type | Description |
|---|---|---|
objective_id | uuid.UUID | The objective to start from, at any level of its tree. |
Returns:
Sequence[SeedObjective]— Sequence[SeedObjective]: The objective and its descendants, parents before children. Empty if no objective has this ID.
get_seed_example_async¶
get_seed_example_async(dataset_name: str | None, example_id: uuid.UUID) → list[SeedRecord]Read one complete logical seed example from one dataset.
Seeds are read as in get_seed_examples_async.
| Parameter | Type | Description |
|---|---|---|
dataset_name | str | None | The dataset name. None or an empty string selects seeds without a dataset name. |
example_id | uuid.UUID | The prompt_group_id of the example, or the seed ID of a seed without a group. |
Returns:
list[SeedRecord]— list[SeedRecord]: The stored members, objectives first. The list is empty if thelist[SeedRecord]— dataset does not contain it.
get_seed_examples_async¶
get_seed_examples_async(dataset_name: str | None, limit: int, after: DecodedKeysetCursor | None = None, data_types: Sequence[PromptDataType] | None = None, harm_categories: Sequence[str] | None = None, seed_types: Sequence[SeedType] | None = None, value_search: str | None = None, value_pattern: str | None = None) → tuple[dict[uuid.UUID, list[SeedRecord]], int, DecodedKeysetCursor | None]Read one page of complete logical seed examples from one dataset.
A logical example is all seeds in the dataset that share a prompt_group_id, or one seed
without a group. Examples are ordered by their earliest date_added, then by example ID,
both descending, using the canonical textual UUID order on every backend. Values inside
one filter use OR, different filters use AND, and any member can satisfy a filter.
Members are stored-record projections: configurations remain raw text, and no templates
are rendered or referenced files loaded.
| Parameter | Type | Description |
|---|---|---|
dataset_name | str | None | The dataset name. None or an empty string selects seeds without a dataset name. |
limit | int | The maximum number of examples to return. |
after | DecodedKeysetCursor | None | The sort key of the last example on the previous page. Defaults to None. |
data_types | Sequence[PromptDataType] | None | Match seeds with any of these data types. Defaults to None. |
harm_categories | Sequence[str] | None | Match seeds with any of these harm categories, as whole values that ignore case. Defaults to None. |
seed_types | Sequence[SeedType] | None | Match seeds with any of these seed types. Defaults to None. |
value_search | str | None | Match text prompts and objectives whose stored value contains this literal text, ignoring case. Simulated-conversation configurations are not searched. Defaults to None. |
value_pattern | str | None | Full case-insensitive LIKE pattern instead of value_search. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
Returns:
dict[uuid.UUID, list[SeedRecord]]— tuple[dict[uuid.UUID, list[SeedRecord]], int, DecodedKeysetCursor | None]: The stored members of eachint— example keyed by example ID in page order, objectives first; the number of examples thatDecodedKeysetCursor | None— match the filters; and the sort key of the last example when more examples follow.
get_seed_groups¶
get_seed_groups(value: str | None = None, value_pattern: str | None = None, value_sha256: Sequence[str] | None = None, dataset_name: str | None = None, dataset_name_pattern: str | None = None, data_types: Sequence[str] | None = None, harm_categories: Sequence[str] | None = None, harm_categories_patterns: Sequence[str] | None = None, added_by: str | None = None, authors: Sequence[str] | None = None, authors_patterns: Sequence[str] | None = None, groups: Sequence[str] | None = None, groups_patterns: Sequence[str] | None = None, source: str | None = None, seed_type: SeedType | None = None, origin: SeedOrigin | None = None, is_general_technique: bool | None = None, parameters: Sequence[str] | None = None, parameters_patterns: Sequence[str] | None = None, metadata: dict[str, str | int] | None = None, prompt_group_ids: Sequence[uuid.UUID] | None = None, group_length: Sequence[int] | None = None) → Sequence[SeedGroup]This synchronous API is deprecated and can block the caller.
Returns:
Sequence[SeedGroup]— Sequence[SeedGroup]: The operation result.
get_seed_groups_async¶
get_seed_groups_async(value: str | None = None, value_pattern: str | None = None, value_sha256: Sequence[str] | None = None, dataset_name: str | None = None, dataset_name_pattern: str | None = None, data_types: Sequence[str] | None = None, harm_categories: Sequence[str] | None = None, harm_categories_patterns: Sequence[str] | None = None, added_by: str | None = None, authors: Sequence[str] | None = None, authors_patterns: Sequence[str] | None = None, groups: Sequence[str] | None = None, groups_patterns: Sequence[str] | None = None, source: str | None = None, seed_type: SeedType | None = None, origin: SeedOrigin | None = None, is_general_technique: bool | None = None, parameters: Sequence[str] | None = None, parameters_patterns: Sequence[str] | None = None, metadata: dict[str, str | int] | None = None, prompt_group_ids: Sequence[uuid.UUID] | None = None, group_length: Sequence[int] | None = None) → Sequence[SeedGroup]Retrieve groups of seed prompts based on the provided filtering criteria.
| Parameter | Type | Description |
|---|---|---|
origin | SeedOrigin | None | Match origin before expanding to complete groups. Defaults to None. |
is_general_technique | (bool | None, Optional) | Match whether the seed represents a general attack technique before expanding to complete groups. Defaults to None. |
value | (str | None, Optional) | The value to match by substring. Defaults to None. |
value_pattern | str | None | Full case-insensitive LIKE pattern. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
value_sha256 | (Sequence[str] | None, Optional) | SHA256 hash of value to filter seed groups by. Defaults to None. |
dataset_name | (str | None, Optional) | Name of the dataset to match exactly. Defaults to None. |
dataset_name_pattern | (str | None, Optional) | A full case-insensitive LIKE pattern for dataset names. Supports wildcards: % (any characters) and _ (single character). ‘/’ escapes the next character; brackets, ‘*’ and backslashes are literal. If both dataset_name and dataset_name_pattern are provided, dataset_name takes precedence. Defaults to None. |
data_types | (Sequence[str] | None, Optional) | List of data types to filter seed prompts by (e.g., text, image_path). Defaults to None. |
harm_categories | (Sequence[str] | None, Optional) | List of harm categories to filter seed prompts by. Defaults to None. |
harm_categories_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
added_by | (str | None, Optional) | The user who added the seed groups to filter by. Defaults to None. |
authors | (Sequence[str] | None, Optional) | List of authors to filter seed groups by. Defaults to None. |
authors_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
groups | (Sequence[str] | None, Optional) | List of groups to filter seed groups by. Defaults to None. |
groups_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
source | (str | None, Optional) | The source from which the seed prompts originated. Defaults to None. |
seed_type | (SeedType | None, Optional) | The type of seed to filter by (“prompt”, “objective”, or “simulated_conversation”). Defaults to None. |
parameters | (Sequence[str] | None, Optional) | List of parameters to filter by. Defaults to None. |
parameters_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
metadata | (dict[str, str | int] | None, Optional) | A free-form dictionary for tagging prompts with custom metadata. Defaults to None. |
prompt_group_ids | (Sequence[uuid.UUID] | None, Optional) | List of prompt group IDs to filter by. Defaults to None. |
group_length | (Sequence[int] | None, Optional) | The number of seeds in the group to filter by. Defaults to None. |
Returns:
Sequence[SeedGroup]— Sequence[SeedGroup]: A list ofSeedGroupobjects that match the filtering criteria.
get_seed_identifiers¶
get_seed_identifiers(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, value: str | None = None, value_sha256: str | None = None, data_type: str | None = None, dataset_name: str | None = None, is_general_technique: bool | None = None) → Sequence[SeedIdentifier]Use get_seed_identifiers_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[SeedIdentifier]— Sequence[SeedIdentifier]: The operation result.
get_seed_identifiers_async¶
get_seed_identifiers_async(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, value: str | None = None, value_sha256: str | None = None, data_type: str | None = None, dataset_name: str | None = None, is_general_technique: bool | None = None) → Sequence[SeedIdentifier]Retrieve seed identifiers using exact normalized-column filters.
| Parameter | Type | Description |
|---|---|---|
identifier_hashes | Sequence[str] | None | Content hashes to include. Defaults to None. |
class_name | str | None | Component class name to match. Defaults to None. |
value | str | None | Seed value to match. Defaults to None. |
value_sha256 | str | None | Seed value hash to match. Defaults to None. |
data_type | str | None | Seed data type to match. Defaults to None. |
dataset_name | str | None | Dataset name to match. Defaults to None. |
is_general_technique | bool | None | General-technique flag to match. Defaults to None. |
Returns:
Sequence[SeedIdentifier]— Sequence[SeedIdentifier]: Matching identifiers ordered by content hash.
get_seeds¶
get_seeds(value: str | None = None, value_pattern: str | None = None, value_sha256: Sequence[str] | None = None, dataset_name: str | None = None, dataset_name_pattern: str | None = None, data_types: Sequence[str] | None = None, harm_categories: Sequence[str] | None = None, harm_categories_patterns: Sequence[str] | None = None, added_by: str | None = None, authors: Sequence[str] | None = None, authors_patterns: Sequence[str] | None = None, groups: Sequence[str] | None = None, groups_patterns: Sequence[str] | None = None, source: str | None = None, seed_type: SeedType | None = None, origin: SeedOrigin | None = None, is_general_technique: bool | None = None, parameters: Sequence[str] | None = None, parameters_patterns: Sequence[str] | None = None, metadata: dict[str, str | int] | None = None, prompt_group_ids: Sequence[uuid.UUID] | None = None) → Sequence[Seed[Any]]Use get_seeds_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[Seed[Any]]— Sequence[Seed]: The operation result.
get_seeds_async¶
get_seeds_async(value: str | None = None, value_pattern: str | None = None, value_sha256: Sequence[str] | None = None, dataset_name: str | None = None, dataset_name_pattern: str | None = None, data_types: Sequence[str] | None = None, harm_categories: Sequence[str] | None = None, harm_categories_patterns: Sequence[str] | None = None, added_by: str | None = None, authors: Sequence[str] | None = None, authors_patterns: Sequence[str] | None = None, groups: Sequence[str] | None = None, groups_patterns: Sequence[str] | None = None, source: str | None = None, seed_type: SeedType | None = None, origin: SeedOrigin | None = None, is_general_technique: bool | None = None, parameters: Sequence[str] | None = None, parameters_patterns: Sequence[str] | None = None, metadata: dict[str, str | int] | None = None, prompt_group_ids: Sequence[uuid.UUID] | None = None) → Sequence[Seed[Any]]Retrieve a list of seed prompts based on the specified filters.
List filters match substrings within decoded elements, not their JSON representation. Substring searches are case-insensitive and literal. Explicit pattern companions accept full LIKE patterns: ‘%’ and ‘_’ are wildcards and ‘/’ escapes the next character. Supplying a literal and its pattern companion raises ValueError.
| Parameter | Type | Description |
|---|---|---|
origin | SeedOrigin | None | Match the recorded ingestion origin. Defaults to None. |
is_general_technique | bool | None | Match whether the seed represents a general attack technique. Defaults to None. |
value | str | The value to match by substring. If None, all values are returned. Defaults to None. |
value_pattern | str | None | Full case-insensitive LIKE pattern. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
value_sha256 | Sequence[str] | None | A list of SHA256 hashes of values to match. If None, all values are returned. Defaults to None. |
dataset_name | str | The dataset name to match exactly. If None, all dataset names are considered. Defaults to None. |
dataset_name_pattern | str | A full case-insensitive LIKE pattern for dataset names. Supports wildcards: % (any characters) and _ (single character). ‘/’ escapes the next character; brackets, ‘*’ and backslashes are literal. If both dataset_name and dataset_name_pattern are provided, dataset_name takes precedence. Defaults to None. |
data_types | Sequence[str] | None | List of data types to filter seed prompts by (e.g., text, image_path). Defaults to None. |
harm_categories | Sequence[str] | A list of harm categories to filter by. If None, all harm categories are considered. Specifying multiple harm categories returns only prompts that are marked with all harm categories. Defaults to None. |
harm_categories_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
added_by | str | The user who added the prompts. Defaults to None. |
authors | Sequence[str] | A list of authors to filter by. Note that this filters by substring, so a query for “Adam Jones” may not return results if the record is “A. Jones”, “Jones, Adam”, etc. If None, all authors are considered. Defaults to None. |
authors_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
groups | Sequence[str] | A list of groups to filter by. If None, all groups are considered. Defaults to None. |
groups_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
source | str | The source to filter by. If None, all sources are considered. Defaults to None. |
seed_type | SeedType | The type of seed to filter by (“prompt”, “objective”, or “simulated_conversation”). Defaults to None. |
parameters | Sequence[str] | A list of parameters to filter by. Specifying parameters effectively returns prompt templates instead of prompts. Defaults to None. |
parameters_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
metadata | dict[str, str | int] | A free-form dictionary for tagging prompts with custom metadata. Defaults to None. |
prompt_group_ids | Sequence[uuid.UUID] | A list of prompt group IDs to filter by. Defaults to None. |
Returns:
Sequence[Seed[Any]]— Sequence[Seed]: A list of seeds (e.g., SeedPrompt, SeedObjective, SeedSimulatedConversation) matching the criteria.
get_session¶
get_session() → SessionUse get_session_async.
This synchronous API is deprecated and can block the caller.
Returns:
Session— The operation result.
get_session_async¶
get_session_async() → AsyncSessionCreate an independent async session.
The caller must close the session with an async context manager.
Returns:
AsyncSession— A session owned by the current event loop.
Raises:
NotImplementedError— If a custom sync session hook has not been migrated.
get_target_identifiers¶
get_target_identifiers(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, endpoint: str | None = None, model_name: str | None = None, underlying_model_name: str | None = None, temperature: float | None = None, top_p: float | None = None, max_requests_per_minute: int | None = None, supported_auth_modes: Sequence[str] | None = None) → Sequence[TargetIdentifier]Use get_target_identifiers_async.
This synchronous API is deprecated and can block the caller.
Returns:
Sequence[TargetIdentifier]— Sequence[TargetIdentifier]: The operation result.
get_target_identifiers_async¶
get_target_identifiers_async(identifier_hashes: Sequence[str] | None = None, class_name: str | None = None, endpoint: str | None = None, model_name: str | None = None, underlying_model_name: str | None = None, temperature: float | None = None, top_p: float | None = None, max_requests_per_minute: int | None = None, supported_auth_modes: Sequence[str] | None = None) → Sequence[TargetIdentifier]Retrieve target identifiers using exact normalized-column filters.
| Parameter | Type | Description |
|---|---|---|
identifier_hashes | Sequence[str] | None | Content hashes to include. Defaults to None. |
class_name | str | None | Component class name to match. Defaults to None. |
endpoint | str | None | Target endpoint to match. Defaults to None. |
model_name | str | None | Target model name to match. Defaults to None. |
underlying_model_name | str | None | Underlying model name to match. Defaults to None. |
temperature | float | None | Temperature to match. Defaults to None. |
top_p | float | None | Top-p value to match. Defaults to None. |
max_requests_per_minute | int | None | Request limit to match. Defaults to None. |
supported_auth_modes | Sequence[str] | None | Authentication modes to match exactly, in any order. Defaults to None. |
Returns:
Sequence[TargetIdentifier]— Sequence[TargetIdentifier]: Matching identifiers ordered by content hash.
get_unique_attack_attribution¶
get_unique_attack_attribution() → dict[str, list[str]]Use get_unique_attack_attribution_async.
This synchronous API is deprecated and can block the caller.
Returns:
dict[str, list[str]]— dict[str, list[str]]: The operation result.
get_unique_attack_attribution_async¶
get_unique_attack_attribution_async() → dict[str, list[str]]Return unique dedicated operator and operation values from indexed columns.
get_unique_attack_class_names¶
get_unique_attack_class_names() → list[str]Use get_unique_attack_class_names_async.
This synchronous API is deprecated and can block the caller.
Returns:
list[str]— list[str]: The operation result.
get_unique_attack_class_names_async¶
get_unique_attack_class_names_async() → list[str]Return sorted unique attack class names from all stored attack results.
Extracts class_name from the atomic_attack_identifier JSON column via a database-level DISTINCT query.
Returns:
list[str]— Sorted list of unique attack class name strings.
get_unique_attack_labels¶
get_unique_attack_labels(operator: Sequence[str] | None = None, operation: Sequence[str] | None = None, labels: Mapping[str, str | Sequence[str]] | None = None) → dict[str, list[str]]Use get_unique_attack_labels_async.
This synchronous API is deprecated and can block the caller.
Returns:
dict[str, list[str]]— dict[str, list[str]]: The operation result.
get_unique_attack_labels_async¶
get_unique_attack_labels_async(operator: Sequence[str] | None = None, operation: Sequence[str] | None = None, labels: Mapping[str, str | Sequence[str]] | None = None) → dict[str, list[str]]Return unique arbitrary labels, optionally narrowed by indexed attribution first.
| Parameter | Type | Description |
|---|---|---|
operator | Sequence[str] | None | Operator values used to narrow rows. Defaults to None. |
operation | Sequence[str] | None | Operation values used to narrow rows. Defaults to None. |
labels | Mapping[str, str | Sequence[str]] | None | Arbitrary label filters used to narrow rows. Defaults to None. |
Returns:
dict[str, list[str]]— dict[str, list[str]]: Mapping of label keys to sorted lists ofdict[str, list[str]]— unique values.
get_unique_converter_class_names¶
get_unique_converter_class_names() → list[str]Use get_unique_converter_class_names_async.
This synchronous API is deprecated and can block the caller.
Returns:
list[str]— list[str]: The operation result.
get_unique_converter_class_names_async¶
get_unique_converter_class_names_async() → list[str]Return sorted unique converter class names used across all attack results.
Extracts class_name values from the request_converters array of either identifier layout within the atomic_attack_identifier JSON column via a database-level query.
Returns:
list[str]— Sorted list of unique converter class name strings.
get_unique_scenario_labels¶
get_unique_scenario_labels() → dict[str, list[str]]Use get_unique_scenario_labels_async.
This synchronous API is deprecated and can block the caller.
Returns:
dict[str, list[str]]— dict[str, list[str]]: The operation result.
get_unique_scenario_labels_async¶
get_unique_scenario_labels_async() → dict[str, list[str]]Return all unique label values across scenario results.
increment_scenario_number_tries¶
increment_scenario_number_tries(scenario_result_id: str) → intUse increment_scenario_number_tries_async.
This synchronous API is deprecated and can block the caller.
Returns:
int— The new number_tries value after incrementing.
increment_scenario_number_tries_async¶
increment_scenario_number_tries_async(scenario_result_id: str) → intAtomically increment and return the number_tries counter for a scenario result.
| Parameter | Type | Description |
|---|---|---|
scenario_result_id | str | The ID of the scenario result to update. |
Returns:
int— The new number_tries value after incrementing.
Raises:
ValueError— If the scenario result is not found.
initialize_async¶
initialize_async() → NoneInitialize the schema once without blocking the caller’s event loop.
Raises:
RuntimeError— If initialization is already in progress.
is_dataset_name_available_async¶
is_dataset_name_available_async(dataset_name: str) → boolReport whether a new dataset can use a name, without reserving it.
A name is taken when stored seeds use it, a staging upload reserved it, or an unfinished prompt generation holds it. Uploads and generations enforce the same rule when they reserve a name.
| Parameter | Type | Description |
|---|---|---|
dataset_name | str | The name to check. |
Returns:
bool— True if no stored dataset, staging upload, or unfinished generation uses the name.
prepare_seed_batch_async¶
prepare_seed_batch_async(seeds: Sequence[Seed[Any]], added_by: str | None = None) → PreparedSeedBatchPrepare copied seeds once for validation and subsequent persistence.
Computes checksums, attribution, timestamps, and encoding metadata through the normal storage path. Media may be copied into managed storage; no database rows are written. Rejected batches can leave unreferenced media, not changed seed rows.
| Parameter | Type | Description |
|---|---|---|
seeds | Sequence[Seed] | Caller-owned seeds to copy and prepare. |
added_by | str | None | Attribution override, matching normal insertion. Defaults to None. |
Returns:
PreparedSeedBatch— Storage-ready seeds, isolated from caller and validator mutations.
print_schema¶
print_schema() → NoneUse print_schema_async.
This synchronous API is deprecated and can block the caller.
print_schema_async¶
print_schema_async() → NonePrint the schema without blocking the caller’s event loop.
promote_attack_conversation¶
promote_attack_conversation(attack_result_id: str, conversation_id: str) → boolUse promote_attack_conversation_async.
This synchronous API is deprecated and can block the caller.
Returns:
bool— The operation result.
promote_attack_conversation_async¶
promote_attack_conversation_async(attack_result_id: str, conversation_id: str) → boolPromote an existing related conversation without losing concurrent branch additions.
Returns:
bool— False when the attack no longer exists.
Raises:
ValueError— If the requested conversation is not part of this attack.SQLAlchemyError— If the transaction fails.
recover_dataset_cleanup_async¶
recover_dataset_cleanup_async() → NoneRecover abandoned uploads and incomplete deletions after runtime initialization.
release_dataset_upload_async¶
release_dataset_upload_async(upload_id: uuid.UUID) → NoneRelease this runtime’s native upload ownership after publication, failure, or shutdown.
remove_seed_groups_from_memory¶
remove_seed_groups_from_memory(value: str | None = None, value_pattern: str | None = None, exact: bool = True, value_sha256: Sequence[str] | None = None, dataset_name: str | None = None, dataset_name_pattern: str | None = None, data_types: Sequence[str] | None = None, harm_categories: Sequence[str] | None = None, harm_categories_patterns: Sequence[str] | None = None, added_by: str | None = None, authors: Sequence[str] | None = None, authors_patterns: Sequence[str] | None = None, groups: Sequence[str] | None = None, groups_patterns: Sequence[str] | None = None, source: str | None = None, seed_type: SeedType | None = None, origin: SeedOrigin | None = None, is_general_technique: bool | None = None, parameters: Sequence[str] | None = None, parameters_patterns: Sequence[str] | None = None, metadata: dict[str, str | int] | None = None, prompt_group_ids: Sequence[uuid.UUID] | None = None) → intUse remove_seed_groups_from_memory_async.
This synchronous API is deprecated and can block the caller.
Returns:
int— The operation result.
remove_seed_groups_from_memory_async¶
remove_seed_groups_from_memory_async(value: str | None = None, value_pattern: str | None = None, exact: bool = True, value_sha256: Sequence[str] | None = None, dataset_name: str | None = None, dataset_name_pattern: str | None = None, data_types: Sequence[str] | None = None, harm_categories: Sequence[str] | None = None, harm_categories_patterns: Sequence[str] | None = None, added_by: str | None = None, authors: Sequence[str] | None = None, authors_patterns: Sequence[str] | None = None, groups: Sequence[str] | None = None, groups_patterns: Sequence[str] | None = None, source: str | None = None, seed_type: SeedType | None = None, origin: SeedOrigin | None = None, is_general_technique: bool | None = None, parameters: Sequence[str] | None = None, parameters_patterns: Sequence[str] | None = None, metadata: dict[str, str | int] | None = None, prompt_group_ids: Sequence[uuid.UUID] | None = None) → intDelete groups of seed prompts based on the provided filtering criteria.
Unlike remove_seeds_from_memory, which deletes only the individual seeds that match, this removes every seed that shares a prompt_group_id with any matching seed. This preserves group integrity: filtering by a single modality (e.g. data_types=[“image_path”]) or attribute removes the whole group rather than leaving a partial group behind. It accepts the same filtering parameters as get_seeds (plus an exact flag). It is recommended to call get_seed_groups with the same filters first to preview which groups will be removed. At least one filter must be provided to prevent accidental deletion of all seeds. The deletion runs in a single transaction, so it works consistently across SQLite and Azure SQL.
Group expansion must still select every objective of an affected decomposition tree;
otherwise ValueError is raised before any rows are deleted.
Only seeds that belong to a group are affected: a matching seed with no prompt_group_id (for example, one added individually via add_seeds_to_memory_async rather than as part of a group) is skipped, since it has no group to expand. Use remove_seeds_from_memory to delete ungrouped seeds. A get_seed_groups preview shows such ungrouped matches as single-seed groups even though this method does not remove them.
Only database records are removed. For file-backed seeds (image_path, audio_path, video_path) the serialized file on disk is left in place; delete those files separately if they are no longer needed.
| Parameter | Type | Description |
|---|---|---|
origin | SeedOrigin | None | Match origin before expanding to complete groups. Defaults to None. |
is_general_technique | bool | None | Match whether the seed represents a general attack technique before expanding to complete groups. Defaults to None. |
value | str | The value to match. For the remove methods this defaults to full-string equality (exact=True) so a short or common value does not delete far more seeds than intended; pass exact=False to match by substring instead. If None, all values are considered. |
value_pattern | str | None | Full case-insensitive LIKE pattern. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
exact | bool | When True, value is matched by full-string equality rather than substring. Has no effect unless value is provided. Defaults to True for the remove methods (the safer choice for deletion). Note this differs from get_seeds, which always matches value by substring. |
value_sha256 | Sequence[str] | None | A list of SHA256 hashes of values to match. If None, all values are considered. Defaults to None. |
dataset_name | str | The dataset name to match exactly. If None, all dataset names are considered. Defaults to None. |
dataset_name_pattern | str | A full case-insensitive LIKE pattern for dataset names. Supports wildcards: % (any characters) and _ (single character). ‘/’ escapes the next character; brackets, ‘*’ and backslashes are literal. If both dataset_name and dataset_name_pattern are provided, dataset_name takes precedence. Defaults to None. |
data_types | Sequence[str] | None | List of data types to filter seed prompts by (e.g., text, image_path). Defaults to None. |
harm_categories | Sequence[str] | A list of harm categories to filter by. If None, all harm categories are considered. Specifying multiple harm categories matches only prompts that are marked with all harm categories. Defaults to None. |
harm_categories_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
added_by | str | The user who added the prompts. Defaults to None. |
authors | Sequence[str] | A list of authors to filter by. Note that this filters by substring, so a query for “Adam Jones” may not return results if the record is “A. Jones”, “Jones, Adam”, etc. If None, all authors are considered. Defaults to None. |
authors_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
groups | Sequence[str] | A list of groups to filter by. If None, all groups are considered. Defaults to None. |
groups_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
source | str | The source to filter by. If None, all sources are considered. Defaults to None. |
seed_type | SeedType | The type of seed to filter by (“prompt”, “objective”, or “simulated_conversation”). Defaults to None. |
parameters | Sequence[str] | A list of parameters to filter by. Specifying parameters effectively targets prompt templates instead of prompts. Defaults to None. |
parameters_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
metadata | dict[str, str | int] | A free-form dictionary for tagging prompts with custom metadata. Defaults to None. |
prompt_group_ids | Sequence[uuid.UUID] | A list of prompt group IDs to filter by. Defaults to None. |
Returns:
int— The number of seeds removed across all affected groups.
Raises:
ValueError— If no filters are provided or the expanded groups contain only part of a decomposition tree.SQLAlchemyError— If the database deletion fails (the transaction is rolled back).
remove_seeds_from_memory¶
remove_seeds_from_memory(value: str | None = None, value_pattern: str | None = None, exact: bool = True, value_sha256: Sequence[str] | None = None, dataset_name: str | None = None, dataset_name_pattern: str | None = None, data_types: Sequence[str] | None = None, harm_categories: Sequence[str] | None = None, harm_categories_patterns: Sequence[str] | None = None, added_by: str | None = None, authors: Sequence[str] | None = None, authors_patterns: Sequence[str] | None = None, groups: Sequence[str] | None = None, groups_patterns: Sequence[str] | None = None, source: str | None = None, seed_type: SeedType | None = None, origin: SeedOrigin | None = None, is_general_technique: bool | None = None, parameters: Sequence[str] | None = None, parameters_patterns: Sequence[str] | None = None, metadata: dict[str, str | int] | None = None, prompt_group_ids: Sequence[uuid.UUID] | None = None) → intUse remove_seeds_from_memory_async.
This synchronous API is deprecated and can block the caller.
Returns:
int— The operation result.
remove_seeds_from_memory_async¶
remove_seeds_from_memory_async(value: str | None = None, value_pattern: str | None = None, exact: bool = True, value_sha256: Sequence[str] | None = None, dataset_name: str | None = None, dataset_name_pattern: str | None = None, data_types: Sequence[str] | None = None, harm_categories: Sequence[str] | None = None, harm_categories_patterns: Sequence[str] | None = None, added_by: str | None = None, authors: Sequence[str] | None = None, authors_patterns: Sequence[str] | None = None, groups: Sequence[str] | None = None, groups_patterns: Sequence[str] | None = None, source: str | None = None, seed_type: SeedType | None = None, origin: SeedOrigin | None = None, is_general_technique: bool | None = None, parameters: Sequence[str] | None = None, parameters_patterns: Sequence[str] | None = None, metadata: dict[str, str | int] | None = None, prompt_group_ids: Sequence[uuid.UUID] | None = None) → intDelete a list of seed prompts based on the specified filters.
Accepts the same filtering parameters as get_seeds (plus an exact flag). It is recommended to call get_seeds with the same filters first to preview which seeds will be removed. At least one filter must be provided to prevent accidental deletion of all seeds. The deletion runs in a single transaction, so it works consistently across SQLite and Azure SQL.
A filter that selects only part of a decomposition tree raises ValueError before any
rows are deleted. Select every objective in the tree, for example by dataset name.
Only database records are removed. For file-backed seeds (image_path, audio_path, video_path) the serialized file on disk is left in place; delete those files separately if they are no longer needed.
| Parameter | Type | Description |
|---|---|---|
origin | SeedOrigin | None | Match the recorded ingestion origin. Defaults to None. |
is_general_technique | bool | None | Match whether the seed represents a general attack technique. Defaults to None. |
value | str | The value to match. For the remove methods this defaults to full-string equality (exact=True) so a short or common value does not delete far more seeds than intended; pass exact=False to match by substring instead. If None, all values are considered. |
value_pattern | str | None | Full case-insensitive LIKE pattern. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
exact | bool | When True, value is matched by full-string equality rather than substring. Has no effect unless value is provided. Defaults to True for the remove methods (the safer choice for deletion). Note this differs from get_seeds, which always matches value by substring. |
value_sha256 | Sequence[str] | None | A list of SHA256 hashes of values to match. If None, all values are considered. Defaults to None. |
dataset_name | str | The dataset name to match exactly. If None, all dataset names are considered. Defaults to None. |
dataset_name_pattern | str | A full case-insensitive LIKE pattern for dataset names. Supports wildcards: % (any characters) and _ (single character). ‘/’ escapes the next character; brackets, ‘*’ and backslashes are literal. If both dataset_name and dataset_name_pattern are provided, dataset_name takes precedence. Defaults to None. |
data_types | Sequence[str] | None | List of data types to filter seed prompts by (e.g., text, image_path). Defaults to None. |
harm_categories | Sequence[str] | A list of harm categories to filter by. If None, all harm categories are considered. Specifying multiple harm categories matches only prompts that are marked with all harm categories. Defaults to None. |
harm_categories_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
added_by | str | The user who added the prompts. Defaults to None. |
authors | Sequence[str] | A list of authors to filter by. Note that this filters by substring, so a query for “Adam Jones” may not return results if the record is “A. Jones”, “Jones, Adam”, etc. If None, all authors are considered. Defaults to None. |
authors_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
groups | Sequence[str] | A list of groups to filter by. If None, all groups are considered. Defaults to None. |
groups_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
source | str | The source to filter by. If None, all sources are considered. Defaults to None. |
seed_type | SeedType | The type of seed to filter by (“prompt”, “objective”, or “simulated_conversation”). Defaults to None. |
parameters | Sequence[str] | A list of parameters to filter by. Specifying parameters effectively targets prompt templates instead of prompts. Defaults to None. |
parameters_patterns | Sequence[str] | None | Case-insensitive full LIKE patterns. All must match decoded list elements. ‘%’ and ‘_’ are wildcards; ‘/’ escapes the next character. Defaults to None. |
metadata | dict[str, str | int] | A free-form dictionary for tagging prompts with custom metadata. Defaults to None. |
prompt_group_ids | Sequence[uuid.UUID] | A list of prompt group IDs to filter by. Defaults to None. |
Returns:
int— The number of seeds removed.
Raises:
ValueError— If no filters are provided or the selection would delete only part of a decomposition tree.SQLAlchemyError— If the database deletion fails (the transaction is rolled back).
replace_finding_paths_async¶
replace_finding_paths_async(operation_id: uuid.UUID, finding_id: uuid.UUID, paths: Sequence[DecompositionPath]) → FindingReplace a finding’s ordered paths, each an ordered chain of its direct sub-findings, in one transaction.
Returns:
Finding— The updated finding.
Raises:
LookupError— If the finding does not belong to the operation.FindingHierarchyError— If path IDs repeat, or a step is not a direct sub-finding of the finding.
replace_prepared_seed_batch_async¶
replace_prepared_seed_batch_async(dataset_name: str, batch: PreparedSeedBatch) → intAtomically replace a dataset with the prepared snapshot, without reprocessing media or hashes.
| Parameter | Type | Description |
|---|---|---|
dataset_name | str | Dataset whose rows are replaced. |
batch | PreparedSeedBatch | The snapshot returned by prepare_seed_batch_async. |
Returns:
int— The number of replaced seed rows.
replace_seeds_for_dataset_async¶
replace_seeds_for_dataset_async(dataset_name: str, seeds: Sequence[Seed[Any]], added_by: str | None = None) → intAtomically replace all stored seeds for a dataset with a new set.
Every existing SeedPromptEntries row for dataset_name is deleted and the provided
seeds are inserted in a single transaction and commit; if the insert fails the delete is
rolled back with it, so the previously stored seeds are preserved. Seeds are prepared
(media serialized, SHA256 computed) before the transaction opens. Deduplication is
intentionally skipped: this is a full replace, so the provided seeds are stored as given.
The isolation guarantee is the database transaction boundary: a reader that queries after
the commit sees the complete new set. This holds on the file-backed SQLite and Azure SQL
backends, where each session has its own connection. The in-memory SQLite backend shares a
single connection across all sessions, so it does not isolate concurrent sessions from one
another; callers that need to read a dataset while it is being replaced should use a
file-backed or Azure SQL backend. RefreshDatasets replaces datasets sequentially, so it
does not rely on cross-session isolation.
SeedPromptEntries has no dependent foreign keys, so no related rows are removed first.
Deleting media-backed seeds (image_path, audio_path, video_path) removes only the
database rows; any serialized media files they reference are left on disk. This matches every
other seed-delete path and results in disk bloat, not data loss.
| Parameter | Type | Description |
|---|---|---|
dataset_name | str | The name of the dataset whose seeds should be replaced. |
seeds | Sequence[Seed] | The new seeds to store for the dataset; must be non-empty and every seed’s dataset_name must equal dataset_name. |
added_by | str | None | The user to attribute the new seeds to. Defaults to None. |
Returns:
int— The number ofSeedPromptEntriesdeleted before the new seeds were inserted.
Raises:
ValueError— Ifdataset_nameis empty,seedsis empty, a seed belongs to another dataset, or the seed groups are structurally invalid.SQLAlchemyError— If the replacement fails; the transaction is rolled back first.
require_operation_async¶
require_operation_async(operation_id: uuid.UUID) → OperationRead a saved Operation by ID without creating or resolving a name.
Returns:
Operation— The saved record.
Raises:
LookupError— If the Operation does not exist.
reserve_dataset_mutation_async¶
reserve_dataset_mutation_async(dataset_name: str, paths: Sequence[str]) → uuid.UUIDJournal new media for an existing exact-name population before writing bytes.
Returns:
uuid.UUID— uuid.UUID: Durable operation ID.
reserve_dataset_upload_async¶
reserve_dataset_upload_async(dataset_name: str, paths: Sequence[str]) → uuid.UUIDReserve an exact name and journal owned asset paths before writing bytes.
Returns:
uuid.UUID— uuid.UUID: The durable upload/cleanup identifier.
reset_database¶
reset_database() → NoneUse reset_database_async.
This synchronous API is deprecated and can block the caller.
reset_database_async¶
reset_database_async() → NoneDrop and rebuild the schema using the blocking-only Alembic tooling.
resolve_operation_id_async¶
resolve_operation_id_async(operation_id: uuid.UUID | str | None, operation_name: str | None = None) → uuid.UUID | NoneReturn the saved Operation for an ID or a deprecated Operation name, without creating one.
An ID takes precedence over a name. Names match regardless of case and surrounding whitespace. Until 1.4.0, a name that matches no saved Operation is kept as a plain name rather than rejected.
TODO(PyRIT 1.4): Remove operation_name with Operation name attribution.
Returns:
uuid.UUID | None— uuid.UUID | None: The saved Operation’s ID, or None when no ID is given and no saved Operation has the name.
Raises:
ValueError— If the ID is malformed.LookupError— If the ID does not belong to a saved Operation.
try_update_prompt_generation_async¶
try_update_prompt_generation_async(generation: PromptGenerationRecord, expected_statuses: Collection[PromptGenerationStatus], expected_execution_id: uuid.UUID | None = None, fields: Collection[str], reserve_dataset_name: bool = False) → boolUpdate a stored generation only while it is in one of expected_statuses.
The compare and the write are one UPDATE, so a generation that another task or process moved on is never overwritten.
| Parameter | Type | Description |
|---|---|---|
generation | PromptGenerationRecord | The new state of the generation. |
expected_statuses | Collection[PromptGenerationStatus] | Statuses the stored generation may be in. |
expected_execution_id | uuid.UUID | None | When set, the run attempt that must still own the generation. Defaults to None. |
fields | Collection[str] | The record fields to write. Other fields keep their stored values, so a write built from an older read can’t revert a concurrent change to them. |
reserve_dataset_name | bool | Whether to recheck, under the dataset lifecycle lock, that no stored dataset, staging upload, or other generation took the name. Use it when a generation that released its name is queued again. Defaults to False. |
Returns:
bool— True if the generation was updated, False if it is missing or moved on.
Raises:
ValueError— Ifexpected_statusesorfieldsis empty, or a field can’t be changed.DatasetNameConflictError— Ifreserve_dataset_nameis set and the name is taken. Nothing changes.RuntimeError— If the database does not return a cursor result.
try_update_scenario_run_state¶
try_update_scenario_run_state(scenario_result_id: str, expected_states: Collection[ScenarioRunState], scenario_run_state: ScenarioRunState, error_message: str | None = None, error_type: str | None = None, expected_metadata_fields: Mapping[str, str] | None = None) → boolUse try_update_scenario_run_state_async.
This synchronous API is deprecated and can block the caller.
Returns:
bool— The operation result.
try_update_scenario_run_state_async¶
try_update_scenario_run_state_async(scenario_result_id: str, expected_states: Collection[ScenarioRunState], scenario_run_state: ScenarioRunState, error_message: str | None = None, error_type: str | None = None, expected_metadata_fields: Mapping[str, str] | None = None) → boolUpdate the run state only when the stored state is one of expected_states.
The compare and the write are a single UPDATE so a run that reached a terminal state
on another thread is not overwritten. A read followed by
update_scenario_run_state cannot give that guarantee because scenario
preparation and cancellation run on different threads.
| Parameter | Type | Description |
|---|---|---|
scenario_result_id | str | The ID of the scenario result to update. |
expected_states | Collection[ScenarioRunState] | States the row may currently be in. |
scenario_run_state | ScenarioRunState | The new state for the scenario. |
error_message | str | None | Optional scenario-level error message. Defaults to None. |
error_type | str | None | Optional exception class name. Defaults to None. |
expected_metadata_fields | Mapping[str, str] | None | Optional metadata fields that must match. Defaults to None. |
Returns:
bool— True if the row was updated, False if it was missing or in another state.
Raises:
ValueError— Ifexpected_statesis empty.
update_attack_result¶
update_attack_result(conversation_id: str, update_fields: dict[str, Any]) → boolUse update_attack_result_async.
This synchronous API is deprecated and can block the caller.
Returns:
bool— The operation result.
update_attack_result_async¶
update_attack_result_async(conversation_id: str, update_fields: dict[str, Any]) → boolUpdate specific fields of an existing AttackResultEntry identified by conversation_id.
This method queries for the raw database entry by conversation_id and updates the specified fields in place, avoiding the creation of duplicate rows.
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation ID of the attack result to update. |
update_fields | dict[str, Any] | A dictionary of column names to new values. Valid fields include ‘adversarial_chat_conversation_ids’, ‘pruned_conversation_ids’, ‘outcome’, ‘attack_metadata’, etc. |
Returns:
bool— True if the update was successful, False if the entry was not found.
Raises:
ValueError— If update_fields is empty.
update_attack_result_by_id¶
update_attack_result_by_id(attack_result_id: str, update_fields: dict[str, Any]) → boolUse update_attack_result_by_id_async.
This synchronous API is deprecated and can block the caller.
Returns:
bool— The operation result.
update_attack_result_by_id_async¶
update_attack_result_by_id_async(attack_result_id: str, update_fields: dict[str, Any]) → boolUpdate specific fields of an existing AttackResultEntry identified by its primary key.
| Parameter | Type | Description |
|---|---|---|
attack_result_id | str | The UUID primary key of the AttackResultEntry. |
update_fields | dict[str, Any] | Column names to new values. |
Returns:
bool— True if the update was successful, False if the entry was not found.
update_attack_result_conditionally_async¶
update_attack_result_conditionally_async(attack_result_id: str, expected_fields: Mapping[str, Any], update_fields: Mapping[str, Any], conversation_target: ComponentIdentifier | None = None, expected_conversation_pieces: Mapping[str, Sequence[MessagePiece]] | None = None) → boolCompare and update prepared fields and conversation targets in one transaction.
Returns:
bool— True after a successful update.
Raises:
AttackStateConflictError— The attack changed or a conversation uses another target.
update_finding_async¶
update_finding_async(operation_id: uuid.UUID, finding_id: uuid.UUID, request: FindingCreate) → FindingReplace a finding’s editable fields, including its parent, without changing identity, creation time, or paths.
A finding moves to another parent, or to the top level, with its sub-findings.
Returns:
Finding— The updated finding.
Raises:
LookupError— If the finding does not belong to the operation.FindingHierarchyError— If the finding would move while it is a step of its parent’s paths, or under a parent that is outside the operation, the finding itself, or one of its sub-findings.
update_operation_async¶
update_operation_async(operation_id: uuid.UUID, name: str | None = None, description: str | None = None) → OperationRename an operation or replace its description. Omitted fields are unchanged and the last save wins.
Names stay unique, ignoring case and surrounding whitespace, so a rename that only changes case is allowed.
Returns:
Operation— The updated operation, or the other operation that already has the name, unchanged.
Raises:
LookupError— If the Operation does not exist.IntegrityError— If the update fails for a reason other than a taken name.
update_prompt_entries_by_conversation_id¶
update_prompt_entries_by_conversation_id(conversation_id: str, update_fields: dict[str, Any]) → boolUse update_prompt_entries_by_conversation_id_async.
This synchronous API is deprecated and can block the caller.
Returns:
bool— The operation result.
update_prompt_entries_by_conversation_id_async¶
update_prompt_entries_by_conversation_id_async(conversation_id: str, update_fields: dict[str, Any]) → boolUpdate prompt entries for a given conversation ID with the specified field values.
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation ID of the entries to be updated. |
update_fields | dict | A dictionary of field names and their new values (ex. {“labels”: {“test”: “value”}}) |
Returns:
bool— True if the update was successful, False otherwise.
Raises:
ValueError— If update_fields is empty or not provided.ValueError— If prompt_metadata is provided and is not a dictionary.ValueError— If an entry is immutable observation evidence.
update_prompt_metadata_by_conversation_id¶
update_prompt_metadata_by_conversation_id(conversation_id: str, prompt_metadata: dict[str, str | int]) → boolUse update_prompt_metadata_by_conversation_id_async.
This synchronous API is deprecated and can block the caller.
Returns:
bool— The operation result.
update_prompt_metadata_by_conversation_id_async¶
update_prompt_metadata_by_conversation_id_async(conversation_id: str, prompt_metadata: dict[str, str | int]) → boolUpdate the metadata of prompt entries in memory for a given conversation ID.
| Parameter | Type | Description |
|---|---|---|
conversation_id | str | The conversation ID of the entries to be updated. |
prompt_metadata | dict[str, str | int] | New metadata. |
Returns:
bool— True if the update was successful, False otherwise.
update_scenario_metadata¶
update_scenario_metadata(scenario_result_id: str, metadata: dict[str, Any]) → NoneUse update_scenario_metadata_async.
This synchronous API is deprecated and can block the caller.
update_scenario_metadata_async¶
update_scenario_metadata_async(scenario_result_id: str, metadata: dict[str, Any]) → NoneReplace the scenario_metadata JSON blob on an existing scenario result.
Used by the scenario layer to persist first-run state (e.g. an adaptive run’s choices) that resume needs to replay. Performs a targeted UPDATE so it doesn’t clobber other columns.
| Parameter | Type | Description |
|---|---|---|
scenario_result_id | str | The ID of the scenario result to update. |
metadata | dict[str, Any] | The full metadata dict to store. Pass the merged dict, not just the new keys — this writes the whole value. |
Raises:
ValueError— If the scenario result is not found.
update_scenario_metadata_fields¶
update_scenario_metadata_fields(scenario_result_id: str, fields: Mapping[str, Any]) → NoneUse update_scenario_metadata_fields_async.
This synchronous API is deprecated and can block the caller.
update_scenario_metadata_fields_async¶
update_scenario_metadata_fields_async(scenario_result_id: str, fields: Mapping[str, Any]) → NoneMerge selected fields into persisted scenario metadata in one transaction.
Raises:
ValueError— If the scenario result is not found.
update_scenario_result_async¶
update_scenario_result_async(scenario_result: ScenarioResult) → NonePersist an updated scenario result.
| Parameter | Type | Description |
|---|---|---|
scenario_result | ScenarioResult | The scenario result to update. |
update_scenario_run_state¶
update_scenario_run_state(scenario_result_id: str, scenario_run_state: ScenarioRunState, error_message: str | None = None, error_type: str | None = None) → NoneUse update_scenario_run_state_async.
This synchronous API is deprecated and can block the caller.
update_scenario_run_state_and_metadata_fields¶
update_scenario_run_state_and_metadata_fields(scenario_result_id: str, scenario_run_state: ScenarioRunState, metadata_fields: Mapping[str, Any], error_message: str | None = None, error_type: str | None = None) → NoneUse update_scenario_run_state_and_metadata_fields_async.
This synchronous API is deprecated and can block the caller.
update_scenario_run_state_and_metadata_fields_async¶
update_scenario_run_state_and_metadata_fields_async(scenario_result_id: str, scenario_run_state: ScenarioRunState, metadata_fields: Mapping[str, Any], error_message: str | None = None, error_type: str | None = None) → NoneUpdate run state and merge scenario metadata in one transaction.
Raises:
ValueError— If the scenario result is not found.
update_scenario_run_state_async¶
update_scenario_run_state_async(scenario_result_id: str, scenario_run_state: ScenarioRunState, error_message: str | None = None, error_type: str | None = None) → NoneUpdate the run state of an existing scenario result.
Performs a targeted UPDATE of only the state/error columns instead of
rebuilding the entire ScenarioResultEntry row.
| Parameter | Type | Description |
|---|---|---|
scenario_result_id | str | The ID of the scenario result to update. |
scenario_run_state | ScenarioRunState | The new state for the scenario. |
error_message | str | None | Optional scenario-level error message. Defaults to None. |
error_type | str | None | Optional exception class name. Defaults to None. |
Raises:
ValueError— If the scenario result is not found.
PromptMemoryEntry¶
Bases: Base
Represents the prompt data.
Because of the nature of database and sql alchemy, type ignores are abundant :)
Attributes:
| Parameter | Type | Description |
|---|---|---|
__tablename__ | str | The name of the database table. |
__table_args__ | dict | Additional arguments for the database table. |
id | Uuid | The unique identifier for the memory entry. |
role | PromptType | system, assistant, user |
conversation_id | str | The identifier for the conversation which is associated with a single target. |
sequence | int | The order of the conversation within a conversation_id. Can be the same number for multi-part requests or multi-part responses. |
timestamp | DateTime | The timestamp of the memory entry. |
prompt_metadata | JSON | The metadata associated with the prompt. This can be specific to any scenarios. Because memory is how components talk with each other, this can be component specific. e.g. the URI from a file uploaded to a blob store, or a document type you want to upload. |
converter_identifiers | list[dict[str, str]] | None | The serialized identifiers of the applied converters. |
converter_identifier_links | list[PromptConverterIdentifierEntry] | The ordered associations to applied converters. |
original_value_data_type | PromptDataType | The data type of the original prompt (text, image) |
original_value | str | The text of the original prompt. If prompt is an image, it’s a link. |
original_value_sha256 | str | The SHA256 hash of the original prompt data. |
converted_value_data_type | PromptDataType | The data type of the converted prompt (text, image) |
converted_value | str | The text of the converted prompt. If prompt is an image, it’s a link. |
converted_value_sha256 | str | The SHA256 hash of the original prompt data. |
ix_PromptMemoryEntries_conversation_sequence_id | Index | Composite conversation ordering index. |
original_prompt_id | UUID | The original prompt id. It is equal to id unless it is a duplicate. |
scores | list[ScoreEntry] | The list of scores associated with the prompt. |
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
entry | MessagePiece | The message piece to convert into a database entry. |
Methods:
get_message_piece¶
get_message_piece() → MessagePieceConvert this database entry back into a MessagePiece object.
Returns:
MessagePiece— The reconstructed message piece with all its data.
SQLiteMemory¶
Bases: MemoryInterface
A memory interface that uses SQLite as the backend database.
This class provides functionality to insert, query, and manage conversation data using SQLite. It supports both file-based and in-memory databases.
Cancellation finalizes active cursors and closes interrupted connections before returning to the caller. Session cleanup also finishes under repeated cancellation. Failed disconnects and session rollbacks preserve the original cancellation and expose cleanup failures as its cause.
File-backed databases wait up to 30 seconds for locks held by other connections
before failing with database is locked.
Note: this is replacing the old DuckDB implementation.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
db_path | Path | str | None | Path to the SQLite database file. Defaults to “pyrit.db”. |
verbose | bool | Whether to enable verbose logging. Defaults to False. |
skip_schema_migration | bool | Whether to skip schema migration. Defaults to False. |
silent | bool | If True, suppresses schema migration console output. Defaults to False. |
Examples:
Methods:
get_all_table_models¶
get_all_table_models() → list[type[Base]]Return a list of all table models used in the database by inspecting the Base registry.
Returns:
list[type[Base]]— list[Base]: A list of SQLAlchemy model classes.
get_session_async¶
get_session_async() → AsyncSessionCreate a session with cancellation-safe SQLite cleanup.
In-memory sessions also have exclusive access to the shared database.
Returns:
AsyncSession— A session that finishes cleanup before releasing exclusive access.
Raises:
NotImplementedError— If a custom sync session hook has not been migrated.RuntimeError— If this thread already holds a synchronous session.
ScenarioAttemptSeedSummary¶
Lightweight projection of attempt seed and outcome fields for scenario recount.
Contains only the scalar fields required to resolve logical execution units and aggregate attempt counts during legacy recount. Never loads prompt entries, score records, retry events, or large conversation payloads.
ScenarioHistoryAggregate¶
Attempt metrics for one scenario run, aggregated by the database.
Counters are computed over logical work units — every persisted attempt is first resolved to the planned unit it belongs to, so retried and errored attempts never inflate unit counts. The metrics query produces one aggregate per history row; a separate projection returns only distinct technique names, never one row per unit.
Methods:
empty¶
empty(scenario_result_id: str) → SelfBuild the zero-valued aggregate for a run with no persisted attempts.
Returns:
Self— Aggregate with all counters set to zero.
ScenarioHistoryKeysetCursor¶
Bases: NamedTuple
Descending keyset anchor for scenario history.
ScenarioHistoryRunRecord¶
Lightweight persisted scenario header for one history row.
ScenarioRunStateRecord¶
Lightweight persisted ID/state projection used for startup reconciliation.
SeedEntry¶
Bases: Base
Represents the raw prompt or prompt template data as found in open datasets.
Note: This is different from the PromptMemoryEntry which is the processed prompt data. SeedPrompt merely reflects basic prompts before plugging into attacks, running through models with corresponding attack strategies, and applying converters. PromptMemoryEntry captures the processed prompt data before and after the above steps.
Attributes:
| Parameter | Type | Description |
|---|---|---|
__tablename__ | str | The name of the database table. |
__table_args__ | dict | Additional arguments for the database table. |
id | Uuid | The unique identifier for the memory entry. |
value | str | The value of the seed prompt. |
value_sha256 | str | The SHA256 hash of the value of the seed prompt data. |
data_type | PromptDataType | The data type of the seed prompt. |
dataset_name | str | The name of the dataset the seed prompt belongs to. |
harm_categories | list[str] | The harm categories associated with the seed prompt. |
description | str | The description of the seed prompt. |
authors | list[str] | The authors of the seed prompt. |
groups | list[str] | The groups involved in authoring the seed prompt (if any). |
source | str | The source of the seed prompt. |
date_added | DateTime | The date the seed prompt was added. |
added_by | str | The user who added the seed prompt. |
prompt_metadata | dict[str, str | int] | The metadata associated with the seed prompt. This includes information that is useful for the specific target you’re probing, such as encoding data. |
parameters | list[str] | The parameters included in the value. Note that seed prompts do not have parameters, only prompt templates do. However, they are stored in the same table. |
prompt_group_id | uuid.UUID | The ID of a group the seed prompt may optionally belong to. Groups are used to organize prompts for multi-turn conversations or multi-modal prompts. |
sequence | int | The turn of the seed prompt in a group. When entire multi-turn conversations are stored, this is used to order the prompts. |
role | str | The role of the prompt (e.g., user, system, assistant). |
seed_type | SeedType | The type of seed - “prompt”, “objective”, or “simulated_conversation”. |
conditions | list[dict[str, Any]] | None | Serialized objective criteria, absent for other seeds. |
parent_objective_id | uuid.UUID | None | The parent of a decomposed objective, absent for other seeds. |
paths | list[dict[str, Any]] | None | Serialized decomposition paths of an objective’s children. |
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
entry | Seed | The seed object to convert into a database entry. |
Methods:
get_seed¶
get_seed() → SeedPrompt | SeedObjective | SeedSimulatedConversationConvert this database entry back into a Seed object.
Returns:
SeedPrompt | SeedObjective | SeedSimulatedConversation— SeedPrompt | SeedObjective | SeedSimulatedConversation: The reconstructed seed object.
Raises:
ValueError— If persisted conditions or decomposition fields are invalid or attached to a non-objective seed, or a simulated conversation record cannot be rebuilt, for example when it names a prompt file that is not present on this machine.
get_seed_record¶
get_seed_record() → SeedRecordProject stored fields without reconstructing an executable seed.
Returns:
SeedRecord— Stored content, identifiers, and metadata, including raw configuration text.
StorageIO¶
Bases: ABC
Abstract interface for storage systems (local disk, Azure Storage Account, etc.).
Methods:
canonical_path¶
canonical_path(path: str) → strResolve the effective storage identity; non-disk adapters override this.
Returns:
str— The canonical local identity.
create_directory_if_not_exists_async¶
create_directory_if_not_exists_async(path: Path | str) → NoneAsynchronously creates a directory or equivalent in the storage system if it doesn’t exist.
delete_file_async¶
delete_file_async(path: Path | str) → NoneDelete one caller-owned file; custom storage must implement cleanup explicitly.
is_file_async¶
is_file_async(path: Path | str) → boolAsynchronously checks if the path refers to a file (not a directory or container).
path_exists_async¶
path_exists_async(path: Path | str) → boolAsynchronously checks if a file or blob exists at the given path.
read_file_async¶
read_file_async(path: Path | str) → bytesAsynchronously reads the file (or blob) from the given path.
write_file_async¶
write_file_async(path: Path | str, data: bytes) → NoneAsynchronously writes data to the given path.
write_stream_async¶
write_stream_async(path: Path | str, chunks: AsyncIterable[bytes]) → NoneWrite inert upload bytes without buffering the complete asset.
SupportedContentType¶
Bases: StrEnum
All supported content types for uploading blobs to provided storage account container.
See all options here: https://
Members are plain strings, so they can be used anywhere a MIME-type string is expected.
Examples:
TextDataTypeSerializer¶
Bases: DataTypeSerializer
Serializer for text and text-like prompt values that stay in-memory.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
prompt_text | str | Prompt value. |
data_type | PromptDataType | Text-like prompt data type. Defaults to 'text'. |
Methods:
data_on_disk¶
data_on_disk() → boolIndicate whether this serializer persists data on disk.
Returns:
bool— Always False for text serializers.
URLDataTypeSerializer¶
Bases: DataTypeSerializer
Serializer for URL values and URL-backed local file references.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
category | str | Data category folder name. |
prompt_text | str | URL or path value. |
extension | str | None | Optional extension for persisted content. Defaults to None. |
Methods:
data_on_disk¶
data_on_disk() → boolIndicate whether this serializer persists data on disk.
Returns:
bool— True for non-http values, False for URL values.
VideoPathDataTypeSerializer¶
Bases: DataTypeSerializer
Serializer for video path values stored on disk.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
category | str | The category or context for the data. |
prompt_text | str | None | The video path or identifier. Defaults to None. |
extension | str | None | The file extension, defaults to ‘mp4’. |
Methods:
data_on_disk¶
data_on_disk() → boolIndicate whether this serializer persists data on disk.
Returns:
bool— Always True for video path serializers.