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

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

pyrit.executor.promptgen

Prompt generator strategy imports.

Functions

get_lazy_dir

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

Return package attributes and unresolved public exports.

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

Returns:

resolve_lazy_export

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

Resolve and cache one package export.

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

Returns:

Raises:

AnecdoctorContext

Bases: PromptGeneratorStrategyContext

Context specific to Anecdoctor prompt generation.

Contains all parameters needed for executing Anecdoctor prompt generation, including the evaluation data, language settings, and conversation ID.

AnecdoctorGenerator

Bases: PromptGeneratorStrategy[AnecdoctorContext, AnecdoctorResult], Identifiable

Implementation of the Anecdoctor prompt generation strategy.

The Anecdoctor generator creates misinformation content by either:

  1. Using few-shot examples directly (default mode when processing_model is not provided)

  2. First extracting a knowledge graph from examples, then using it (when processing_model is provided)

This generator is designed to test a model’s susceptibility to generating false or misleading content when provided with examples in ClaimsReview format. The generator can optionally use a processing model to extract a knowledge graph representation of the examples before generating the final content.

The generation flow consists of:

  1. (Optional) Extract knowledge graph from evaluation data using processing model

  2. Format a system prompt based on language and content type

  3. Send formatted examples (or knowledge graph) to target model

  4. Return the generated content as the result

Constructor Parameters:

ParameterTypeDescription
objective_targetPromptTargetThe chat model to be used for prompt generation.
processing_modelPromptTarget | NoneThe model used for knowledge graph extraction. If provided, the generator will extract a knowledge graph from the examples before generation. If None, the generator will use few-shot examples directly. Defaults to None.
converter_configStrategyConverterConfig | NoneConfiguration for converters. Defaults to None.
prompt_normalizerPromptNormalizer | NoneNormalizer for handling prompts. Defaults to None.

Examples:

Methods:

execute_async

execute_async(kwargs: Any = {}) → AnecdoctorResult

Execute the prompt generation strategy asynchronously with the provided parameters.

ParameterTypeDescription
content_typestrThe type of content to generate (e.g., “viral tweet”, “news article”).
languagestrThe language of the content to generate (e.g., “english”, “spanish”).
evaluation_datalist[str]The data in ClaimsReview format to use in constructing the prompt.
memory_labelsdict[str, str] | NoneMemory labels for the generation context. Defaults to None.
**kwargsAnyAdditional parameters for the generation. Defaults to {}.

Returns:

AnecdoctorResult

Bases: PromptGeneratorStrategyResult

Result of Anecdoctor prompt generation.

Contains the generated content from the misinformation prompt generation.

Attributes:

ParameterTypeDescription
generated_contentMessageThe generated content from the prompt generation.

AssertGenerator

Bases: PromptGeneratorStrategy[AssertGeneratorContext, AssertGeneratorResult]

Generate a taxonomy, coverage assignments, and related objective and prompt seeds.

Model calls are sequential. Targets own request timeouts and transport retries; the generator validates responses through PyRIT’s JSON retry mechanism.

Constructor Parameters:

ParameterTypeDescription
targetPromptTargetTarget for taxonomy and seed generation.
research_targetPromptTarget | NoneOptional separate target for behavior and dimension research. Explicit web search requires search support on it. Defaults to None.

Examples:

Methods:

advance_async

advance_async(checkpoint: AssertGenerationCheckpoint, stop_after: AssertGenerationStage | None = None, on_checkpoint: Callable[[AssertGenerationCheckpoint], Awaitable[None]] | None = None) → AssertGenerationCheckpoint

Run the remaining stages of a checkpoint, optionally stopping after one of them.

Start from AssertGenerationCheckpoint(config=...). To review the policy, stop after AssertGenerationStage.DIMENSIONS, apply with_reviewed_policy, and call again. on_checkpoint receives the progress after each stage and each batch of seed groups, so a caller can store it and resume after an interruption.

This returns progress rather than a result, so it runs setup and teardown but not the strategy events or retry collection of execute_async. Before any model call, it checks the target of each role that has a stage left to run: the target must support the request’s web search policy and, if the role already produced work, must be the target that produced it; only its rate limit may differ. build_result attributes work to the recorded targets.

ParameterTypeDescription
checkpointAssertGenerationCheckpointThe progress to continue from.
stop_afterAssertGenerationStage | NoneThe last stage to run. Defaults to every stage.
on_checkpointCallable[[AssertGenerationCheckpoint], Awaitable[None]] | NoneReceives each new checkpoint. Defaults to None.

Returns:

build_result

build_result(checkpoint: AssertGenerationCheckpoint) → AssertGeneratorResult

Package a complete checkpoint as native seed groups, without model calls.

The result names the targets recorded in the checkpoint, which produced its work, rather than this generator’s targets.

ParameterTypeDescription
checkpointAssertGenerationCheckpointProgress with every requested seed group.

Returns:

Raises:

estimate

estimate(checkpoint: AssertGenerationCheckpoint) → PromptGenerationEstimate

Estimate the remaining model calls and tokens of a checkpoint without calling a target.

Input tokens measure the request each stage sends, with typical output sizes in place of stage outputs that don’t exist yet. Seed-group calls are exact once the taxonomy and dimension levels are known, generated or supplied in the request, because the batch plan is then known. Before that, they range from one call per five remaining groups (every group shares an assignment) to one call per remaining group (every group has its own assignment).

ParameterTypeDescription
checkpointAssertGenerationCheckpointThe progress to estimate from. Use AssertGenerationCheckpoint(config=...) for a new request.

Returns:

Raises:

execute_with_context_async

execute_with_context_async(context: AssertGeneratorContext) → AssertGeneratorResult

Execute a request once through the standard strategy lifecycle: run every stage, then build the result.

Returns:

Raises:

validate_checkpoint

validate_checkpoint(checkpoint: AssertGenerationCheckpoint, stop_after: AssertGenerationStage | None = None) → None

Check, without model calls, that this generator’s targets can run a checkpoint’s remaining stages.

advance_async runs the same check. Only roles with a stage left are checked: their target must support the request’s web search policy and, if the role already produced work, must be the target that produced it.

ParameterTypeDescription
checkpointAssertGenerationCheckpointThe progress to continue from.
stop_afterAssertGenerationStage | NoneThe last stage to run. Defaults to every stage.

Raises:

validate_config

validate_config(config: AssertGenerationConfig) → None

Check that the configured targets can enforce a request’s web search policy, without model calls.

The research target is checked only when the request runs a research stage, which a supplied taxonomy with explicit dimension levels skips.

ParameterTypeDescription
configAssertGenerationConfigThe request to check.

Raises:

AssertGeneratorContext

Bases: PromptGeneratorStrategyContext

Single-use request and the generator-owned conversations for its stages.

AssertGeneratorResult

Bases: PromptGeneratorStrategyResult

Complete native seed groups, policy, coverage, and generation evidence.

PromptGeneratorStrategy

Bases: Strategy[PromptGeneratorStrategyContextT, PromptGeneratorStrategyResultT], ABC

Base class for all prompt generator strategies. Provides a structure for implementing specific prompt generation strategies.

Constructor Parameters:

ParameterTypeDescription
context_typetypeType of the context used by the strategy.
loggerlogging.LoggerLogger instance for logging events. Defaults to logger.
event_handlerStrategyEventHandlerEvent handler for handling strategy events. Defaults to None.

PromptGeneratorStrategyContext

Bases: StrategyContext, ABC

Base class for all prompt generator strategy contexts.

PromptGeneratorStrategyResult

Bases: StrategyResult, ABC

Base class for all prompt generator strategy results.

TargetObjectiveGenerator

Bases: PromptGeneratorStrategy[TargetObjectiveGeneratorContext, TargetObjectiveGeneratorResult]

Generate a complete batch of text objectives through the standard strategy execution entry point.

Constructor Parameters:

ParameterTypeDescription
targetPromptTargetTarget used to generate objectives.
system_promptSeedPrompt | NoneText seed prompt; defaults to the bundled generation YAML. Its response_json_schema is used for both target output and local validation. If omitted on a custom prompt, the bundled schema is used. The schema must require an objectives array of strings. Trusted templates can use instructions, count, and harm_categories parameters.
timeout_secondsfloatPositive finite deadline, including retry waits. Cleanup can take up to five additional seconds after cancellation. Defaults to 120.

Methods:

estimate

estimate(instructions: str, count: int, harm_categories: Sequence[str] = ()) → PromptGenerationEstimate

Estimate the model calls and tokens of a request with the bundled prompt, without calling a target.

ParameterTypeDescription
instructionsstrWhat the objectives should cover.
countintThe number of objectives to generate.
harm_categoriesSequence[str]Harm categories to apply. Defaults to ().

Returns:

Raises:

execute_with_context_async

execute_with_context_async(context: TargetObjectiveGeneratorContext) → TargetObjectiveGeneratorResult

Execute once within the deadline, with bounded cleanup after cancellation.

Returns:

Raises:

TargetObjectiveGeneratorResult

Bases: PromptGeneratorStrategyResult

Validated objectives and their generation conversation ID.