Converters for transforming prompts before sending them to targets in red teaming workflows.
Converters are organized into categories: Text-to-Text (encoding, obfuscation, translation, variation), Audio (text-to-audio, audio-to-text, audio-to-audio), Image (text-to-image, image-to-image), Video (image-to-video), File (text-to-PDF/URL), Selective Converting (partial prompt transformation), and Human-in-the-Loop (interactive review). Converters can be stacked together to create complex transformation pipelines for testing AI system robustness.
Functions¶
get_converter_modalities¶
get_converter_modalities() → list[tuple[str, list[PromptDataType], list[PromptDataType]]]Retrieve a list of all converter classes and their supported input/output modalities by reading the SUPPORTED_INPUT_TYPES and SUPPORTED_OUTPUT_TYPES class attributes.
Returns:
list[tuple[str, list[PromptDataType], list[PromptDataType]]]— list[tuple[str, list[PromptDataType], list[PromptDataType]]]: A sorted list of tuples containing:Converter class name (str)
List of supported input modalities (list[PromptDataType])
List of supported output modalities (list[PromptDataType])
list[tuple[str, list[PromptDataType], list[PromptDataType]]]— Sorted by input modality, then output modality, then converter name.
Examples:
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.
AcrosticConverter¶
Bases: Converter
Hides a prompt as an acrostic: the first character of each line spells the original message when read vertically.
Each character of the prompt becomes one or more lines — an alphabetic character is expanded into benign words starting with its uppercase form, a space is rendered as a sentinel line, other whitespace is encoded by Unicode code point, and remaining characters are emitted directly. A leading instruction tells the model to read the acrostic vertically and follow the reconstructed message.
This is a steganographic converter: a content filter scanning the visible
text sees an innocuous word list, while the real request is only legible
when read top-to-bottom. It is the encoder counterpart of
FirstLetterConverter.
Example — "hi there" becomes (with the default word bank):
Harbor
Island
—
Temple
Harbor
Engine
River
EngineReading the first character of each line yields HI THERE.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
instruction | (str, Optional) | Leading instruction that tells the model how to read the acrostic. Defaults to a built-in instruction. |
word_bank | (dict[str, str], Optional) | Mapping of lowercase letter to a benign word starting with that letter. Defaults to a built-in bank. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultEncode the prompt as an acrostic word list prefixed with the instruction.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input prompt to be converted. |
input_type | PromptDataType | The type of the input prompt. Must be “text”. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted prompt and its type.
Raises:
ValueError— If the input type is not supported.
decode¶
decode(acrostic_text: str) → strReconstruct the hidden message from an acrostic produced by this converter.
Useful for round-trip verification. The leading instruction is separated from the acrostic body by a blank line and is skipped; each remaining line contributes its first character, with sentinel lines restoring whitespace.
Letters come back uppercased because each acrostic word starts with a capital. Other characters retain their original value.
| Parameter | Type | Description |
|---|---|---|
acrostic_text | str | The acrostic text produced by this converter. |
Returns:
str— The reconstructed message, with sentinel lines rendered as spaces.
AddImageTextConverter¶
Bases: _BaseImageTextConverter
Adds text to an image and wraps the text into multiple lines if necessary.
Supports optional bounding box placement, text rotation, centering, and automatic font sizing to fit text within a specified region. When no bounding_box is provided, the full image is used as the bounding box.
Font size can be a fixed int or a (min, max) tuple for automatic sizing that shrinks from max down to min to fit text within the bounding box.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
img_to_add | Path | File path of image to add text to. |
font_name | Path | None | Path of font to use. Must be a TrueType font (.ttf). Defaults to None which uses Pillow’s built-in default font. |
color | tuple[int, int, int] | Color to print text in, using RGB values. Defaults to (0, 0, 0). |
font_size | int | tuple[int, int] | Font size as a fixed int, or a (min, max) tuple for automatic sizing that shrinks from max down to min to fit text in the bounding box. Defaults to 15. |
bounding_box | tuple[int, int, int, int] | None | Optional (x1, y1, x2, y2) region to constrain text within. When not set, the full image is used with a default margin. Defaults to None. |
rotation | float | Rotation angle in degrees for the text. Must be finite. Defaults to 0.0. |
center_text | bool | Whether to center text horizontally and vertically within the bounding box. Defaults to False. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by adding it as text to the image.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The text to be added to the image. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing path to the updated image.
Raises:
ValueError— If the input type is not supported.
AddImageVideoConverter¶
Bases: Converter
Adds an image to a video at a specified position.
Currently the image is placed in the whole video, not at a specific timepoint.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
video_path | Path | str | Local file path or Azure Blob URL of video to add image to. |
img_position | tuple | Position to place image in video. Defaults to (10, 10). |
img_resize_size | tuple | Size to resize image to. Defaults to (500, 500). |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'image_path') → ConverterResultConvert the given prompt (image) by adding it to a video.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The image path to be added to the video. |
input_type | PromptDataType | The type of input data. Defaults to 'image_path'. |
Returns:
ConverterResult— The result containing filename of the converted video.
Raises:
ModuleNotFoundError— If OpenCV is not installed.ValueError— If the input type is not supported, the image path is invalid, the input video format is unsupported, the input video cannot be read, the output video cannot be written, or the overlay image cannot be decoded.
AddTextImageConverter¶
Bases: _BaseImageTextConverter
Adds a string to an image and wraps the text into multiple lines if necessary.
This class is similar to AddImageTextConverter except
we pass in text as an argument to the constructor as opposed to an image file path.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
text_to_add | str | Text to add to an image. |
font_name | Path | None | Path of font to use. Must be a TrueType font (.ttf). Defaults to None which uses Pillow’s built-in default font. |
color | tuple[int, int, int] | Color to print text in, using RGB values. Defaults to (0, 0, 0). |
font_size | int | Size of font to use. Defaults to 15. |
x_pos | int | X coordinate to place text in (0 is left most). Defaults to 10. |
y_pos | int | Y coordinate to place text in (0 is upper most). Defaults to 10. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'image_path') → ConverterResultConvert the given prompt (image) by adding text to it.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The image file path to which text will be added. |
input_type | PromptDataType | The type of input data. Defaults to 'image_path'. |
Returns:
ConverterResult— The result containing path to the updated image.
Raises:
ValueError— If the input type is not supported.
AllWordsSelectionStrategy¶
Bases: WordSelectionStrategy
Selects all words (default strategy).
Methods:
select_words¶
select_words(words: list[str]) → list[int]Select all words.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of words to select from. |
Returns:
list[int]— list[int]: All word indices.
AnsiAttackConverter¶
Bases: Converter
Generates prompts with ANSI codes to evaluate LLM behavior and system risks.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
include_raw | bool | Include scenarios with raw ANSI codes. Defaults to True. |
include_escaped | bool | Include scenarios with escaped ANSI codes. Defaults to True. |
include_tasks | bool | Include “ASKS + HIGH_LEVEL_TASKS” scenarios. Defaults to True. |
include_repeats | bool | Include “repeat this payload” scenarios. Defaults to True. |
include_unescape | bool | Include “unescape this payload” scenarios. Defaults to True. |
incorporate_user_prompt | bool | If True, the user’s prompt is integrated into the final scenario. Defaults to True. |
seed | int | None | Optional seed for reproducible scenario generation. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt into an ANSI attack scenario.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The original user prompt. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the generated ANSI scenario prompt.
Raises:
ValueError— If the input type is not supported.
input_supported¶
input_supported(input_type: PromptDataType) → boolCheck if the input type is supported.
| Parameter | Type | Description |
|---|---|---|
input_type | PromptDataType | The type of input data. |
Returns:
bool— True if the input type is supported, False otherwise.
output_supported¶
output_supported(output_type: PromptDataType) → boolCheck if the output type is supported.
| Parameter | Type | Description |
|---|---|---|
output_type | PromptDataType | The type of output data. |
Returns:
bool— True if the output type is supported, False otherwise.
ArabicPresentationFormConverter¶
Bases: Converter
Substitutes Arabic letters with their isolated Arabic Presentation Forms-B glyphs.
Each standard Arabic letter is replaced by its isolated presentation form (for example ALEF U+0627 is replaced by U+FE8D). A reader still recognizes the same letters, shown in their non-joining isolated shapes, while the underlying code point and token sequence change. The substitution map is derived from Unicode decomposition data, so it stays correct without a hand-maintained table. The transformation is deterministic, and characters with no Arabic isolated presentation form (including Arabic digits and punctuation) are left unchanged.
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by substituting Arabic letters with isolated presentation forms.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the substituted text.
Raises:
ValueError— If the input type is not supported.
ArabiziConverter¶
Bases: Converter
Transliterates Arabic script into Arabizi (Latin-script “chat Arabic”).
Arabizi is the everyday Latin-script encoding of Arabic used in chat and social media, where letters that have no Latin equivalent are written with digits that resemble their shape (for example HAH becomes 7, AIN becomes 3, and QAF becomes 8). This converter applies a deterministic per-character mapping with Gulf-leaning conventions: no language model is involved, so the same input always produces the same output. The attack surface targeted is tokenizer and safety classifier handling of transliterated Arabic, not the language itself.
Short-vowel diacritics and the tatweel connector are dropped, the Arabic comma, semicolon and question mark become their Latin counterparts, and characters outside the Arabic block (Latin text, digits, punctuation) are left unchanged. The mapping is intentionally lossy, mirroring how Arabizi is actually written.
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by transliterating Arabic script into Arabizi.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the transliterated text.
Raises:
ValueError— If the input type is not supported.
AsciiArtConverter¶
Bases: Converter
Uses the art package to convert text into ASCII art.
art silently omits characters the selected font has no glyph for. Those
characters are instead passed through as literal text and a warning is logged,
so no part of the prompt is lost. Combining characters and emoji sequences are
kept together. Padding uses terminal display widths; control-character layout
remains dependent on the receiving terminal.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
font | str | The font to use for ASCII art. Defaults to “rand” which selects a random font. Indirect selectors such as “wizard” or “rnd-small” are resolved to a single concrete font per conversion. Font names are case-insensitive. The special “mix” mode chooses a stable, seeded glyph mapping for each conversion. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt into ASCII art.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the ASCII art representation of the prompt.
Raises:
ValueError— If the input type is not supported.
AsciiSmugglerConverter¶
Bases: SmugglerConverter
Implements encoding and decoding using Unicode Tags.
If ‘control’ is True, the encoded output is wrapped with: - U+E0001 (start control tag) - U+E007F (end control tag)
Unicode Tags only exist for printable ASCII, so before encoding, characters with a faithful ASCII
equivalent are replaced: whitespace such as newlines and tabs becomes a space, typographic dashes,
quotes and ellipses become their ASCII forms, accents are removed (é becomes e, whether it is
written precomposed or as e plus a combining accent), and fullwidth letters and ligatures become their
ASCII letters (A becomes A, fi becomes fi). Characters with no faithful ASCII equivalent,
such as CJK text, emoji, superscripts and subscripts (², ₂) or spacing accents (´), still raise
ValueError.
Replicates the functionality detailed in the following blog post: Rehberger, 2024
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
action | Literal['encode', 'decode'] | The action to perform. Defaults to 'encode'. |
unicode_tags | bool | Whether to add Unicode tags during encoding. Defaults to False. |
Examples:
Methods:
decode_message¶
decode_message(message: str) → strDecode a message encoded with Unicode Tags.
For each character in the Unicode Tags range, subtracts 0xE0000. Skips control tags if present, and the England, Scotland and Wales flag emoji, which are written with tags.
| Parameter | Type | Description |
|---|---|---|
message | str | The encoded message. |
Returns:
str— The decoded message.
encode_message¶
encode_message(message: str) → tuple[str, str]Encode the message using Unicode Tags.
Characters with a faithful ASCII equivalent are first replaced with it. Each ASCII printable character (0x20-0x7E) is then mapped to a corresponding Unicode Tag (by adding 0xE0000). If control mode is enabled, wraps the output.
| Parameter | Type | Description |
|---|---|---|
message | str | The message to encode. |
Returns:
tuple[str, str]— tuple[str, str]: A tuple with a summary of code points and the encoded message.
Raises:
ValueError— Ifmessagecontains a character with no ASCII printable (0x20-0x7E) equivalent, which has no Unicode Tag representation. Such characters were previously dropped while the result still reported success; useSneakyBitsSmugglerConverterorVariationSelectorSmugglerConverterto smuggle arbitrary Unicode losslessly.
to_ascii_equivalent¶
to_ascii_equivalent(text: str) → str | NoneReturn the printable ASCII text that encoding text actually smuggles.
text is first composed to NFC, so canonically equivalent spellings such as café and
cafe plus a combining acute give the same result. A combining mark with no base character to
compose with, such as one at the start of the text or after a space, has no equivalent.
| Parameter | Type | Description |
|---|---|---|
text | str | The text to normalize. |
Returns:
str | None— str | None:textwith each character replaced by its ASCII equivalent, or None when any character has no equivalent and encoding would raise.
AskToDecodeConverter¶
Bases: Converter
Wraps encoded text with prompts that ask a target to decode it.
This converter takes encoded text (e.g., Base64, ROT13, Morse code) and wraps it in various prompt templates that request decoding. The prompts can be generic (“Decode the following text:”) or encoding-specific (“Base64 encoded string:”). This is useful for testing whether AI systems will decode potentially harmful encoded content when explicitly asked.
Credit to Garak:
garak
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
template | str | Custom template for conversion. Should include {encoded_text} placeholder and optionally {encoding_name} placeholder. If None, a random template is selected. Defaults to None. |
encoding_name | str | Name of the encoding scheme (e.g., “Base64”, “ROT13”, “Morse”). Used in encoding_name_templates to provide context about the encoding type. Defaults to “cipher”. |
seed | int | None | Optional seed for reproducible template selection. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given encoded text by wrapping it with a decoding request prompt.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The encoded text to be wrapped with a decoding request. |
input_type | PromptDataType | Type of input data. Defaults to “text”. |
Returns:
ConverterResult— The result containing the converted prompt.
Raises:
ValueError— If the input type is not supported (only “text” is supported).
AtbashConverter¶
Bases: Converter
Encodes text using the Atbash cipher.
‘Hello 123’ would encode to ‘Svool 876’.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
append_description | bool | If True, appends plaintext “expert” text to the prompt. This includes instructions to only communicate using the cipher, a description of the cipher, and an example encoded using the cipher. Defaults to False. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt using the Atbash cipher.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the encoded prompt.
Raises:
ValueError— If the input type is not supported.
AudioEchoConverter¶
Bases: Converter
Adds an echo effect to an audio file.
The echo is created by mixing a delayed, attenuated copy of the signal back into the original. The delay and decay parameters control the timing and loudness of the echo respectively. Sample rate, bit depth, and channel count are preserved. Unsigned 8-bit PCM is mixed around its silence midpoint of 128.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | str | The format of the audio file, defaults to “wav”. |
delay | float | The echo delay in seconds. Must be finite and greater than 0. Defaults to 0.3. |
decay | float | The decay factor for the echo (0.0 to 1.0). A value of 0.0 means no echo, 1.0 means the echo is as loud as the original. Must be finite and between 0 and 1 (exclusive of both). Defaults to 0.5. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'audio_path') → ConverterResultConvert the given audio file by adding an echo effect.
| Parameter | Type | Description |
|---|---|---|
prompt | str | File path to the audio file to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'audio_path'. |
Returns:
ConverterResult— The result containing the converted audio file path.
Raises:
ValueError— If the input type is not supported.Exception— If there is an error during the conversion process.
AudioFrequencyConverter¶
Bases: Converter
Shifts the frequency of an audio file up by a specified value. By default, it will shift it above the human hearing range (=20 kHz).
The shift moves the whole spectrum up without a mirrored lower sideband. When the shift is non-zero, the output is written at a sample rate high enough to hold the shifted spectrum, so it does not alias back into the audible band. Channel layout is preserved, and floating-point WAV input retains its sample dtype and amplitude scale.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | str | The format of the audio file, defaults to “wav”. |
shift_value | int | The value in Hz by which the frequency will be shifted up, defaults to 20000 Hz. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'audio_path') → ConverterResultConvert the given audio file by shifting its frequency.
| Parameter | Type | Description |
|---|---|---|
prompt | str | File path to the audio file to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'audio_path'. |
Returns:
ConverterResult— The result containing the audio file path.
Raises:
ValueError— If the input type is not supported.Exception— If there is an error during the conversion process.
AudioSpeedConverter¶
Bases: Converter
Changes the playback speed of an audio file.
A speed_factor > 1.0 speeds up the audio (shorter duration), while a speed_factor < 1.0 slows it down (longer duration). The converter resamples the audio signal using interpolation so that the sample rate, bit depth, and number of channels remain unchanged.
Because the samples are resampled rather than time-stretched, the pitch changes together with the speed, like playing a tape faster or slower. For example, a speed_factor of 2.0 raises a 440 Hz tone to about 880 Hz.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | str | The format of the audio file, defaults to “wav”. |
speed_factor | float | The factor by which to change the speed. Values > 1.0 speed up the audio, values < 1.0 slow it down. Must be finite, greater than 0, and at most 100. Defaults to 1.5. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'audio_path') → ConverterResultConvert the given audio file by changing its playback speed.
The audio is resampled via interpolation so that the output has a different number of samples (and therefore a different duration) while keeping the original sample rate. The pitch shifts by the same factor as the speed.
| Parameter | Type | Description |
|---|---|---|
prompt | str | File path to the audio file to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'audio_path'. |
Returns:
ConverterResult— The result containing the converted audio file path.
Raises:
ValueError— If the input type is not supported, or if the speed factor would leave no samples in the converted audio.Exception— If there is an error during the conversion process.
AudioVolumeConverter¶
Bases: Converter
Changes the volume of an audio file by scaling the amplitude.
A volume_factor > 1.0 increases the volume (louder), while a volume_factor < 1.0 decreases it (quieter). A volume_factor of 1.0 leaves the audio unchanged. The converter scales all audio samples by the given factor and clips the result to the valid range for the original data type. Sample rate, bit depth, and number of channels are preserved. Unsigned 8-bit PCM is scaled around its silence midpoint of 128.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | str | The format of the audio file, defaults to “wav”. |
volume_factor | float | The factor by which to scale the volume. Values > 1.0 increase volume, values < 1.0 decrease volume. Must be finite and greater than 0. Defaults to 1.5. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'audio_path') → ConverterResultConvert the given audio file by changing its volume.
The audio samples are scaled by the volume factor. For integer audio formats the result is clipped to prevent overflow.
| Parameter | Type | Description |
|---|---|---|
prompt | str | File path to the audio file to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'audio_path'. |
Returns:
ConverterResult— The result containing the converted audio file path.
Raises:
ValueError— If the input type is not supported.Exception— If there is an error during the conversion process.
AudioWhiteNoiseConverter¶
Bases: Converter
Adds white noise to an audio file.
White noise is generated and mixed into the original signal at a level controlled by the noise_scale parameter. The output preserves the original sample rate, bit depth, channel count, and number of samples.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | str | The format of the audio file, defaults to “wav”. |
noise_scale | float | Controls the amplitude of the added noise, expressed as a fraction of the signal’s maximum possible value. For int16 audio the noise amplitude will be noise_scale * 32767. Must be finite, greater than 0, and at most 1.0. Defaults to 0.02. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'audio_path') → ConverterResultConvert the given audio file by adding white noise.
| Parameter | Type | Description |
|---|---|---|
prompt | str | File path to the audio file to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'audio_path'. |
Returns:
ConverterResult— The result containing the converted audio file path.
Raises:
ValueError— If the input type is not supported.Exception— If there is an error during the conversion process.
AzureSpeechAudioToTextConverter¶
Bases: Converter
Transcribes a .wav audio file into text using Azure AI Speech service.
Authentication is auto-detected from the provided credentials, in priority order:
If
azure_speech_keyis a callable token provider, it takes highest priority — it is resolved at conversion time and used with Entra ID auth (azure_speech_resource_idrequired).If
azure_speech_keyis a string (or theAZURE_SPEECH_KEYenv var is set), API key auth is used.If neither is provided, Entra ID auth is used automatically via
DefaultAzureCredentialandazure_speech_resource_idmust be set.
https://
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
azure_speech_region | (str, Optional) | The name of the Azure region. Defaults to None. |
azure_speech_key | (str | Callable[[], str | Awaitable[str]], Optional) | The API key for accessing the service, or a sync/async callable that returns a token string. If a string key is provided (or the AZURE_SPEECH_KEY env var is set), key auth is used. If a callable token provider is provided, it is resolved at conversion time and used with Entra ID auth (azure_speech_resource_id must also be set). If omitted, Entra ID auth via DefaultAzureCredential is used automatically. Defaults to None. |
azure_speech_resource_id | (str, Optional) | The resource ID for accessing the service when using Entra ID auth. Required when using a callable token provider or when no API key is available. Defaults to None. |
recognition_language | str | Recognition voice language. Defaults to “en-US”. For more on supported languages, see the following link: https:// |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'audio_path') → ConverterResultConvert the given audio file into its text representation.
| Parameter | Type | Description |
|---|---|---|
prompt | str | File path to the audio file to be transcribed. |
input_type | PromptDataType | The type of input data. Defaults to 'audio_path'. |
Returns:
ConverterResult— The result containing the transcribed text.
Raises:
ValueError— If the input type is not supported or if the provided file is not a .wav file.
stop_cb¶
stop_cb(evt: Any, recognizer: Any) → NoneStop continuous recognition upon receiving an event ‘evt’.
Connected to both canceled and session_stopped: only a cancellation event carries a
result with cancellation details, a session event (SessionEventArgs) has none.
| Parameter | Type | Description |
|---|---|---|
evt | speechsdk.SessionEventArgs | Event, a SpeechRecognitionCanceledEventArgs on cancellation. |
recognizer | speechsdk.SpeechRecognizer | Speech recognizer object. |
Raises:
ModuleNotFoundError— If the azure.cognitiveservices.speech module is not installed.
transcript_cb¶
transcript_cb(evt: Any, transcript: list[str]) → NoneAppend transcribed text upon receiving a “recognized” event.
| Parameter | Type | Description |
|---|---|---|
evt | speechsdk.SpeechRecognitionEventArgs | Event. |
transcript | list | List to store transcribed text. |
AzureSpeechTextToAudioConverter¶
Bases: Converter
Generates a wave file from a text prompt using Azure AI Speech service.
Authentication is auto-detected from the provided credentials, in priority order:
If
azure_speech_keyis a callable token provider, it takes highest priority — it is resolved at conversion time and used with Entra ID auth (azure_speech_resource_idrequired).If
azure_speech_keyis a string (or theAZURE_SPEECH_KEYenv var is set), API key auth is used.If neither is provided, Entra ID auth is used automatically via
DefaultAzureCredentialandazure_speech_resource_idmust be set.
https://
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
azure_speech_region | (str, Optional) | The name of the Azure region. Defaults to None. |
azure_speech_key | (str | Callable[[], str | Awaitable[str]], Optional) | The API key for accessing the service, or a sync/async callable that returns a token string. If a string key is provided (or the AZURE_SPEECH_KEY env var is set), key auth is used. If a callable token provider is provided, it is resolved at conversion time and used with Entra ID auth (azure_speech_resource_id must also be set). If omitted, Entra ID auth via DefaultAzureCredential is used automatically. Defaults to None. |
azure_speech_resource_id | (str, Optional) | The resource ID for accessing the service when using Entra ID auth. Required when using a callable token provider or when no API key is available. Defaults to None. |
synthesis_language | str | Synthesis voice language. Defaults to 'en_US'. |
synthesis_voice_name | str | Synthesis voice name. For more details see the following link for synthesis language and synthesis voice: https://'en-US-AvaNeural'. |
output_format | str | Either wav or mp3. Must match the file prefix. Defaults to 'wav'. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given text prompt into its audio representation.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The text prompt to be converted into audio. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the audio file path.
Raises:
ModuleNotFoundError— If theazure.cognitiveservices.speechmodule is not installed.RuntimeError— If there is an error during the speech synthesis process.ValueError— If the input type is not supported or if the prompt is empty.
Base2048Converter¶
Bases: Converter
Converter that encodes text to base2048 format.
This converter takes input text and converts it to base2048 encoding, which uses 2048 different Unicode characters to represent binary data. This can be useful for obfuscating text or testing how systems handle encoded Unicode content.
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt to base2048 encoding.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | Type of data, unused for this converter. Defaults to 'text'. |
Returns:
ConverterResult— The converted text representation of the original prompt in base2048.
Raises:
ValueError— If the input type is not supported.
Base64Converter¶
Bases: Converter
Converter that encodes text to base64 format.
This converter takes input text and converts it to base64 encoding, which can be useful for obfuscating text or testing how systems handle encoded content.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
encoding_func | EncodingFunc | The base64 encoding function to use. Defaults to “b64encode”. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt to base64 encoding.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | Type of data, unused for this converter. Defaults to 'text'. |
Returns:
ConverterResult— The converted text representation of the original prompt in base64.
Raises:
ValueError— If the input type is not supported.
BidiConverter¶
Bases: Converter
Wraps text in Unicode bidirectional control characters.
The converter surrounds the prompt with a matched pair of bidirectional formatting code points so that the logical (stored) code point order can differ from the order a human reader sees rendered. This is the family of manipulation behind the “Trojan Source” findings (CVE-2021-42574). The transformation is deterministic: no language model or randomness is involved, so the same input and scheme always produce the same output.
Schemes (per the Unicode Bidirectional Algorithm, UAX #9):
- "override": RIGHT-TO-LEFT OVERRIDE (U+202E) ... POP DIRECTIONAL FORMATTING (U+202C).
- "embedding": RIGHT-TO-LEFT EMBEDDING (U+202B) ... POP DIRECTIONAL FORMATTING (U+202C).
- "isolate": RIGHT-TO-LEFT ISOLATE (U+2067) ... POP DIRECTIONAL ISOLATE (U+2069).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
scheme | Literal['override', 'embedding', 'isolate'] | The bidirectional control scheme used to wrap the prompt. Defaults to "override". |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by wrapping it in bidirectional control characters.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the wrapped text, or an empty string if theConverterResult— prompt is empty.
Raises:
ValueError— If the input type is not supported.
BifidConverter¶
Bases: Converter
Encodes text using the Bifid cipher.
The Bifid cipher, invented by Felix Delastelle around 1901, is a classical fractionating transposition cipher. It combines a Polybius square with transposition to achieve diffusion: each plaintext letter is first replaced by its (row, column) coordinates in a 5x5 Polybius square, the coordinates are then fractionated (all rows written out, followed by all columns), and finally re-paired into new coordinates that are mapped back to letters. Because the two coordinates of a single ciphertext letter are typically drawn from two different plaintext letters, a single-character change in the plaintext affects multiple ciphertext characters.
The 5x5 Polybius square holds 25 cells, so one pair of letters must share a cell; by
convention I and J are merged (any J in the plaintext is treated as I). The
square can be seeded with a keyword via the key argument: the (de-duplicated) keyword
letters are placed first, followed by the remaining letters of the alphabet. With the
default empty key the square is the plain alphabet ABCDEFGHIKLMNOPQRSTUVWXYZ.
Fractionation can be performed over the whole message at once (the default, period=0) or
in fixed-size blocks when a positive period is supplied, matching the classic
period-based Bifid variant.
Non-letter characters (spaces, digits, punctuation) and the I/J merge mean the
transformation is not perfectly reversible; this converter uppercases the input, drops every
character that is not an ASCII letter, and returns a contiguous block of uppercase
ciphertext letters.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
key | str | Keyword used to seed the 5x5 Polybius square. Non-letter characters are ignored and letters are de-duplicated (keeping first occurrence) before the rest of the alphabet is appended. J is treated as I. Defaults to an empty string, which yields the plain-alphabet square ABCDEFGHIKLMNOPQRSTUVWXYZ. |
period | int | Size of the fractionation block. 0 (the default) fractionates the entire message as a single block. A positive value splits the message into blocks of that many letters, fractionating each independently. Defaults to 0. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt using the Bifid cipher.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input prompt to be converted. |
input_type | PromptDataType | The type of the input prompt. Must be “text”. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted prompt and its type.
Raises:
ValueError— If the input type is not supported.
BinAsciiConverter¶
Bases: WordLevelConverter
Converts text to various binary-to-ASCII encodings.
Supports hex, quoted-printable, and UUencode formats.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
encoding_func | str | The encoding function to use. Options: “hex”, “quoted-printable”, “UUencode”. Defaults to “hex”. |
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, all words will be converted. Defaults to None. |
word_split_separator | str | None | Separator used to split words in the input text. Defaults to " ". |
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a word using the specified encoding function.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to encode. |
Returns:
str— The encoded word.
Raises:
ValueError— If an unsupported encoding function is encountered.
join_words¶
join_words(words: list[str]) → strJoin words appropriately based on the encoding type and selection mode.
Empty words do not emit UU records, since zero-length records terminate stream decoders. Encoded separators still preserve the original spacing.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of encoded words to join. |
Returns:
str— The joined string.
BinaryConverter¶
Bases: WordLevelConverter
Transforms input text into its binary representation with configurable bits per character (8, 16, or 32).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
bits_per_char | BinaryConverter.BitsPerChar | Number of bits to use for each character (8, 16, or 32). Default is 16 bits. Defaults to BitsPerChar.BITS_16. |
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, all words will be converted. Defaults to None. |
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
Raises:
ValueError— Ifbits_per_charis too small to represent any character in the word.
join_words¶
join_words(words: list[str]) → strJoin the converted words with the binary representation of a space.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of converted words. |
Returns:
str— The final joined string with spaces in binary format.
validate_input¶
validate_input(prompt: str) → NoneValidate the bit width of selected words (deprecated until 1.4.0).
Subclass overrides may still call this method via super(). After removal,
standalone preflight is caller-owned: inherited WordLevelConverter.validate_input
does not check bit width.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input text prompt to validate. |
Raises:
ValueError— Ifbits_per_charis too small to represent any character in the prompt.
BrailleConverter¶
Bases: Converter
Converts text into Braille Unicode representation.
This converter transforms standard text into Braille patterns using Unicode Braille characters (U+2800 to U+28FF). Every printable ASCII character is mapped: letters, digits, punctuation, and symbols. Uppercase letters are prefixed with the Braille capitalization indicator and digit runs with the number indicator. A letter from a to j directly after a number is prefixed with the letter sign, so it is not read as another digit. Characters with no Braille mapping (accented and CJK letters, emoji, control characters) pass through unchanged rather than being dropped, so the encoded prompt keeps its meaning.
The letter, digit, and core punctuation mappings are based on the
implementation from Garak:
garak
Note: This converter is useful for testing how AI systems handle Braille-encoded text, which can be used to obfuscate potentially harmful content.
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given text into Braille Unicode representation.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The text to be converted to Braille. |
input_type | PromptDataType | Type of input data. Defaults to “text”. |
Returns:
ConverterResult— The text converted to Braille Unicode characters.
Raises:
ValueError— If the input type is not supported (only “text” is supported).
CaesarConverter¶
Bases: Converter
Encodes text using the Caesar cipher with a specified offset.
Using offset=1, ‘Hello 123’ would encode to ‘Ifmmp 234’, as each character would shift by 1.
Letters shift by the offset modulo 26 and ASCII digits 0-9 by the offset modulo 10, so negative
offsets shift backwards and offset=13 encodes ‘Room 12’ to ‘Ebbz 45’.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
caesar_offset | int | Offset for caesar cipher, range 0 to 25 (inclusive). Can also be negative for shifting backwards. |
append_description | bool | If True, appends plaintext “expert” text to the prompt. This includes instructions to only communicate using the cipher, a description of the cipher, and an example encoded using the cipher. Defaults to False. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt using the Caesar cipher.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input prompt to be converted. |
input_type | PromptDataType | The type of the input prompt. Must be “text”. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted prompt and its type.
Raises:
ValueError— If the input type is not supported.
CharNoiseConverter¶
Bases: Converter
Nudges printable ASCII characters to an adjacent codepoint.
Each character is shifted one step up or down with probability noise_probability,
kept inside the printable ASCII range. Non-ASCII characters are left alone. Unlike
NoiseConverter this uses no LLM. Randomness is drawn from the converter’s own
stream, so a configured root seed makes the output reproducible.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
noise_probability | float | Per-character probability in [0.0, 1.0] of nudging a character to an adjacent codepoint. Defaults to 0.05. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultApply one fresh pass of ASCII noise to the prompt.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The text prompt to perturb. |
input_type | PromptDataType | The input data type. Only text is supported. Defaults to 'text'. |
Returns:
ConverterResult— The perturbed prompt.
Raises:
ValueError— If the input type is not supported.
CharSwapConverter¶
Bases: WordLevelConverter
Applies character swapping to words in the prompt to test adversarial textual robustness.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
max_iterations | int | Number of times to generate perturbed prompts. The higher the number the higher the chance that words are different from the original prompt. Defaults to 10. |
seed | int | None | Optional seed for reproducible character swaps. Defaults to None. |
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, defaults to WordProportionSelectionStrategy(proportion=0.2). |
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
CharacterSpaceConverter¶
Bases: Converter
Spaces out the input prompt and removes ASCII punctuation except backslashes.
Characters are grapheme clusters, so combining marks, Indic vowel signs and emoji sequences stay whole.
For more information on the bypass strategy, refer to Priyanshu, 2024.
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by removing punctuation and spacing out characters.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input text prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted text.
Raises:
ValueError— If the input type is not supported.
CodeAttackConverter¶
Bases: Converter
Encodes a prompt as a code-completion task (CodeAttack, Ren et al. ACL 2024).
The prompt is encoded into a data-structure initialisation sequence embedded inside a partial code template. The model is asked to complete the code, which sidesteps natural-language safety training.
Separator normalisation. How much of the input survives the encode step depends on the encoding, because each one splits the prompt differently:
PYTHON_STRING,CPPandGOembed the prompt as a single string literal. Every character survives, including whitespace runs, hyphens, tabs, newlines and non-BMP characters such as emoji. These round-trip byte-identically.PYTHON_LISTsplits onstr.split(), so any run of whitespace (spaces, tabs, newlines) collapses to a single token boundary and leading and trailing whitespace is dropped. Hyphens are preserved inside tokens. Round-trips losslessly only when words are separated by single spaces.PYTHON_STACKsplits on[\s\-]+, so it collapses whitespace runs exactly likePYTHON_LISTand additionally consumes hyphens as delimiters. It also reverses token order (the template’sdecode()pops the stack). A prompt that yields a single token is exploded into individual characters. Round-trips losslessly only when words are separated by single spaces and contain no hyphens.
In every case the encoded literals are escaped for the target language, so quotes, backslashes and control characters cannot break out of the literal.
Template and encoding pairing. Each built-in Template ships a wrapper
that only works with one Encoding, so the enum implies the encoding and
passing encoding= alongside a built-in is rejected. A pathlib.Path
demands an explicit encoding=, because the data structure cannot be
inferred from a custom file. In short: enum implies, Path demands.
CodeAttack Ren et al., 2024.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
template | CodeAttackConverter.Template | pathlib.Path | The code template to render. Pass a CodeAttackConverter.Template member to use one of the built-in templates, or a pathlib.Path to a custom YAML file. Defaults to Template.PYTHON_STACK_VERBOSE. |
encoding | CodeAttackConverter.Encoding | None | The data structure the objective is encoded into. A built-in Template implies its encoding, so passing this alongside one is rejected: each built-in ships a wrapper that only works with its mapped encoding, and pairing it with another would declare one data structure, populate a different one, and decode from the empty original. A pathlib.Path demands it, because the data structure cannot be inferred from a custom file. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultEncode the prompt into a code-completion template.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The natural-language prompt to encode. |
input_type | PromptDataType | Must be "text". Defaults to 'text'. |
Returns:
ConverterResult— ConverterResult containing the code-completion template with theConverterResult— prompt encoded as data-structure initialisation calls.
Raises:
ValueError— If the input type is not supported.
CodeChameleonConverter¶
Bases: Converter
Encrypts user prompt, adds stringified decrypt function in markdown and instructions.
The user prompt is encrypted, and the target is asked to solve the encrypted problem by completing a ProblemSolver class utilizing the decryption function while following the instructions.
Code Chameleon Converter Lv et al., 2024.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
encrypt_type | str | Must be one of “custom”, “reverse”, “binary_tree”, “odd_even” or “length”. |
encrypt_function | Callable | User provided encryption function. Only used if encrypt_mode is “custom”. Used to encode user prompt. Defaults to None. |
decrypt_function | Callable or list | User provided encryption function. Only used if encrypt_mode is “custom”. Used as part of markdown code block instructions in system prompt. If list is provided, strings will be treated as single statements for imports or comments. Functions will take the source code of the function. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by applying the specified encryption function.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted prompt.
Raises:
ValueError— If the input type is not supported.
ColloquialWordswapConverter¶
Bases: Converter
Converts text by replacing words with regional colloquial alternatives.
Supports loading substitutions from YAML files (e.g., Singaporean, Filipino, Indian) or accepting a custom substitution dictionary. Defaults to Singaporean substitutions.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
deterministic | bool | If True, use the first substitution for each wordswap. If False, randomly choose a substitution for each wordswap. Defaults to False. |
custom_substitutions | dict[str, list[str]] | None | A dictionary of custom substitutions to override the defaults. Defaults to None. |
wordswap_path | Path | None | Path to a YAML file containing word substitutions. Can be a filename within the built-in colloquial_wordswaps directory (e.g., “filipino.yaml”) or an absolute path to a custom YAML file. Defaults to None (uses singaporean.yaml). |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by replacing words with regional colloquial alternatives.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input text prompt to be converted. |
input_type | PromptDataType | The type of the input prompt. Defaults to “text”. |
Returns:
ConverterResult— The result containing the converted prompt.
Raises:
ValueError— If the input type is not supported.
ColumnarTranspositionConverter¶
Bases: Converter
Encodes text using the (incomplete-columns) columnar transposition cipher.
The columnar transposition cipher is a classical transposition cipher: the plaintext is written row-wise into a grid whose number of columns equals the length of a keyword, and the ciphertext is produced by reading the columns out one at a time in the alphabetical order of the keyword’s letters. It is a pure permutation of the input characters (no letters are substituted), so every character of the prompt - including spaces, digits, and punctuation - is placed in the grid and the transformation is fully reversible given the keyword and the message length.
This implementation uses the standard incomplete-columns variant: the final row of the grid may be only partially filled, producing columns of unequal length, and no padding characters are added. Ties between repeated keyword letters are broken by their original left-to-right position (a stable sort), the usual convention.
Using key="ZEBRAS", the classic worked example ‘WEAREDISCOVEREDFLEEATONCE’ encodes to
‘EVLNACDTESEAROFODEECWIREE’.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
key | str | The keyword whose length sets the number of columns and whose alphabetical letter order determines the column read-out order. Must consist of alphabetic characters only. Ordering is case-insensitive; repeated letters keep their original left-to-right order. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt using the columnar transposition cipher.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input prompt to be converted. |
input_type | PromptDataType | The type of the input prompt. Must be “text”. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted prompt and its type.
Raises:
ValueError— If the input type is not supported.
ContentWordSelectionStrategy¶
Bases: WordSelectionStrategy
Selects content words with a deterministic, dependency-free heuristic.
A token is treated as a content word when, after stripping punctuation, it
contains letters, meets min_word_length, and is not in the stopword
list. Selection is left-to-right. This approximates POS-based noun/verb
masking used by Simple Assistive Task Linkage (SATA) without downloading
an NLTK tagger.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
max_words | int | Maximum number of content words to select. Defaults to 2. |
skip_first | int | Number of leading content words to leave unmasked. Defaults to 1, approximating SATA’s skip-first-verb/noun behavior. |
min_word_length | int | Minimum alphabetic length after punctuation is stripped. Defaults to 3. |
stopwords | Collection[str] | None | Function words to ignore. Defaults to DEFAULT_CONTENT_STOPWORDS. |
candidate_words | Collection[str] | None | Optional allowlist. When set, only these words (case-insensitive, punctuation-stripped) are eligible. Defaults to None (all content words). |
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the content-word selection configuration.
Stopwords and candidate words are stored as sorted lists so order does not affect identifier equality.
Returns:
dict[str, Any]— dict[str, Any]: Selection limits, stopwords, and optional candidates.
select_words¶
select_words(words: list[str]) → list[int]Select up to max_words content-word indices, skipping the first few.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of words to select from. |
Returns:
list[int]— list[int]: Indices of selected content words, in left-to-right order.
Converter¶
Bases: Identifiable
Base class for converters that transform prompts into a different representation or format.
Concrete subclasses must declare their supported input and output modalities using class attributes:
SUPPORTED_INPUT_TYPES: tuple of PromptDataType values that the converter accepts
SUPPORTED_OUTPUT_TYPES: tuple of PromptDataType values that the converter produces
These attributes are enforced at class definition time for all non-abstract subclasses.
Concrete convert_async implementations are also wrapped at class definition time so
named random streams are scoped to one input. Stochastic subclasses should obtain randomness
through _get_random_generator and store an optional explicit constructor seed in _seed.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | None | Target used by the converter, if any. When provided, it is validated against TARGET_REQUIREMENTS. Defaults to None. |
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted output and its type.
convert_tokens_async¶
convert_tokens_async(prompt: str, input_type: PromptDataType = 'text', start_token: str = '⟪', end_token: str = '⟫', keep_tokens: bool = False) → ConverterResultConvert innermost marked regions, optionally retaining their delimiters.
Regions may be empty, span multiple lines, and nest. Each call converts all innermost regions and retains their outer delimiters for later calls. With keep_tokens=True, the selected pairs are retained too. Identical start and end delimiters form flat pairs. Without delimiters, the entire prompt is converted, including non-text inputs. Selected regions require text input and text output. All delimiters are validated before any conversion is invoked. If a region fails, the regions still running are cancelled and awaited before its error is raised.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input prompt containing text to be converted. |
input_type | str | The type of input data. Defaults to “text”. |
start_token | str | The token indicating the start of a substring to be converted. Defaults to “⟪” which is relatively distinct. |
end_token | str | The token indicating the end of a substring to be converted. Defaults to “⟫” which is relatively distinct. |
keep_tokens | bool | Retain each selected pair around its converted text. With no markers, wrap the whole text result. Non-text results are unchanged. Defaults to False. |
Returns:
ConverterResult— The prompt with specified substrings converted.
Raises:
ValueError— If delimiters are empty, regions are malformed, or selected regions cannot be converted from text to text.
get_reconstruction_parameters¶
get_reconstruction_parameters() → dict[str, object]Return server-only constructor inputs for a separate converter.
Returns:
dict[str, object]— dict[str, object]: Inputs retained when the source was constructed.
Raises:
ValueError— If the constructor did not retain its inputs.
input_supported¶
input_supported(input_type: PromptDataType) → boolCheck if the input type is supported by the converter.
| Parameter | Type | Description |
|---|---|---|
input_type | PromptDataType | The input type to check. |
Returns:
bool— True if the input type is supported, False otherwise.
output_supported¶
output_supported(output_type: PromptDataType) → boolCheck if the output type is supported by the converter.
| Parameter | Type | Description |
|---|---|---|
output_type | PromptDataType | The output type to check. |
Returns:
bool— True if the output type is supported, False otherwise.
ConverterResult¶
The result of a prompt conversion, containing the converted output and its type.
DRAConverter¶
Bases: Converter
Disguises a prompt letter by letter and asks the target to rebuild and answer it.
The Disguise and Reconstruction Attack (DRA) Liu et al., 2024 spells the lowercased prompt one
character per line, each hidden in parentheses inside a harmless phrase such as happy (h)our.
It then appends a template with a word guide (the prompt’s words, with flagged words cut short)
and instructions to rebuild the request and open the answer with an agreeing sentence. No single
line contains the request.
This is garak’s single-shot version, without the paper’s retry that cuts words shorter after a refusal. A word counts as flagged when it exactly matches the paper’s list of words that Detoxify scored as toxic.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
prompt_template | SeedPrompt | None | The template appended after the disguised prompt, such as DRATemplate.PREPARE_TOOLS.to_seed_prompt(). It must declare a word_guide parameter and may also declare tools. If not provided, each conversion picks a DRATemplate from the seeded random stream. Defaults to None. |
harmful_keep_ratio | float | Lowest share of a flagged word of 5 or more characters to keep. The cut falls at a random index from max(2, int(length * harmful_keep_ratio)) to length - 1, so a higher value keeps more of the word. Must be between 0 and 1, exclusive. Defaults to 0.5. |
benign_keep_ratio | float | Lowest share of a cut benign word to keep. The cut falls at a random index from min(length * 2 // 3, int(length * benign_keep_ratio)) to length - 1, and never before the first character, so values above two thirds have no effect. Must be between 0 and 1, exclusive. Defaults to 0.5. |
benign_full_word_probability | float | Probability that a benign word of 4 or more characters is kept whole. Lower values give the target fewer hints. Must be between 0 and 1, inclusive. Defaults to 0.33. |
seed | int | None | Seed for the template pick and the truncation. Pass an int for reproducible output; leave as None to inherit the root configured by initialize_pyrit_async(seed=...). Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultDisguise the prompt and append the rendered DRA template.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The request to disguise. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The disguise lines followed by the rendered template.
Raises:
ValueError— If the input type is not supported.
DRATemplate¶
Bases: enum.Enum
Selectable DRA answer-forcing templates.
Each member maps to a named template in dra_converter.yaml. The PREPARE_TOOLS
templates also name two tools the answer should start by preparing; the STRICT
templates use the paper’s firmer wording for Llama models.
Examples:
Methods:
to_seed_prompt¶
to_seed_prompt() → SeedPromptLoad the SeedPrompt template backing this enum member.
Returns:
SeedPrompt— The template prompt for this member.
DecompositionConverter¶
Bases: Converter
Decompose-and-reconstruct converter based on DrAttack Li et al., 2024.
The converter splits the objective into ordered, role-tagged phrases using an LLM, then rebuilds it as a fragmented “Question A / Question B” task plus a static benign in-context demonstration. The target is asked to answer the disaggregated questions jointly, reconstructing the original intent itself, so the assembled harmful instruction never appears verbatim in the request.
The decomposition is requested as a flat {"words": [...], "types": [...]} JSON object (easier
to validate than a nested parse tree), constrained by the response_json_schema declared in the
system prompt. The response is validated against a reconstruction-recall invariant (the joined
phrases must preserve the original tokens) plus valid-tag and opening-instruction checks; on
failure an InvalidJsonException is raised, which @pyrit_json_retry retries.
DrAttack paper: Li et al., “DrAttack: Prompt Decomposition and Reconstruction Makes Powerful
LLM Jailbreakers”, Findings of EMNLP 2024, https://
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The endpoint used to decompose the objective. Must satisfy CHAT_TARGET_REQUIREMENTS. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
decomposition_prompt | SeedPrompt | None | System prompt instructing the model how to decompose a sentence (carries the response JSON schema). Defaults to the bundled decomposition/decomposition_system_prompt.yaml. |
reconstruction_prompt | SeedPrompt | None | Template that renders the decomposed objective into the reconstruction task. Defaults to the bundled decomposition/reconstruction_prompt.yaml. |
use_word_game | bool | If True, each harmful noun phrase is replaced by an innocuous codeword in the reconstruction questions, and a mapping preamble is prepended in the same prompt. Defaults to False. |
word_game_prompt | SeedPrompt | None | Template for the word-game mapping preamble. Defaults to the bundled decomposition/word_game_preamble.yaml. Only used when use_word_game is True. |
codewords | tuple[str, ...] | Innocuous codewords substituted for harmful noun phrases when the word-game is enabled. Defaults to a bundled list of fruit names. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the objective into a decompose-and-reconstruct prompt.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The objective to convert. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The reconstruction prompt.
Raises:
ValueError— If the input type is not supported.InvalidJsonException— If decomposition does not produce a valid result within the retries.
DenylistConverter¶
Bases: LLMGenericTextConverter
Replaces forbidden words or phrases in a prompt with synonyms using an LLM.
An existing PromptTarget is used to perform the conversion (like Azure OpenAI).
Matching is Unicode-aware and case-insensitive without changing the prompt’s casing.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The target for the prompt conversion. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
system_prompt_template | SeedPrompt | None | The system prompt template to use for the conversion. If not provided, a default template will be used. Defaults to None. |
denylist | list[str] | A list of words or phrases that should be replaced in the prompt. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by removing any words or phrases that are in the denylist, replacing them with synonymous words.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the modified prompt.
DiacriticConverter¶
Bases: Converter
Applies diacritics to specified characters in a string.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
target_chars | str | Characters to apply the diacritic to. Defaults to “aeiou”. |
accent | str | Type of diacritic to apply (default is ‘acute’). Available options are: - acute: ́ - grave: ̀ - tilde: ̃ - umlaut: ̈ Defaults to 'acute'. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by applying diacritics to specified characters.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The text prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the modified text.
Raises:
ValueError— If the input type is not supported.
DigitBijectionConverter¶
Bases: BijectionConverter
Bijection converter that maps letters to random digit strings. Each English letter maps to a randomly-selected num_digits-digit number. Based on mode 2 from the Bijection Learning attack Huang et al., 2024.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
num_digits | int | Length of digit strings to map letters to (2-4). Defaults to 2. |
mapping | (dict[str, str], Optional) | Explicit mapping dict. If provided, used directly. Defaults to None. |
seed | (int, Optional) | Random seed for reproducibility. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultEncode the prompt using digit tokens.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the encoded prompt.
Raises:
ValueError— If the input type is not supported.
decode¶
decode(encoded_text: str) → strDecode digit-token text back to plaintext.
Unrecognized characters and incomplete escapes are preserved.
| Parameter | Type | Description |
|---|---|---|
encoded_text | str | The encoded text to decode. |
Returns:
str— The decoded plain text.
encode¶
encode(prompt: str) → strEncode text using digit tokens, uppercase markers, and literal-digit escapes.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to encode. |
Returns:
str— The encoded prompt.
get_teaching_instructions¶
get_teaching_instructions() → strReturn the digit-mode setup instructions.
Returns:
str— Instructions for using this digit mapping and its markers.
EcojiConverter¶
Bases: Converter
Converter that encodes text using Ecoji encoding.
Ecoji is an encoding scheme that represents binary data using emojis. See https://ecoji.io/ for more details.
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt to Ecoji encoding.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The text to encode. |
input_type | PromptDataType | The type of input. Defaults to “text”. |
Returns:
ConverterResult— The result containing the Ecoji-encoded text.
Raises:
ValueError— If the input type is not supported.
EmojiConverter¶
Bases: WordLevelConverter
Converts English text to randomly chosen circle or square character emojis.
Inspired by src/utils.ts
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
seed | int | None | Optional seed for reproducible output. Defaults to None. |
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, all words will be converted. Defaults to None. |
word_split_separator | str | None | Separator used to split words in the input text. Defaults to ' '. |
**kwargs | Any | Forwarded to WordLevelConverter for cooperative multiple inheritance. Defaults to {}. |
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
FirstLetterConverter¶
Bases: WordLevelConverter
Replaces each word of the prompt with its first letter (or digit). Whitespace and words that do not contain any letter or digit are ignored.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
letter_separator | str | The string used to join the first letters. Defaults to ' '. |
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, all words will be converted. Defaults to None. |
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
join_words¶
join_words(words: list[str]) → strJoin the converted words using the specified letter separator.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of converted words. |
Returns:
str— The joined string of converted words.
FlipConverter¶
Bases: Converter
Flips the input text prompt by reversing its extended grapheme clusters.
For example, “hello me” would be converted to “em olleh”. Multi-code-point sequences like emoji ZWJ sequences, skin-tone modifiers, combining marks, and Indic conjuncts stay together in their perceived clusters.
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by reversing the text.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | Type of data. Defaults to 'text'. |
Returns:
ConverterResult— The converted text representation of the original prompt with characters reversed.
Raises:
ValueError— If the input type is not supported.
FullwidthConverter¶
Bases: WordLevelConverter
Converts printable ASCII characters to their fullwidth Unicode forms.
Letters, digits and punctuation in the range U+0021 to U+007E map to the Halfwidth and Fullwidth Forms block (U+FF01 to U+FF5E), so “Hello!” becomes “Hello!”. Characters outside that range, including spaces between words, are left unchanged. The output normalizes back to the original text under NFKC, which makes this a useful probe for filters or classifiers that match on exact characters without normalizing the input first.
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into its fullwidth form.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The word with printable ASCII characters replaced by fullwidth characters.
GridCompositeConverter¶
Bases: _BaseImageTextConverter
Renders the prompt text into a composite grid where one cell carries the text payload and the remaining cells are innocuous images.
The grid defaults to 2x2 (four-quadrant split) but any grid_size
with at least two cells is supported.
Selection of the payload cell and the innocuous images is seeded from
random_seed so a given configuration always produces the same composite,
keeping the converter’s identity (and any downstream technique evaluation
hash) stable.
Reference: DMN (ACL 2026) quadrant-splitting; “Beyond Visual Safety” (arXiv:2601.15698) neutralized visual splicing.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
innocuous_images | Sequence[Path | str] | Bank of benign image paths (or Azure Blob URLs) to fill the non-payload cells. Must contain at least rows * cols - 1 entries. Bank entries are sampled without replacement; duplicate paths are treated as distinct entries and may therefore produce identical tiles. |
grid_size | tuple[int, int] | Grid layout as (rows, cols). Must contain at least two cells. Defaults to (2, 2). |
tile_size | tuple[int, int] | Size of each cell as (width, height) in pixels; every image is resized to this and the payload text is rendered within it. Defaults to (400, 400). |
payload_position | int | None | Row-major index (0-based) of the cell that carries the objective text. When None (default), a cell is chosen deterministically from random_seed. |
payload_background | Path | str | None | Optional background image for the payload cell. When None (default), the text is rendered on a white cell. |
font_name | Path | None | Path of the font to use. Must be a TrueType font (.ttf). Defaults to None, which uses Pillow’s built-in default font. |
color | tuple[int, int, int] | Text color as RGB values. Defaults to (0, 0, 0). |
font_size | int | tuple[int, int] | Font size for the payload text as a fixed int, or a (min, max) tuple for automatic sizing that shrinks from max down to min to fit the text in the cell. A long objective that overflows even at the minimum size logs a warning rather than being silently clipped. Defaults to (8, 20). |
random_seed | int | Seed controlling the payload cell and innocuous-image selection. Kept in the identifier so identical configurations produce identical composites. Defaults to 42. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultRender the prompt text into the payload cell of an innocuous composite grid.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The objective text to render into the payload cell. |
input_type | PromptDataType | The type of input data. Must be “text”. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the path to the composite image.
Raises:
ValueError— If the input type is not supported orpromptis empty.
IPAConverter¶
Bases: LLMGenericTextConverter
Converts text to broad International Phonetic Alphabet (IPA) transcription using an LLM.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The target that performs the transcription. Defaults to REQUIRED_VALUE. |
dialect | str | None | The language variety or dialect to use for pronunciation. When omitted, the converter infers the language and dialect from the input. Defaults to None. |
Examples:
ImageBlurConverter¶
Bases: BaseImageToImageConverter
Applies a Gaussian blur to an image.
This converter uses PIL’s ImageFilter.GaussianBlur with a configurable radius. The output has the same size as the input. Images with transparency are blurred with premultiplied alpha, so the color of fully transparent pixels does not bleed into visible edges.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | Literal['JPEG', 'PNG', 'WEBP'] | None | Output image format. Must be one of ‘JPEG’, ‘PNG’, or ‘WEBP’. If None, keeps original format (if supported). Defaults to None. |
radius | float | The Gaussian blur radius in pixels. Must be finite and greater than 0. Defaults to 2.0. |
Examples:
ImageColorSaturationConverter¶
Bases: BaseImageToImageConverter
Adjusts the color saturation level of an image.
This converter uses PIL’s ImageEnhance.Color to adjust an image’s color saturation. A level of 0.0 produces a grayscale (black-and-white) image, 1.0 preserves the original colors, and values greater than 1.0 oversaturate the colors.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | Literal['JPEG', 'PNG', 'WEBP'] | None | Output image format. Must be one of ‘JPEG’, ‘PNG’, or ‘WEBP’. If None, keeps original format (if supported). Defaults to None. |
level | float | The color saturation level. 0.0 produces a grayscale image (black and white). 1.0 preserves the original colors. Values greater than 1.0 oversaturate the colors. Must be finite. Defaults to 0.0 (grayscale image). |
Examples:
ImageCompressionConverter¶
Bases: Converter
Compresses images to reduce file size while preserving visual quality.
This converter supports multiple compression strategies across JPEG, PNG, and WEBP formats, each with format-specific optimization settings. It can maintain the original image format or convert between formats as needed.
When converting images with transparency (alpha channel) to JPEG format, the converter automatically composites the transparent areas onto a solid background color. CMYK images converted to PNG use RGB pixels without the incompatible source ICC profile. Integer-mode images saved as PNG are clipped to the format’s 16-bit range.
Supported input types:
File paths to any image that PIL can open (or URLs pointing to such images):
https://
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | str | Output image format. Must be one of ‘JPEG’, ‘PNG’, or ‘WEBP’. If None, keeps original format (if supported). Defaults to None. |
quality | int | General quality setting for JPEG and WEBP formats (0-100). For JPEG format, it represents the image quality, on a scale from 0 (worst) to 95 (best). For WEBP format, the value ranges from 0 to 100; for lossy compression: 0-smallest file size and 100-largest; for lossless: 0-fastest/less efficient, and 100 gives the best compression. Defaults to None. |
optimize | bool | Whether to optimize the image during compression. For JPEG: makes the encoder perform an extra pass over the image to select optimal settings. For PNG: instructs the PNG writer to make the output file as small as possible. Defaults to None. |
progressive | bool | Whether to save JPEG images as progressive. Defaults to None. |
compress_level | int | ZLIB compression level (0-9): 1=fastest, 9=best, 0=none. Ignored if optimize is True (then it is forced to 9). Defaults to None. |
lossless | bool | Whether to use lossless compression for WEBP format. Defaults to None. |
method | int | Quality/speed trade-off for WEBP format (0=fast, 6=slower-better). Defaults to None. |
background_color | tuple[int, int, int] | RGB color tuple for background when converting transparent images to JPEG. Defaults to black. |
min_compression_threshold | int | Minimum file size threshold for compression. Defaults to 1024 bytes. |
fallback_to_original | bool | Fallback to original if compression increases file size. Defaults to True. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'image_path') → ConverterResultConvert the given prompt (image) by compressing it.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The image file path or URL pointing to the image to be compressed. |
input_type | PromptDataType | The type of input data. Defaults to 'image_path'. |
Returns:
ConverterResult— The result containing path to the compressed image.
Raises:
ValueError— If the input type is not supported.
ImageNoiseConverter¶
Bases: BaseImageToImageConverter
Adds random Gaussian pixel noise to an image.
Zero-mean Gaussian noise with the configured standard deviation (on the 0-255 scale) is added to every color channel, and the result is clipped to the valid range. An alpha channel, if present, is left unchanged, and the output has the same size as the input.
The noise is drawn from a generator seeded through PyRIT’s seeded randomness, so a configured seed gives the same noise for the same input.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | Literal['JPEG', 'PNG', 'WEBP'] | None | Output image format. Must be one of ‘JPEG’, ‘PNG’, or ‘WEBP’. If None, keeps original format (if supported). Defaults to None. |
standard_deviation | float | Standard deviation of the Gaussian noise on the 0-255 scale. Must be finite and greater than 0. Defaults to 25.0. |
Examples:
ImageOverlayConverter¶
Bases: Converter
Composites a prompt image (overlay) onto a base image at a specified position.
The base image is configured via the constructor, while the overlay image is provided as the prompt input. This is useful for creating many variations of a scenario by layering different images on top of a base image (e.g., placing a CAPTCHA image over an open locket in a photo of hands).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
base_image | Path | str | Local file path or Azure Blob URL of the base image. |
position | tuple[int, int] | (x, y) pixel coordinates on the base image where the top-left corner of the overlay will be placed. Defaults to (0, 0). |
overlay_size | tuple[int, int] | None | Optional (width, height) to resize the overlay image before compositing. Defaults to None (use original size). |
opacity | float | Opacity of the overlay from 0.0 (fully transparent) to 1.0 (fully opaque). Defaults to 1.0. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'image_path') → ConverterResultOverlay the prompt image onto the configured base image.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The file path of the overlay image to place on the base. |
input_type | PromptDataType | The type of input data. Must be “image_path”. Defaults to 'image_path'. |
Returns:
ConverterResult— The result containing the path to the composited image.
Raises:
ValueError— If the input type is not supported.
ImagePromptStyleConverter¶
Bases: LLMGenericTextConverter
LLM-based converter that expands a short objective into a detailed image generation prompt using a photographic style filter and scene variation.
The converter loads a filter YAML file containing style_instructions and a list of variations, then uses an LLM to expand the user’s objective into a fully styled image generation prompt.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The LLM endpoint that generates the expanded prompt. Must satisfy CHAT_TARGET_REQUIREMENTS (inherited from LLMGenericTextConverter). Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
filter_name | str | None | Name of a built-in filter YAML file (without extension) in the image_prompt_style directory. Mutually exclusive with filter_path. Defaults to None. |
filter_path | Path | None | Path to a custom filter YAML file. Mutually exclusive with filter_name. Defaults to None. |
variation | str | None | Name of the variation to use (matched by key name in the YAML variations mapping, e.g. “wide_mirror_shot”). This is case-insensitive. If None, a random variation is selected on each call to convert_async. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert a short objective into a detailed, styled image generation prompt.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The user’s short objective |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— ConverterResult containing the expanded image generation prompt.
Raises:
ValueError— If the input type is not supported.
list_available_filters¶
list_available_filters() → list[str]List all available image filter names.
Returns:
list[str]— List of filter names (YAML filenames without extension), excluding the system prompt.
list_available_variations¶
list_available_variations(filter_name: str) → list[str]List all available variation names for a given filter.
| Parameter | Type | Description |
|---|---|---|
filter_name | str | Name of a built-in filter YAML file (without extension). |
Returns:
list[str]— Sorted list of variation key names defined in the filter.
Raises:
ValueError— If filter_name isn’t a built-in filter, or if the filter file is malformed.
ImageResizingConverter¶
Bases: BaseImageToImageConverter
Resizes an image by a given scale factor.
This converter uses PIL’s Image.resize to scale an image by a specified factor. A scale_factor of 1.0 preserves the original size, values less than 1.0 shrink the image, and values greater than 1.0 enlarge it.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | Literal['JPEG', 'PNG', 'WEBP'] | None | Output image format. Must be one of ‘JPEG’, ‘PNG’, or ‘WEBP’. If None, keeps original format (if supported). Defaults to None. |
scale_factor | float | The factor by which to scale the image dimensions. 1.0 preserves the original size. Values less than 1.0 shrink the image. Values greater than 1.0 enlarge the image. Defaults to 0.5 (halve the image dimensions). |
Examples:
ImageRotationConverter¶
Bases: BaseImageToImageConverter
Rotates an image by a given angle in degrees.
This converter uses PIL’s Image.rotate to rotate an image by a specified angle. Positive values rotate counter-clockwise. The image is expanded to fit the entire rotated content, and exposed background areas are filled with a configurable fill color (white by default).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
output_format | Literal['JPEG', 'PNG', 'WEBP'] | None | Output image format. Must be one of ‘JPEG’, ‘PNG’, or ‘WEBP’. If None, keeps original format (if supported). Defaults to None. |
angle | float | The rotation angle in degrees (counter-clockwise). Must be finite. Defaults to 90.0. |
fill_color | tuple[int, int, int] | The RGB color to fill exposed background areas after rotation. Defaults to (255, 255, 255) (white). |
Examples:
IndexSelectionStrategy¶
Bases: TextSelectionStrategy
Selects text based on absolute character indices.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
start | int | The starting character index (inclusive). Defaults to 0. |
end | int | None | The ending character index (exclusive). If None, selects to end of text. Defaults to None. |
Examples:
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the start index and the end index when one was provided.
Returns:
dict[str, Any]— dict[str, Any]: Start index, and end index when set.
select_range¶
select_range(text: str) → tuple[int, int]Select a range based on absolute character indices.
| Parameter | Type | Description |
|---|---|---|
text | str | The input text to select from. |
Returns:
tuple[int, int]— tuple[int, int]: A tuple of (start_index, end_index).
InsertPunctuationConverter¶
Bases: Converter
Inserts punctuation into a prompt to test robustness.
Punctuation insertion: inserting single punctuations in string.punctuation.
Words in a prompt: a word does not contain any punctuation and space.
“a1b2c3” is a word; “a1 2” are 2 words; “a1,b,3” are 3 words.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
word_swap_ratio | float | Percentage of words to perturb. Defaults to 0.2. |
between_words | bool | If True, insert punctuation only between words. If False, insert punctuation within words. Defaults to True. |
seed | int | None | Optional seed for reproducible output. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text', punctuation_list: list[str] | None = None) → ConverterResultConvert the given prompt by inserting punctuation.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The text to convert. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
punctuation_list | list[str] | None | List of punctuations to use for insertion. Defaults to None. |
Returns:
ConverterResult— The result containing an iteration of modified prompts.
Raises:
ValueError— If the input type is not supported, or ifpunctuation_listis empty or contains anything other than single characters fromstring.punctuation.
JsonStringConverter¶
Bases: Converter
Converts a string to a JSON-safe format using json.dumps().
This converter is useful when a string needs to be embedded within a JSON payload, such as when sending prompts to HTTP targets that expect JSON-formatted requests. The converter properly escapes special characters like quotes, newlines, backslashes, and unicode characters.
The output is the escaped string content without the surrounding quotes that json.dumps() adds, making it ready to be inserted into a JSON string field.
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt to a JSON-safe string.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the JSON-escaped string.
Raises:
ValueError— If the input type is not supported.
KeywordSelectionStrategy¶
Bases: TextSelectionStrategy
Selects text around a keyword with optional context.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
keyword | str | The keyword to search for. |
context_before | int | Number of characters to include before the keyword. Defaults to 0. |
context_after | int | Number of characters to include after the keyword. Defaults to 0. |
case_sensitive | bool | Whether the keyword search is case-sensitive. Defaults to True. |
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the keyword, the context sizes and the case-sensitivity flag.
Returns:
dict[str, Any]— dict[str, Any]: Keyword, context sizes and case-sensitivity flag.
select_range¶
select_range(text: str) → tuple[int, int]Select the range around the first occurrence of the keyword.
| Parameter | Type | Description |
|---|---|---|
text | str | The input text to select from. |
Returns:
tuple[int, int]— tuple[int, int]: A tuple of (start_index, end_index) including context, or (0, 0) if keyword not found.
LLMGenericTextConverter¶
Bases: Converter
Represents a generic LLM-backed converter for text-in/text-out transformations.
Subclasses may override _process_response to parse, extract, or otherwise post-process
the raw LLM response (e.g., JSON parsing). Subclasses opt into retry behavior by setting
RETRY_EXCEPTIONS to the tuple of exception types that should trigger a retry; by default
the attempt count is read from the RETRY_MAX_NUM_ATTEMPTS environment variable and no
wait is applied between attempts (matching pyrit_json_retry). Subclasses needing a
fixed attempt count or exponential backoff can pass max_retry_attempts and/or
retry_wait_max_seconds to __init__.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The endpoint that converts the prompt. Must satisfy CHAT_TARGET_REQUIREMENTS (multi-turn + editable history capabilities, possibly via normalization-pipeline adaptation). Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
system_prompt_template | SeedPrompt | None | The prompt template to set as the system prompt. The input prompt is available as objective when rendering. Defaults to None. |
user_prompt_template_with_objective | SeedPrompt | None | The prompt template to wrap the user input with. Must include an objective parameter; the raw user prompt is rendered as objective. Additional **kwargs are also forwarded to the renderer, so subclasses can pass static template parameters (e.g., language). Defaults to None. |
retry_exceptions | tuple[type[BaseException], ...] | None | Exception types that should trigger a retry. Overrides the class-level RETRY_EXCEPTIONS for this instance only. If None, RETRY_EXCEPTIONS is used. Defaults to None. |
max_retry_attempts | int | None | Maximum number of retry attempts. If None, the value is read at retry time from the RETRY_MAX_NUM_ATTEMPTS environment variable. Defaults to None. |
retry_wait_max_seconds | int | None | Upper bound (in seconds) for exponential backoff between retry attempts. If None, no wait is applied between attempts (matches pyrit_json_retry). Defaults to None. |
kwargs | Any | Additional parameters forwarded to both the system prompt and user prompt templates during rendering. Their constructor-time state contributes to the identifier, including container iteration order, path flavor and object fields. Parameters should remain static after construction. Sets and frozensets are rejected, including inside other parameters, because their iteration order can change between processes. Pass an ordered list instead, such as sorted(values). The incoming prompt supplies objective at render time. Defaults to {}. |
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt using an LLM via the specified converter target.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted output and its type.
Raises:
ValueError— If the input type is not supported.
LSBImageStegoConverter¶
Bases: Converter
Encode a text prompt into the Least Significant Bits (LSB) of a lossless PNG image.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
carrier_image_path | str | Path | None | Optional path to a cover image. When None, a lossless solid carrier image is generated and sized to fit the payload. Defaults to None. |
channels | Literal['RGB', 'RGBA'] | Pixel channel mode used for LSB embedding. Defaults to “RGBA”. |
delimiter | str | End-of-payload sentinel appended after the UTF-8 payload. Defaults to “====EOF====”. |
min_dimensions | tuple[int, int] | Minimum (width, height) for synthetic carriers. Defaults to (64, 64). |
background_color | tuple[int, int, int] | tuple[int, int, int, int] | Base RGB/RGBA color for synthetic carrier images. Defaults to (240, 244, 248, 255). |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given text prompt into a lossless PNG image with an LSB-encoded payload.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The text prompt to encode inside the PNG image. |
input_type | PromptDataType | The input data type. Defaults to “text”. |
Returns:
ConverterResult— Result containing the saved PNG file path with output_type=“image_path”.
Raises:
ValueError— If the input type is unsupported, the prompt is empty, or the carrier cannot hold the payload.
decode_image¶
decode_image(image_path: str | Path | BytesIO, channels: StegoChannelMode = 'RGBA', delimiter: str = _DEFAULT_DELIMITER) → strDecode and return the UTF-8 string hidden inside the LSBs of a PNG image.
| Parameter | Type | Description |
|---|---|---|
image_path | str | Path | BytesIO | Path or byte stream of the stego PNG image. |
channels | Literal['RGB', 'RGBA'] | Pixel channel mode used during encoding. Defaults to “RGBA”. |
delimiter | str | End-of-payload sentinel string. Defaults to “====EOF====”. |
Returns:
str— The decoded UTF-8 text payload.
Raises:
ValueError— If parameters are invalid, the delimiter is missing, or the payload is not valid UTF-8.
LSBImageStegoDecodeConverter¶
Bases: Converter
Decode a UTF-8 text payload from an LSB stego PNG image (image_path -> text).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
channels | Literal['RGB', 'RGBA'] | Pixel channel mode used during encoding. Defaults to “RGBA”. |
delimiter | str | End-of-payload sentinel string. Defaults to “====EOF====”. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'image_path') → ConverterResultDecode the hidden UTF-8 text payload from a stego PNG image path.
| Parameter | Type | Description |
|---|---|---|
prompt | str | Path to the stego PNG image. |
input_type | PromptDataType | The input data type. Defaults to “image_path”. |
Returns:
ConverterResult— Result containing the decoded UTF-8 string with output_type=“text”.
Raises:
ValueError— If the input type is unsupported, the path is empty, or decoding fails.
LeetspeakConverter¶
Bases: _CharacterSubstitutionConverter
Converts a string to a leetspeak version.
Leetspeak is the look-alike member of the character-substitution family
(see _CharacterSubstitutionConverter): by default it uses the standard leet table, and a
custom_substitutions map can override it.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
deterministic | bool | If True, use the first substitution for each character. If False, randomly choose a substitution for each character. Defaults to True. |
custom_substitutions | dict | None | A dictionary of custom substitutions to override the defaults. Each key is a single character, matched case-insensitively, and maps to a non-empty list of replacement strings. Defaults to None. |
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, all words will be converted. Defaults to None. |
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into leetspeak.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
LetterBijectionConverter¶
Bases: BijectionConverter
Bijection converter that maps letters to other letters.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
fixed_size | int | Number of leading letters to keep unchanged (identity mapping), from 0 to 26. Defaults to 0. |
mapping | (dict[str, str], Optional) | Explicit mapping dict. If provided, used directly. Defaults to None. |
seed | (int, Optional) | Random seed for reproducibility. Defaults to None. |
Examples:
LogicJailbreakConverter¶
Bases: LLMGenericTextConverter
Converts a natural language request into a formal logical expression using an LLM.
Implements the Logic Jailbreak (LogiBreak) attack, which rewrites a request as a structured first-order logical expression (predicates, quantifiers, and logical connectives) so that safety alignment keyed on natural-language surface form is less likely to recognize the intent. The converted prompt wraps the logical expression in a “formal semantics” framing that asks the target for a concrete, step-by-step implementation of the expression.
An existing PromptTarget performs the natural-language-to-logic conversion.
The formalization and delivery prompts are ported from the authors’ reference
implementation (https://
Reference: Peng et al., “Logic Jailbreak: Efficiently Unlocking LLM Safety Restrictions
Through Formal Logical Expression”, Findings of ACL 2026 (arXiv:2505.13527).
https://
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The endpoint that formalizes the prompt. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
prompt_template | SeedPrompt | The seed prompt template to use for the conversion. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt into a formal logical expression and wrap it for delivery.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the framed logical expression.
MaliciousQuestionGeneratorConverter¶
Bases: LLMGenericTextConverter
Generates malicious questions using an LLM.
An existing PromptTarget is used to perform the conversion (like Azure OpenAI).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The endpoint that converts the prompt. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
prompt_template | SeedPrompt | The seed prompt template to use. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the input prompt into malicious questions.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input prompt to convert. |
input_type | PromptDataType | The type of the input prompt. Must be “text”. Defaults to 'text'. |
Returns:
ConverterResult— The result of the conversion.
input_supported¶
input_supported(input_type: PromptDataType) → boolCheck if the input type is supported.
| Parameter | Type | Description |
|---|---|---|
input_type | PromptDataType | The type of the input prompt. |
Returns:
bool— True if the input type is “text”, False otherwise.
output_supported¶
output_supported(output_type: PromptDataType) → boolCheck if the output type is supported.
| Parameter | Type | Description |
|---|---|---|
output_type | PromptDataType | The desired type of the output prompt. |
Returns:
bool— True if the output type is “text”, False otherwise.
MathObfuscationConverter¶
Bases: Converter
Convert text into character-level algebraic identities.
This converter encodes each character of the input text into an equation of
the form X = nX - (n - 1)X, where n is a randomly chosen integer greater
than or equal to 2. This creates a deterministic, reversible obfuscation of
the original input.
The transformation follows these rules:
Each non-space character becomes one algebraic line.
Numeric characters, such as digits, superscripts and fractions, write the multiplication explicitly, as in
5 = 8*5 - 7*5, because85 - 75would read as two-digit numbers.Space characters are represented as blank output lines.
Newline characters are preserved as blank output lines.
An inline hint is added after the first equation, and a suffix instruction is appended to prompt the model to decode the content.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
min_n | int | Minimum integer value used for n in X = nX - (n - 1)X. Must be greater than or equal to 2. Defaults to 2. |
max_n | int | Maximum integer value used for n. Must be greater than or equal to min_n. Defaults to 9. |
hint | str | None | Inline hint appended to the first equation line. If None, uses the default hint explaining the variable encoding. Set to empty string “” to disable hint entirely. Defaults to None. |
suffix | str | None | Custom suffix to append after the obfuscated text. If None, uses the default suffix prompting the model to decode. Set to empty string “” to disable suffix entirely. Defaults to None. |
rng | random.Random | None | Optional random number generator instance used to produce reproducible obfuscation results. If omitted, the converter uses its operation-local hierarchical stream. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert text into algebraic obfuscated form.
Each non-space character in the input string is transformed into a corresponding algebraic identity. Space characters are represented as blank output lines, preserving word boundaries. Newline characters are preserved as block breaks in the output.
| Parameter | Type | Description |
|---|---|---|
prompt | str | Input text to be transformed. |
input_type | PromptDataType | Expected to be "text". Other types are not supported. Defaults to 'text'. |
Returns:
ConverterResult— An instance containing the obfuscated text and output format.
Raises:
ValueError— Ifinput_typeis not"text".
MathPromptConverter¶
Bases: LLMGenericTextConverter
Converts natural language instructions into symbolic mathematics problems using an LLM.
An existing PromptTarget is used to perform the conversion (like Azure OpenAI).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The endpoint that converts the prompt. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
prompt_template | SeedPrompt | The seed prompt template to use. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt into a mathematical problem format.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the mathematical representation and real-world example.
MorseConverter¶
Bases: Converter
Encodes prompts using morse code.
Uses ‘-’ and ‘.’ characters, with ’ ’ to separate characters and ‘/’ to separate words. Invalid or unsupported characters are replaced with an error sequence ‘........’.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
append_description | bool | Append plaintext “expert” text to the prompt. Includes instructions to only communicate using the cipher, a description of the cipher, and an example encoded using cipher. Defaults to False. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt to morse code.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | Type of input data. Defaults to “text”. |
Returns:
ConverterResult— The result containing the morse code representation of the prompt.
Raises:
ValueError— If the input type is not supported.
NatoConverter¶
Bases: WordLevelConverter
Converts text into NATO phonetic alphabet representation.
This converter transforms standard text into NATO phonetic alphabet format,
where each ASCII letter is replaced with its corresponding NATO phonetic code
word (e.g., “A” becomes “Alfa”, “B” becomes “Bravo”). Characters outside the
ASCII alphabet are preserved with their original casing. Spaces are represented
by <space> so word boundaries remain distinct from code-word separators.
The NATO phonetic alphabet is the most widely used spelling alphabet, designed to improve clarity of voice communication. This converter can be used to test how AI systems handle phonetically encoded text, which can be used to obfuscate potentially harmful content.
Reference: NATO phonetic alphabet
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert one word into NATO phonetic alphabet representation.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to convert. |
Returns:
str— The converted word, with code words separated by spaces.
join_words¶
join_words(words: list[str]) → strJoin converted words while preserving every source-space boundary.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The converted words. |
Returns:
str— The converted words separated by explicit space tokens.
NegationTrapConverter¶
Bases: Converter
Converts a prompt into a negation-based logical trap. This technique exploits LLM reasoning patterns by asking the model to confirm or deny a wrong answer, potentially causing it to reveal the correct one.
This technique was discovered during CTF red teaming exercises where targets would leak information when asked to evaluate incorrect statements.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
wrong_value | str | A deliberately wrong value to use in the trap. The target may reveal the correct value when correcting this. Defaults to “incorrect_guess”. |
trap_template | str | A custom template string. Must include {prompt} and {wrong_value} placeholders. If None, uses the default denial template. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the prompt into a negation trap.
This technique works by presenting an obviously wrong answer and asking the target to correct it, which may cause it to reveal protected information.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of the input prompt. Defaults to 'text'. |
Returns:
ConverterResult— The prompt converted to a negation trap.
Raises:
ValueError— If the input type is not supported.
input_supported¶
input_supported(input_type: PromptDataType) → boolCheck if the input type is supported.
| Parameter | Type | Description |
|---|---|---|
input_type | PromptDataType | The type of the input prompt. |
Returns:
bool— True if the input type is supported, False otherwise.
output_supported¶
output_supported(output_type: PromptDataType) → boolCheck if the output type is supported.
| Parameter | Type | Description |
|---|---|---|
output_type | PromptDataType | The desired type of the output prompt. |
Returns:
bool— True if the output type is supported, False otherwise.
NoiseConverter¶
Bases: LLMGenericTextConverter
Injects noise errors into a conversation using an LLM.
An existing PromptTarget is used to perform the conversion (like Azure OpenAI).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The endpoint that converts the prompt. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
noise | str | The noise to inject. Grammar error, delete random letter, insert random space, etc. Defaults to None. |
number_errors | int | The number of errors to inject. Defaults to 5. |
prompt_template | (SeedPrompt, Optional) | The prompt template for the conversion. Defaults to None. |
Examples:
PDFConverter¶
Bases: Converter
Converts a text prompt into a PDF file.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
prompt_template | SeedPrompt | None | A SeedPrompt object representing a template. Defaults to None. |
font_type | str | Font type for the PDF. Defaults to “Helvetica”. |
font_path | Path | None | Local TrueType font to embed, overriding font_type for generated text and injection items without an explicit font. Choose a font covering the text’s characters. Defaults to None. |
font_size | int | Font size for the PDF. Defaults to 12. |
font_color | tuple[int, int, int] | None | Text color in RGB format (0-255). Generated PDFs use it, or black when it isn’t set. Injection items without their own font_color use it, or white when it isn’t set, so injected text stays hidden by default. Defaults to None. |
page_width | int | Width of the PDF page in mm. Defaults to 210 (A4 width). |
page_height | int | Height of the PDF page in mm. Defaults to 297 (A4 height). |
column_width | int | Width of each column in the PDF. Defaults to 0 (full page width). |
row_height | int | Height of each row in the PDF. Defaults to 10. |
existing_pdf | Path | None | Path to an existing PDF file. Defaults to None. |
injection_items | list[dict[str, Any]] | None | Injection items for modifying an existing PDF. Identifier values must be JSON-serializable or UTF-8 bytes, which are identified as their decoded text. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt into a PDF.
If a template is provided, it injects the prompt into the template, otherwise, it generates a simple PDF with the prompt as the content. Further it can modify existing PDFs.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be embedded in the PDF. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the full file path to the generated PDF.
Raises:
ValueError— If the input type is not supported.
PersuasionConverter¶
Bases: LLMGenericTextConverter
Rephrases prompts using a variety of persuasion techniques.
Based on Zeng et al., 2024.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The chat target used to perform rewriting on user prompts. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
persuasion_technique | str | Persuasion technique to be used by the converter, determines the system prompt to be used to generate new prompts. Must be one of “authority_endorsement”, “evidence_based”, “expert_endorsement”, “logical_appeal”, “misrepresentation”. |
Examples:
PigpenConverter¶
Bases: _CharacterSubstitutionConverter
Encodes text with the Pigpen (Freemason’s / Masonic) cipher.
Pigpen is a geometric monoalphabetic substitution: each letter becomes the fragment of the grid
that surrounds its cell. This is the geometric member of the character-substitution family
(see _CharacterSubstitutionConverter); like Leetspeak it is case-folding and not reversible
(Hello and hello encode identically).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, all words are converted. Defaults to None. |
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into Pigpen glyphs.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
PinyinConverter¶
Bases: Converter
Replaces Chinese (Hanzi) characters with their Pinyin romanization.
Pinyin mixing is a Chinese-specific adversarial text transformation: Hanzi characters or spans are rewritten as full or abbreviated Pinyin while the text stays understandable to a Chinese-reading model. This can bypass keyword- and token-level safety filters that match on Hanzi rather than on romanized readings. The pattern is described in recent work on Chinese LLM safety such as CSSBench.
The converter uses no LLM call. It resolves readings using phrase context before replacing individual characters:
full: each selected Hanzi becomes its full Pinyin reading without tone marks (e.g.中->zhong).initial: each selected Hanzi becomes the first letter of its reading (e.g.中->z).mixed: each selected Hanzi is independently rendered as either its full reading or its initial.
proportion controls how many of the Hanzi are converted; a value below 1.0 leaves
the rest as Hanzi, producing mixed Hanzi/Pinyin text. Characters that are not Hanzi are
always left unchanged, as are Hanzi without a dictionary reading. Pass seed for
reproducible selection.
Pinyin dictionaries are loaded lazily, and phrase lookup runs in a worker thread.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
mode | PinyinMode | How a converted Hanzi is rendered. "full" uses the full toneless reading, "initial" uses only the first letter, and "mixed" chooses one of the two independently per character. Defaults to "full". |
proportion | float | Fraction in [0.0, 1.0] of the Hanzi characters to convert. The selected count is round(proportion * number_of_hanzi) and the positions are chosen at random (seedable). 1.0 converts every Hanzi. Defaults to 1.0. |
separator | str | String inserted after each converted syllable, except at the end of the prompt. Original characters, including trailing whitespace, are preserved. Full Pinyin spans run together by default (中心 -> zhongxin); pass separator=" " to keep syllable boundaries readable (zhong xin). Defaults to "". |
seed | int | None | Optional seed for reproducible selection and, in "mixed" mode, reproducible per-character rendering. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert Hanzi characters in the prompt to Pinyin.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The text prompt to convert. |
input_type | PromptDataType | The input data type. Only text is supported. Defaults to 'text'. |
Returns:
ConverterResult— The converted prompt.
Raises:
ValueError— If the input type is not supported.
PolicyPuppetryConverter¶
Bases: Converter
Wraps a prompt in a Policy Puppetry prompt-injection template.
Policy Puppetry is a post-instruction-hierarchy, universal, and transferable prompt-injection technique that frames a request as policy/configuration the model should follow, bypassing instruction hierarchy and safety guardrails.
The templates live in pyrit/datasets/converters/policy_puppetry_converter.yaml
and are referenced via PolicyPuppetryTemplate.
Reference: HiddenLayer, 2025
(https://
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
prompt_template | SeedPrompt | None | The template the prompt is wrapped in. The template must expose a single {{ prompt }} parameter. If not provided, a random template from PolicyPuppetryTemplate is used. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultWrap the prompt in the configured Policy Puppetry template.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to wrap. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the templated prompt.
Raises:
ValueError— If the input type is not supported.
PolicyPuppetryTemplate¶
Bases: enum.Enum
Selectable Policy Puppetry templates.
Each member maps to a named template in policy_puppetry_converter.yaml.
Callers can reference a member and resolve it to its SeedPrompt via
to_seed_prompt.
Examples:
Methods:
random¶
random() → PolicyPuppetryTemplateReturn a randomly selected template member.
Returns:
PolicyPuppetryTemplate— A random member of the enum.
to_seed_prompt¶
to_seed_prompt() → SeedPromptLoad the SeedPrompt template backing this enum member.
Returns:
SeedPrompt— The template prompt for this member.
PositionSelectionStrategy¶
Bases: TextSelectionStrategy
Selects text based on proportional start and end positions.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
start_proportion | float | The starting position as a proportion (0.0 to 1.0). |
end_proportion | float | The ending position as a proportion (0.0 to 1.0). |
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the start and end proportions.
Returns:
dict[str, Any]— dict[str, Any]: Start and end proportions.
select_range¶
select_range(text: str) → tuple[int, int]Select a range based on the relative position in the text.
| Parameter | Type | Description |
|---|---|---|
text | str | The input text to select from. |
Returns:
tuple[int, int]— tuple[int, int]: A tuple of (start_index, end_index).
PromptTemplateConverter¶
Bases: Converter
Inserts the input prompt into a template at a {{ prompt }} placeholder.
Any template containing a {{ prompt }} placeholder is accepted; every
occurrence of the placeholder is replaced with the input. This covers task
framing (e.g. TASK is '{{ prompt }}') as well as wrapping the prompt in
surrounding content, such as hiding it in an HTML comment for indirect prompt
injection (e.g. <p>Visible text</p><!-- {{ prompt }} -->).
The converter identifier stores a fixed-size hash of the configured template,
rather than the template text. The deprecated TaskFramingConverter retains
its legacy identifier.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
template | str | A template containing a {{ prompt }} placeholder marking where the input is inserted. |
strip_characters | str | Characters removed from the input before it is inserted into the template. Defaults to no stripping. Useful when the template delimits the input (e.g. with quotes) and matching characters in the input would otherwise collide with those delimiters. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by inserting it into the template.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to insert. |
input_type | PromptDataType | Type of input data. Defaults to “text”. |
Returns:
ConverterResult— The template with the prompt inserted at the placeholder.
Raises:
ValueError— If the input type is not supported.
ProportionSelectionStrategy¶
Bases: TextSelectionStrategy
Selects a proportion of text anchored to a specific position (start, end, middle, or random).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
proportion | float | The proportion of text to select (0.0 to 1.0). |
anchor | str | Where to anchor the selection. Valid values: - ‘start’: Select from the beginning - ‘end’: Select from the end - ‘middle’: Select from the middle - ‘random’: Select from a random position Defaults to 'start'. |
seed | int | None | Random seed for reproducible random selections. Defaults to None. Scoped to this strategy: it makes this strategy reproducible without affecting the randomness of any other component. |
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the proportion, the anchor and the optional seed.
Returns:
dict[str, Any]— dict[str, Any]: Proportion, anchor, and seed when one was provided.
select_range¶
select_range(text: str) → tuple[int, int]Select a proportion of text based on the anchor position.
| Parameter | Type | Description |
|---|---|---|
text | str | The input text to select from. |
Returns:
tuple[int, int]— tuple[int, int]: A tuple of (start_index, end_index).
PuzzleType¶
Bases: str, Enum
The three puzzle encodings described in the PUZZLED paper.
PuzzledConverter¶
Bases: Converter
Hides the sensitive words of a prompt inside a word puzzle the target must solve.
Implements the PUZZLED jailbreak of Ahn & Lee, “PUZZLED: Jailbreaking LLMs through Word-Based
Puzzles” (arXiv:2508.01306). The most sensitive words in the prompt are masked with indexed
[WORD1] placeholders and re-encoded as one of three word puzzles. The converted prompt asks
the model to solve the puzzle, restore the masked words, and then carry out the reconstructed
instruction, so the harmful request is never stated in plain text.
Each puzzle uses the same letter units as its clues: canonically equivalent spellings are normalized, and combining marks stay attached to their letters during encoding. Alphanumeric tokens, underscores, and words containing joiners are not partially masked.
Keyword selection uses spaCy’s en_core_web_sm model when it is installed and degrades to a
length-based heuristic when it is not, so the converter has no hard dependency on spaCy. Run
python -m spacy download en_core_web_sm to enable the paper’s part-of-speech-aware
selection; without it, keywords are chosen by length alone and short harmful words may be
left unmasked.
PUZZLED Ahn & Lee, 2025.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
puzzle_type | PuzzleType | str | Which encoding to build. One of “word_search”, “anagram” or “crossword”. Defaults to PuzzleType.WORD_SEARCH. |
num_to_mask | int | None | How many words to mask. Defaults to a length-based rule from the paper (more words for longer prompts). |
essential_words | list[str] | None | Sensitive words to prefer when selecting what to mask. When omitted, words are chosen automatically. Defaults to None. |
seed | int | None | Seed for the puzzle randomness (word-search placement and anagram shuffling). Pass an int for reproducible output; leave as None to inherit the root configured by initialize_pyrit_async(seed=...). Defaults to None. |
converter_target | PromptTarget | None | Optional chat model used to generate the paper’s “indirect semantic description” clue for each masked word. When omitted, each clue is the deterministic length-and-part-of-speech clue only. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultMask the prompt’s sensitive words and encode them as the configured puzzle.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input prompt to convert. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The puzzle-wrapped prompt.
Raises:
ValueError— If the input type is not supported, or the prompt has no maskable words.
QRCodeConverter¶
Bases: Converter
Converts a text string to a QR code image.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
scale | (int, Optional) | Scaling factor that determines the width/height in pixels of each black/white square (known as a “module”) in the QR code. Defaults to 3. |
border | (int, Optional) | Controls how many modules thick the border should be. Defaults to recommended value of 4. |
dark_color | (tuple, Optional) | Sets color of dark modules, using RGB values. Defaults to black: (0, 0, 0). |
light_color | (tuple, Optional) | Sets color of light modules, using RGB values. Defaults to white: (255, 255, 255). |
data_dark_color | (tuple, Optional) | Sets color of dark data modules (the modules that actually stores the data), using RGB values. Defaults to dark_color. |
data_light_color | (tuple, Optional) | Sets color of light data modules, using RGB values. Defaults to light_color. |
finder_dark_color | (tuple, Optional) | Sets dark module color of finder patterns (squares located in three corners), using RGB values. Defaults to dark_color. |
finder_light_color | (tuple, Optional) | Sets light module color of finder patterns, using RGB values. Defaults to light_color. |
border_color | (tuple, Optional) | Sets color of border, using RGB values. Defaults to light_color. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt to a QR code image.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing filename of the converted QR code image.
Raises:
ValueError— If the input type is not supported or if the prompt is empty.
ROT13Converter¶
Bases: WordLevelConverter
Encodes prompts using the ROT13 cipher.
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
RandomCapitalLettersConverter¶
Bases: Converter
Takes a prompt and randomly capitalizes it by a percentage of the total characters.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
percentage | float | The percentage of characters to capitalize in the prompt. Must be between 1 and 100. Defaults to 100.0. This includes decimal points in that range. |
seed | int | None | Optional seed for reproducible output. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by randomly capitalizing a percentage of its characters.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input text prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted text.
Raises:
ValueError— If the input type is not supported.
generate_random_positions¶
generate_random_positions(total_length: int, set_number: int) → list[int]Generate a list of unique random positions within the range of total_length.
| Parameter | Type | Description |
|---|---|---|
total_length | int | The total length of the string. |
set_number | int | The number of unique random positions to generate. |
Returns:
list[int]— A list of unique random positions.
Raises:
ValueError— Ifset_numberis greater thantotal_length.
is_percentage¶
is_percentage(input_string: float) → boolCheck if the input string is a valid percentage between 1 and 100.
| Parameter | Type | Description |
|---|---|---|
input_string | str | The input string to check. |
Returns:
bool— True if the input string is a valid percentage, False otherwise.
string_to_upper_case_by_percentage¶
string_to_upper_case_by_percentage(percentage: float, prompt: str) → strConvert a string by randomly capitalizing a percentage of its characters.
| Parameter | Type | Description |
|---|---|---|
percentage | float | The percentage of characters to capitalize. |
prompt | str | The input string to be converted. |
Returns:
str— The converted string with randomly capitalized characters.
Raises:
ValueError— If the percentage is not between 1 and 100.
RandomTranslationConverter¶
Bases: LLMGenericTextConverter, WordLevelConverter
Translates each individual word in a prompt to a random language using an LLM.
An existing PromptTarget is used to perform the translation (like Azure OpenAI).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The target for the prompt conversion. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
system_prompt_template | SeedPrompt | None | The system prompt template to use for the conversion. If not provided, a default template will be used. Defaults to None. |
languages | list[str] | None | The list of available languages to use for translation. Defaults to None. |
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, all words will be converted. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted output and its type.
Raises:
ValueError— If the input type is not supported.
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
RangeSelectionStrategy¶
Bases: TextSelectionStrategy
Selects text based on proportional start and end positions.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
start_proportion | float | The starting position as a proportion (0.0 to 1.0). Defaults to 0.0. |
end_proportion | float | The ending position as a proportion (0.0 to 1.0). Defaults to 1.0. |
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the start and end proportions.
Returns:
dict[str, Any]— dict[str, Any]: Start and end proportions.
select_range¶
select_range(text: str) → tuple[int, int]Select a range based on proportional positions.
| Parameter | Type | Description |
|---|---|---|
text | str | The input text to select from. |
Returns:
tuple[int, int]— tuple[int, int]: A tuple of (start_index, end_index).
RegexSelectionStrategy¶
Bases: TextSelectionStrategy
Selects text based on the first regex match.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
pattern | str | Pattern[str] | The regex pattern to match. |
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the regex pattern and flags.
Returns:
dict[str, Any]— dict[str, Any]: Pattern string and compiled flags.
select_range¶
select_range(text: str) → tuple[int, int]Select the range of the first regex match.
| Parameter | Type | Description |
|---|---|---|
text | str | The input text to select from. |
Returns:
tuple[int, int]— tuple[int, int]: A tuple of (start_index, end_index) of the first match, or (0, 0) if no match found.
RepeatTokenConverter¶
Bases: Converter
Repeats a specified token a specified number of times in addition to a given prompt.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
token_to_repeat | str | The string to be repeated. |
times_to_repeat | int | The number of times the string will be repeated. |
token_insert_mode | str | The mode of insertion for the repeated token. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by repeating the specified token a specified number of times.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of the input prompt. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the modified prompt with repeated tokens.
Raises:
ValueError— If the input type is not supported.
RolePlayToolCallConverter¶
Bases: LLMGenericTextConverter
Write one untrusted message so a desired tool action looks approved.
The defender already shows an authorized task. This converter writes the message beside that task. It does not call the defender’s tools.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The chat target that writes the message. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
valid_call | str | A normal allowed tool call. This is an example, not the goal. Example: refund {“order”: “order-1”, “amount”: 25}. |
action_desired | str | The executed action that should look approved. Example: refund {“order”: “order-1”, “amount”: 80}. |
message_format | str | The format of the generated message. Defaults to “random”, which selects XML, YAML, JSON, Markdown, or plain text on each conversion. Supply a format or custom format instructions to use it on every conversion. |
system_prompt | SeedPrompt | The adversarial chat’s system prompt template. Defaults to the role-play YAML. Can use objective (the incoming prompt), valid_call, action_desired, and message_format as Jinja parameters. |
SATAMaskingConverter¶
Bases: Converter
Replaces selected content words with a mask token such as [MASK].
This is the word-selection step for Simple Assistive Task Linkage (SATA)
Dong et al., 2025. PyRIT already provides HarmBench seeds and
PromptTemplateConverter; this converter supplies deterministic masking so
the two can be composed into the SATA infill attack.
Selection is dependency-free (no POS tagger or NLTK download). Use
ContentWordSelectionStrategy by default, or pass any
WordSelectionStrategy.
This converter splits on any whitespace (\s+) and never yields empty
tokens. SelectiveTextConverter splits on a single space by default,
so WordIndexSelectionStrategy indices match only when the prompt is
already single-space-separated, with no leading, trailing, or repeated
spaces. Tabs, newlines, and doubled spaces produce a different index
space here because those separators are preserved rather than treated as
part of a token.
Whitespace (spaces, tabs, newlines) and punctuation attached to a selected word are preserved; only the word core is replaced. A punctuation-only token occupies an index and is replaced in full if selected.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
mask_token | str | Replacement token. Defaults to [MASK]. |
selection_strategy | WordSelectionStrategy | None | Custom word selector. When provided, do not also pass num_masks, skip_first, min_word_length, stopwords, or candidate_words; configure those on the strategy instead. Defaults to None. |
num_masks | int | None | Number of content words to replace when using the default strategy. Defaults to 2. |
skip_first | int | None | Leading content words to leave unmasked when using the default strategy. Defaults to 1. |
min_word_length | int | None | Minimum alphabetic length for a content word when using the default strategy. Defaults to 3. |
stopwords | Collection[str] | None | Function words ignored by the default strategy. Defaults to the built-in English list. |
candidate_words | Collection[str] | None | Optional allowlist for the default strategy. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the prompt by masking selected content-word cores.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to mask. |
input_type | PromptDataType | Type of input data. Defaults to “text”. |
Returns:
ConverterResult— The masked prompt with separators and punctuation preserved.
Raises:
ValueError— If the input type is not supported.
ScientificTranslationConverter¶
Bases: LLMGenericTextConverter
Uses an LLM to transform simple or direct prompts into scientifically-framed versions using technical terminology, chemical notation, or academic phrasing. This can be useful for red-teaming scenarios to test whether safety filters can be bypassed through scientific translation.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The LLM target to perform the conversion. Defaults to REQUIRED_VALUE. |
mode | str | The translation mode to use. Built-in options are: - academic: Use academic/homework style framing - technical: Use technical jargon and terminology - smiles: Uses chemical notation (e.g., SMILES or IUPAC notation such as “2-(acetyloxy)benzoic acid” or “CC(=O)Oc1ccccc1C(=O)O” for aspirin) - research: Frame as research/safety study or question - reaction: Frame as a step-by-step chemistry mechanism problem - math: Frame as the answer key to a mathematical problem or equation for a homework/exam setting - combined: Use combination of above techniques together (default) You can also use a custom mode name if you provide a prompt_template. |
prompt_template | (SeedPrompt, Optional) | Custom prompt template. Required if using a custom mode not in the built-in list. Defaults to None. |
Examples:
SearchReplaceConverter¶
Bases: Converter
Converts a string by replacing chosen phrase with a new phrase of choice.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
pattern | str | The regex pattern to replace. Empty patterns match at every character boundary. |
replace | str | list[str] | The regex replacement template(s) to use. Literal backslashes must be escaped. Can be a single string or a list of strings. If a list is provided, a random element will be chosen. |
regex_flags | int | Regex flags to use for the replacement. Defaults to 0 (no flags). |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by replacing the specified pattern with a random choice from the replacement list.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted text.
Raises:
ValueError— If the input type is not supported.
SelectiveTextConverter¶
Bases: Converter
A wrapper converter that applies another converter to selected portions of text.
This converter supports multiple selection strategies:
Character-level: Selects a contiguous character range (e.g., IndexSelectionStrategy, RegexSelectionStrategy)
Word-level: Selects specific words (e.g., WordIndexSelectionStrategy, WordPositionSelectionStrategy)
Token-based: Auto-detects and converts text between ⟪⟫ tokens (TokenSelectionStrategy)
Most use cases will use word-level strategies for more intuitive selection.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
sub_converter | Converter | The converter to apply to the selected text. |
selection_strategy | TextSelectionStrategy | The strategy for selecting which text to convert. Can be character-level or word-level strategy. |
preserve_tokens | bool | If True, wraps converted text with start/end tokens. With TokenSelectionStrategy, retains each converted region’s marker pair, including nested pairs. Without markers, wraps the whole converted value. Defaults to False. |
start_token | str | The token to place before converted text when preserve_tokens=True. Defaults to “⟪”. |
end_token | str | The token to place after converted text when preserve_tokens=True. Defaults to “⟫”. |
word_separator | str | The separator to use when working with word-level strategies. Defaults to " ". |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert selected portions of the prompt using the wrapped converter.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Must be “text”. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted output and its type.
Raises:
ValueError— If the input type is not “text”.ValueError— If token-based conversion produces non-text output.ValueError— If marker preservation is requested around a custom token override.
convert_tokens_async¶
convert_tokens_async(prompt: str, input_type: PromptDataType = 'text', start_token: str = '⟪', end_token: str = '⟫', keep_tokens: bool = False) → ConverterResultApply token selection once, including when called from a pipeline.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input text. |
input_type | PromptDataType | The input type. Must be text for token selection. Defaults to 'text'. |
start_token | str | Opening marker used by the pipeline. Defaults to '⟪'. |
end_token | str | Closing marker used by the pipeline. Defaults to '⟫'. |
keep_tokens | bool | Retain the call’s marker pair even if preserve_tokens is False. Defaults to False. |
Returns:
ConverterResult— Converted text with selected boundaries consumed or preserved.
Raises:
ValueError— If preserving markers around a custom token override is requested.
SneakyBitsSmugglerConverter¶
Bases: SmugglerConverter
Encodes and decodes text using a bit-level approach.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
action | Literal['encode', 'decode'] | The action to perform. Defaults to 'encode'. |
zero_char | str | None | Character to represent binary 0 in sneaky_bits mode (default: U+2062). Defaults to None. |
one_char | str | None | Character to represent binary 1 in sneaky_bits mode (default: U+2064). Defaults to None. |
Examples:
Methods:
decode_message¶
decode_message(message: str) → strDecode the message encoded using Sneaky Bits mode.
The method filters out only the valid invisible characters (self.zero_char and self.one_char),
groups them into 8-bit chunks, reconstructs each byte, and finally decodes the byte sequence using UTF-8.
| Parameter | Type | Description |
|---|---|---|
message | str | The message encoded with Sneaky Bits. |
Returns:
str— The decoded original message.
encode_message¶
encode_message(message: str) → tuple[str, str]Encode the message using Sneaky Bits mode.
The message is first converted to its UTF-8 byte sequence. Then each byte is represented as 8 bits,
with each bit replaced by an invisible character (self.zero_char for 0 and self.one_char for 1).
| Parameter | Type | Description |
|---|---|---|
message | str | The message to encode. |
Returns:
str— tuple[str, str]: A tuple where the first element is a bit summary (empty in this implementation)str— and the second element is the encoded message containing the invisible bits.
StringJoinConverter¶
Bases: WordLevelConverter
Converts text by joining its characters with the specified join value.
Characters are grapheme clusters, so combining marks, Indic vowel signs and emoji sequences stay whole.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
join_value | str | The string used to join characters of each word. Defaults to '-'. |
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, all words will be converted. Defaults to None. |
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
SuffixAppendConverter¶
Bases: Converter
Appends a specified suffix to the prompt.
E.g. with a suffix !!!, it converts a prompt of test to test !!!.
See https://
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
suffix | str | The suffix to append to the prompt. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by appending the specified suffix.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | Type of input data. Defaults to “text”. |
Returns:
ConverterResult— The prompt with the suffix appended.
Raises:
ValueError— If the input type is not supported.
SuperscriptConverter¶
Bases: WordLevelConverter
Converts text to superscript.
This converter leaves characters that do not have a superscript equivalent unchanged.
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
TaskFramingConverter¶
Bases: PromptTemplateConverter
Deprecated: use PromptTemplateConverter instead; will be removed in 1.4.0.
Use PromptTemplateConverter(template=...) instead. To keep the previous
default behavior, pass template="TASK is '{{ prompt }}'".
The docstring intentionally does not start with “Deprecated alias”: the registry
skips such classes, and existing callers must still be able to build this one by
name (e.g. ConverterRegistry.create_instance("TaskFramingConverter", ...))
until it is removed.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
task_template | str | A template containing a {{ prompt }} placeholder marking where the input is inserted. Defaults to TASK is '{{ prompt }}'. |
strip_characters | str | Characters removed from the input before it is inserted into the template. Defaults to no stripping. |
TatweelConverter¶
Bases: Converter
Inserts Arabic tatweel (kashida, U+0640) between adjacent Arabic letters that join.
The tatweel is a connector that visually elongates a word without changing its meaning. Inserting it between letters leaves the text legible to a human reader while changing the underlying code point and token sequence. The transformation is deterministic: no language model or randomness is involved.
A tatweel only lengthens an existing connection, so it is inserted only after a letter that joins the next letter (not after alef, dal, thal, reh, zain, waw, teh marbuta, hamza or their variants) and only before a letter that joins the previous one (not before hamza). Elsewhere it would show as a detached stroke inside the word. Characters outside the main Arabic block, and Arabic letters not directly followed by another Arabic letter, are left untouched.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
tatweel_count | int | Number of tatweel characters inserted between adjacent joining Arabic letters. Must be at least 1. Defaults to 1. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by inserting tatweel between adjacent Arabic letters that join.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the elongated text.
Raises:
ValueError— If the input type is not supported.
TemplateSegmentConverter¶
Bases: Converter
Uses a template to randomly split a prompt into segments defined by the template.
This converter is a generalized version of this:
https://
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
prompt_template | (SeedPrompt, Optional) | The prompt template for the conversion. Must have two or more parameters. If not provided, uses the default tom_and_jerry.yaml template. Defaults to None. |
seed | int | None | Optional seed for reproducible segment boundaries. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by splitting it into random segments and using them to fill the template parameters. The prompt is split into N segments (where N is the number of template parameters) at random word boundaries. Each segment is then used to fill the corresponding template parameter.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the template filled with prompt segments.
Raises:
ValueError— If the input type is not supported.
TenseConverter¶
Bases: LLMGenericTextConverter
Converts a conversation to a different tense using an LLM.
An existing PromptTarget is used to perform the conversion (like Azure OpenAI).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The target chat support for the conversion which will translate. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
tense | str | The tense the converter should convert the prompt to. E.g. past, present, future. |
prompt_template | (SeedPrompt, Optional) | The prompt template for the conversion. Defaults to None. |
Examples:
TextJailbreakConverter¶
Bases: Converter
Uses a jailbreak template to create a prompt.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
jailbreak_template | TextJailBreak | The jailbreak template to use for conversion. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt using the jailbreak template.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted output and its type.
Raises:
ValueError— If the input type is not supported.
TextSelectionStrategy¶
Bases: abc.ABC
Base class for text selection strategies used by SelectiveTextConverter and WordLevelConverter. Defines how to select a region of text or words for conversion.
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the parameters that affect which text this strategy selects.
Values must be JSON-serializable and stored in a stable, order-independent form when the original input was a set-like collection.
Returns:
dict[str, Any]— dict[str, Any]: Behavioral parameters for converter identifiers.
select_range¶
select_range(text: str) → tuple[int, int]Select a range of characters in the text to be converted.
| Parameter | Type | Description |
|---|---|---|
text | str | The input text to select from. |
Returns:
tuple[int, int]— tuple[int, int]: A tuple of (start_index, end_index) representing the character range. The range is inclusive of start_index and exclusive of end_index.
TokenBijectionConverter¶
Bases: BijectionConverter
Bijection converter that maps letters to tokens from a tokenizer vocabulary. Each English letter maps to a randomly sampled distinct token from the target model’s tokenizer vocabulary. Based on mode 3 from arXiv:2410.01294 (Haize Labs).
Unlike LetterBijectionConverter/DigitBijectionConverter, each mapped unit is a variable-length word rather than a fixed-width symbol, so encoded units are separated by a delimiter to keep them legible and unambiguously decodable.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
tokenizer | _TokenizerWithVocab | A HuggingFace tokenizer with get_vocab() method. |
mapping | dict[str, str] | None | Optional explicit mapping dict. Defaults to None. |
seed | int | None | Optional random seed for reproducibility. Defaults to None. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultEncode the prompt using token words.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the encoded prompt.
Raises:
ValueError— If the input type is not supported.
decode¶
decode(encoded_text: str) → strDecode token-word text back to plaintext.
A doubled delimiter is restored to one literal hyphen; unrecognized text is preserved.
| Parameter | Type | Description |
|---|---|---|
encoded_text | str | The encoded text to decode. |
Returns:
str— The decoded plain text.
encode¶
encode(prompt: str) → strEncode text using token words, hyphen-delimited word runs, and literal-hyphen escapes.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to encode. |
Returns:
str— The encoded prompt.
get_teaching_instructions¶
get_teaching_instructions() → strReturn the token-mode setup instructions.
Returns:
str— Instructions for using this token mapping.
TokenSelectionStrategy¶
Bases: TextSelectionStrategy
A special selection strategy that signals SelectiveTextConverter to auto-detect and convert text between start/end tokens (e.g., ⟪ and ⟫).
This strategy is used when chaining converters with preserve_tokens=True. Instead of programmatically selecting text, it relies on tokens already present in the text from a previous converter.
Examples:
Methods:
select_range¶
select_range(text: str) → tuple[int, int]Do not use this method for TokenSelectionStrategy. SelectiveTextConverter handles token detection separately.
| Parameter | Type | Description |
|---|---|---|
text | str | The input text (ignored). |
Returns:
tuple[int, int]— tuple[int, int]: Always returns (0, 0) as this strategy uses token detection instead.
ToneConverter¶
Bases: LLMGenericTextConverter
Converts a conversation to a different tone using an LLM.
An existing PromptTarget is used to perform the conversion (like Azure OpenAI).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The target chat support for the conversion which will translate. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
tone | str | The tone for the conversation. E.g. upset, sarcastic, indifferent, etc. |
prompt_template | (SeedPrompt, Optional) | The prompt template for the conversion. Defaults to None. |
Examples:
ToxicSentenceGeneratorConverter¶
Bases: LLMGenericTextConverter
Generates toxic sentence starters using an LLM.
An existing PromptTarget is used to perform the conversion (like Azure OpenAI).
Based on Project Moonshot’s attack module that generates toxic sentences to test LLM
safety guardrails:
attack
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The endpoint that converts the prompt. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
prompt_template | SeedPrompt | The seed prompt template to use. If not provided, defaults to the toxic_sentence_generator.yaml. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt into a toxic sentence starter.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The conversion result containing the toxic sentence starter.
input_supported¶
input_supported(input_type: PromptDataType) → boolCheck if the input type is supported.
| Parameter | Type | Description |
|---|---|---|
input_type | PromptDataType | The type of input data. |
Returns:
bool— True if the input type is supported, False otherwise.
output_supported¶
output_supported(output_type: PromptDataType) → boolCheck if the output type is supported.
| Parameter | Type | Description |
|---|---|---|
output_type | PromptDataType | The type of output data. |
Returns:
bool— True if the output type is supported, False otherwise.
TranslationConverter¶
Bases: LLMGenericTextConverter
Translates prompts into different languages using an LLM.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The target chat support for the conversion which will translate. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
language | str | The language for the conversion. E.g. Spanish, French, leetspeak, etc. |
prompt_template | SeedPrompt | None | The prompt template for the conversion. Defaults to DEFAULT_PROMPT_TEMPLATE. |
max_retries | int | Maximum number of retry attempts on failure. Defaults to 3. |
max_wait_time_in_seconds | int | Upper bound for exponential backoff between retries. Defaults to 60. |
Examples:
TransparencyAttackConverter¶
Bases: Converter
Creates a transparency attack by optimizing an alpha channel to blend attack and benign images.
Currently, only JPEG images are supported as input. Output images will always be saved as PNG with transparency.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
benign_image_path | Path | Path to the benign image file. Must be a JPEG file (.jpg or .jpeg). |
size | tuple | Size that the images will be resized to (width, height). It is recommended to use a size that matches aspect ratio of both attack and benign images. Since the original study resizes images to 150x150 pixels, this is the default size used. Bigger values may significantly increase computation time. Defaults to (150, 150). |
steps | int | Number of optimization steps to perform. Recommended range: 100-2000 steps. Default is 1500. Generally, the higher the steps, the better end result you can achieve, but at the cost of increased computation time. Defaults to 1500. |
learning_rate | float | Controls the magnitude of adjustments in each step (used by the Adam optimizer). Recommended range: 0.0001-0.01. Default is 0.001. Values close to 1 may lead to instability and lower quality blending, while values too low may require more steps to achieve a good blend. Defaults to 0.001. |
convergence_threshold | float | Minimum change in loss required to consider improvement. If the change in loss between steps is below this value, it’s counted as no improvement. Default is 1e-6. Recommended range: 1e-6 to 1e-4. Defaults to 1e-06. |
convergence_patience | int | Number of consecutive steps with no improvement before stopping. Default is 10. Defaults to 10. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'image_path') → ConverterResultConvert the given prompt by blending an attack image (potentially harmful) with a benign image. Uses the Novel Image Blending Algorithm from McKee & Noever, 2024.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The image file path to the attack image. |
input_type | PromptDataType | The type of input data. Must be “image_path”. Defaults to 'image_path'. |
Returns:
ConverterResult— The result containing path to the manipulated image with transparency.
Raises:
ValueError— If the input type is not supported or if the prompt is invalid.
UnicodeConfusableConverter¶
Bases: Converter
Applies substitutions to words in the prompt to test adversarial textual robustness by replacing characters with visually similar ones.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
source_package | Literal['confusable_homoglyphs', 'confusables', 'cyrillic_homoglyph'] | The package to use for homoglyph generation. Can be one of: - “confusable_homoglyphs” (https://'confusable_homoglyphs'. |
deterministic | bool | This argument is for unittesting only. Defaults to False. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by applying confusable substitutions. This leads to a prompt that looks similar, but is actually different (e.g., replacing a Latin ‘a’ with a Cyrillic ‘а’).
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the prompt with confusable substitutions applied.
Raises:
ValueError— If the input type is not supported.
UnicodeReplacementConverter¶
Bases: WordLevelConverter
Converts a prompt to its unicode representation.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
encode_spaces | bool | If True, spaces in the prompt will be replaced with unicode representation. Defaults to False. |
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, all words will be converted. Defaults to None. |
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
join_words¶
join_words(words: list[str]) → strJoin a list of words into a single string, optionally encoding spaces as unicode.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of words to join. |
Returns:
str— The joined string.
UnicodeSubstitutionConverter¶
Bases: Converter
Encodes the prompt using any unicode starting point.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
start_value | int | The unicode starting point to use for encoding. Defaults to 917504. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by encoding it using any unicode starting point. Default is to use invisible flag emoji characters.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted output and its type.
Raises:
ValueError— If the input type is not supported, or if shifting a character bystart_valuedoes not give a valid Unicode scalar value (above U+10FFFF or a surrogate).
UrlConverter¶
Bases: Converter
Converts a prompt to a URL-encoded string.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
safe | str | Characters that should not be URL-encoded. Defaults to “/”, matching urllib.parse.quote. Set to “” to encode forward slashes. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt into a URL-encoded string.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the URL-encoded prompt.
Raises:
ValueError— If the input type is not supported.
VariationConverter¶
Bases: LLMGenericTextConverter
Generates variations of the input prompts using the converter target.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
converter_target | PromptTarget | The target to which the prompt will be sent for conversion. Can be omitted if a default has been configured via PyRIT initialization. Defaults to REQUIRED_VALUE. |
prompt_template | SeedPrompt | None | The template used for generating the system prompt. If not provided, a default template will be used. Defaults to None. |
Examples:
VariationSelectorSmugglerConverter¶
Bases: SmugglerConverter
Encodes and decodes text using Unicode Variation Selectors.
If embed_in_base is True, the payload is concatenated with a base character
(default: 😊); otherwise, a space separator is inserted. A one-byte payload of
0x0E or 0x0F always uses the separator to distinguish it from an emoji’s presentation selector.
Extension: In addition to embedding into a base character, we also support appending invisible variation selectors directly to visible text—enabling mixed visible and hidden content within a single string.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
action | Literal['encode', 'decode'] | The action to perform. Defaults to 'encode'. |
base_char_utf8 | str | None | Base character for variation_selector_smuggler mode (default: 😊). Defaults to None. |
embed_in_base | bool | If True, the hidden payload is embedded directly into the base character. If False, a visible separator (space) is inserted between the base and payload. Default is True. Defaults to True. |
Examples:
Methods:
decode_message¶
decode_message(message: str) → strDecode a message encoded using Unicode variation selectors.
The decoder reads the variation selectors that follow the base character, with or without the space separator. Selectors elsewhere in the text, such as the U+FE0F in an emoji like ❤️, are not part of the payload. A lone U+FE0E or U+FE0F directly adjacent to the base character is ambiguous with emoji presentation; a space separator identifies it as a payload. If no unambiguous anchored payload is found, the first run of variation selectors is decoded for compatibility.
| Parameter | Type | Description |
|---|---|---|
message | str | The encoded message. |
Returns:
str— The decoded message.
decode_visible_hidden¶
decode_visible_hidden(combined: str) → tuple[str, str]Extract the visible text and decodes the hidden text from a combined string.
encode_visible_hidden appends the base character and the hidden payload after the visible text, so the
last occurrence of the base character starts the hidden payload. The visible text may contain the base
character itself.
| Parameter | Type | Description |
|---|---|---|
combined | str | The combined text containing visible and hidden parts. |
Returns:
tuple[str, str]— tuple[str, str]: A tuple with the visible text and the decoded hidden text.
encode_message¶
encode_message(message: str) → tuple[str, str]Encode the message using Unicode variation selectors.
The message is converted to UTF-8 bytes, and each byte is mapped to a variation selector: - 0x00-0x0F => U+FE00 to U+FE0F. - 0x10-0xFF => U+E0100 to U+E01EF.
If embed_in_base is True, the payload is embedded directly into the base character;
otherwise, a visible separator (a space) is inserted between the base and payload.
One-byte 0x0E and 0x0F payloads always use the separator because their selectors also
control emoji presentation.
| Parameter | Type | Description |
|---|---|---|
message | str | The message to encode. |
Returns:
tuple[str, str]— tuple[str, str]: A tuple containing a summary of the code points and the encoded string.
encode_visible_hidden¶
encode_visible_hidden(visible: str, hidden: str) → tuple[str, str]Combine visible text with hidden text by encoding the hidden text using variation_selector_smuggler mode.
The hidden payload is generated as a composite using the current embedding setting and then appended to the visible text.
| Parameter | Type | Description |
|---|---|---|
visible | str | The visible text. |
hidden | str | The secret/hidden text to encode. |
Returns:
tuple[str, str]— tuple[str, str]: A tuple containing a summary and the combined text.
VigenereConverter¶
Bases: Converter
Encodes text using the Vigenere cipher with a specified key.
The Vigenere cipher is a polyalphabetic substitution cipher that generalizes the Caesar cipher: instead of a single fixed shift, each letter of the plaintext is shifted by an amount determined by the corresponding letter of a repeating keyword.
Using key="key", ‘Hello’ would encode to ‘Rijvs’, as each letter is shifted by the amount
corresponding to the aligned letter of the repeating key (‘k’, ‘e’, ‘y’, ‘k’, ‘e’).
Only alphabetic characters advance the position in the key; non-alphabetic characters
(spaces, digits, punctuation) are passed through unchanged and do not consume a key letter.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
key | str | The keyword used to encode the prompt. Must consist of alphabetic characters only. |
append_description | bool | If True, appends plaintext “expert” text to the prompt. This includes instructions to only communicate using the cipher, a description of the cipher, and an example encoded using the cipher. Defaults to False. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt using the Vigenere cipher.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The input prompt to be converted. |
input_type | PromptDataType | The type of the input prompt. Must be “text”. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the converted prompt and its type.
Raises:
ValueError— If the input type is not supported.
WordDocConverter¶
Bases: Converter
Convert a text prompt into a Word (.docx) document.
This converter supports two main modes:
New document generation If no existing document is provided, the converter creates a simple
.docxcontaining the rendered prompt content in a single paragraph.Placeholder-based injection into an existing document If an
existing_docxis provided, the converter searches for a literal placeholder string (for example{{INJECTION_PLACEHOLDER}}) in the document’s paragraphs. When the placeholder is found fully inside a single run, it is replaced with the rendered prompt content while preserving the rest of the paragraph and its formatting... important:: Placeholders must be fully contained within a single run. If a placeholder spans multiple runs (for example due to mixed formatting), this converter will not replace it. This limitation is intentional to avoid collapsing mixed formatting or rewriting complex run structures.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
prompt_template | SeedPrompt | None | Optional SeedPrompt template used to render the final content before injection. If provided, prompt passed to convert_async must be a string whose contents can be interpreted as the template parameters (for example, a JSON-encoded or other parseable mapping of keys to values). Defaults to None. |
existing_docx | Path | None | Optional path to an existing .docx file. When provided, the converter will search for placeholder inside the document paragraphs and replace it with the rendered content. If not provided, a new document is generated instead. Defaults to None. |
placeholder | str | Literal placeholder text to search for in the existing document. This value must be fully contained within a single run for the replacement to succeed. Defaults to '{{INJECTION_PLACEHOLDER}}'. |
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt into a Word document (.docx).
If prompt_template is provided, the prompt is first used to render the
template via SeedPrompt.render_template_value. Otherwise, the raw
prompt string is used as the content.
When
existing_docxis set, this content is injected into the document by replacing the configured placeholder string.When no
existing_docxis provided, a new document with a single paragraph containing the content is created.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt or dynamic data used to generate the content. |
input_type | PromptDataType | The type of input data. Must be "text". Defaults to 'text'. |
Returns:
ConverterResult— Contains the path to the generated.docxfile inConverterResult—output_textandoutput_type="binary_path".
Raises:
ValueError— If the input type is not supported.
WordIndexSelectionStrategy¶
Bases: WordSelectionStrategy
Selects words based on their indices in the word list.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
indices | list[int] | The list of word indices in conversion order. |
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the selected indices in conversion order.
Returns:
dict[str, Any]— dict[str, Any]: The ordered index list.
select_words¶
select_words(words: list[str]) → list[int]Select words at the specified indices.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of words to select from. |
Returns:
list[int]— list[int]: The list of valid indices.
Raises:
ValueError— If any indices are out of range.
WordKeywordSelectionStrategy¶
Bases: WordSelectionStrategy
Selects words that match specific keywords.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
keywords | list[str] | The list of keywords to match. |
case_sensitive | bool | Whether matching is case-sensitive. Defaults to True. |
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the keyword list and case-sensitivity flag.
Returns:
dict[str, Any]— dict[str, Any]: Sorted keywords and the case-sensitivity flag.
select_words¶
select_words(words: list[str]) → list[int]Select words that match the keywords.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of words to select from. |
Returns:
list[int]— list[int]: The list of indices where keywords were found.
WordPositionSelectionStrategy¶
Bases: WordSelectionStrategy
Selects words based on proportional start and end positions.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
start_proportion | float | The starting position as a proportion (0.0 to 1.0). |
end_proportion | float | The ending position as a proportion (0.0 to 1.0). |
Examples:
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the start and end proportions.
Returns:
dict[str, Any]— dict[str, Any]: Start and end proportions.
select_words¶
select_words(words: list[str]) → list[int]Select words based on the relative position.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of words to select from. |
Returns:
list[int]— list[int]: The list of indices in the specified position range.
WordProportionSelectionStrategy¶
Bases: WordSelectionStrategy
Selects a random proportion of words.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
proportion | float | The proportion of words to select (0.0 to 1.0). |
seed | int | None | Random seed for reproducible selections. Defaults to None. Scoped to this strategy: it makes this strategy reproducible without affecting the randomness of any other component. |
Examples:
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the proportion and optional seed.
Returns:
dict[str, Any]— dict[str, Any]: Proportion and seed when one was provided.
select_words¶
select_words(words: list[str]) → list[int]Select a random proportion of words.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of words to select from. |
Returns:
list[int]— list[int]: The list of randomly selected indices.
WordRegexSelectionStrategy¶
Bases: WordSelectionStrategy
Selects words that match a regex pattern.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
pattern | str | Pattern[str] | The regex pattern to match against words. |
Examples:
Methods:
get_identifier_params¶
get_identifier_params() → dict[str, Any]Return the regex pattern and flags.
Returns:
dict[str, Any]— dict[str, Any]: Pattern string and compiled flags.
select_words¶
select_words(words: list[str]) → list[int]Select words that match the regex pattern.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of words to select from. |
Returns:
list[int]— list[int]: The list of indices where words matched the pattern.
WordSelectionStrategy¶
Bases: TextSelectionStrategy, StructuredParameterValue
Base class for word-level selection strategies.
Word selection strategies work by splitting text into words and selecting specific word indices. They provide a select_words() method and implement select_range() by converting word selections to character ranges.
Methods:
get_registry_input_variants¶
get_registry_input_variants() → dict[str, type[StructuredParameterValue]]Return the safe implementations available to registry input consumers.
select_range¶
select_range(text: str, word_separator: str = ' ') → tuple[int, int]Select a character range by first selecting words, then converting to character positions.
This implementation splits the text by word_separator, gets selected word indices, then calculates the character range that spans those words.
| Parameter | Type | Description |
|---|---|---|
text | str | The input text to select from. |
word_separator | str | The separator used to split words. Defaults to " ". |
Returns:
tuple[int, int]— tuple[int, int]: A tuple of (start_index, end_index) representing the character range that encompasses all selected words.
select_words¶
select_words(words: list[str]) → list[int]Select word indices to be converted.
| Parameter | Type | Description |
|---|---|---|
words | list[str] | The list of words to select from. |
Returns:
list[int]— list[int]: A list of indices representing which words should be converted.
ZalgoConverter¶
Bases: WordLevelConverter
Converts text into cursed Zalgo text using combining Unicode marks.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
intensity | int | Number of combining marks per character (higher = more cursed). Default is 10. Defaults to 10. |
seed | int | None | Optional root seed for this conversion. Nested components inherit independent child streams unless they provide their own seed. If omitted, the converter inherits the root configured by initialize_pyrit_async(seed=...). Defaults to None. |
word_selection_strategy | WordSelectionStrategy | None | Strategy for selecting which words to convert. If None, all words will be converted. Defaults to None. |
Examples:
Methods:
convert_word_async¶
convert_word_async(word: str) → strConvert a single word into the target format supported by the converter.
| Parameter | Type | Description |
|---|---|---|
word | str | The word to be converted. |
Returns:
str— The converted word.
ZeroWidthConverter¶
Bases: Converter
Injects zero-width spaces between characters in the provided text to bypass content safety mechanisms.
Characters are grapheme clusters, so combining marks, Indic vowel signs and emoji sequences stay whole.
Examples:
Methods:
convert_async¶
convert_async(prompt: str, input_type: PromptDataType = 'text') → ConverterResultConvert the given prompt by injecting zero-width spaces between each character.
| Parameter | Type | Description |
|---|---|---|
prompt | str | The prompt to be converted. |
input_type | PromptDataType | The type of input data. Defaults to 'text'. |
Returns:
ConverterResult— The result containing the modified prompt.
Raises:
ValueError— If the input type is not supported.
- Rehberger, J. (2024). Hiding and Finding Text with Unicode Tags. https://embracethered.com/blog/posts/2024/hiding-and-finding-text-with-unicode-tags/
- Priyanshu, A. (2024). Bypassing Meta’s LLaMA Classifier: A Simple Jailbreak. https://blogs.cisco.com/security/bypassing-metas-llama-classifier-a-simple-jailbreak
- Ren, Q., Gao, C., Shao, J., Yan, J., Tan, X., Lam, W., & Ma, L. (2024). CodeAttack: Revealing Safety Generalization Challenges of Large Language Models via Code Completion. Findings of the Association for Computational Linguistics: ACL 2024, 11437–11452. 10.18653/v1/2024.findings-acl.679
- Lv, H., Wang, X., Zhang, Y., Huang, C., Dou, S., Ye, J., Gui, T., Zhang, Q., & Huang, X. (2024). CodeChameleon: Personalized Encryption Framework for Jailbreaking Large Language Models. arXiv Preprint arXiv:2402.16717. https://arxiv.org/abs/2402.16717
- Liu, T., Zhang, Y., Zhao, Z., Dong, Y., Meng, G., & Chen, K. (2024). Making Them Ask and Answer: Jailbreaking Large Language Models in Few Queries via Disguise and Reconstruction. 33rd USENIX Security Symposium (USENIX Security 24), 4711–4728. https://www.usenix.org/conference/usenixsecurity24/presentation/liu-tong
- Li, X., Wang, R., Cheng, M., Zhou, T., & Hsieh, C.-J. (2024). DrAttack: Prompt Decomposition and Reconstruction Makes Powerful LLM Jailbreakers. Findings of the Association for Computational Linguistics: EMNLP 2024. https://arxiv.org/abs/2402.16914
- Huang, B. R. Y., Li, M., & Tang, L. (2024). Endless Jailbreaks With Bijection Learning. arXiv Preprint arXiv:2410.01294. https://arxiv.org/abs/2410.01294
- Zeng, Y., Lin, H., Zhang, J., Yang, D., Jia, R., & Shi, W. (2024). How Johnny Can Persuade LLMs to Jailbreak Them: Rethinking Persuasion to Challenge AI Safety by Humanizing LLMs. arXiv Preprint arXiv:2401.06373. https://arxiv.org/abs/2401.06373
- Ahn, Y., & Lee, J. (2025). PUZZLED: Jailbreaking LLMs through Word-Based Puzzles. arXiv Preprint arXiv:2508.01306. https://arxiv.org/abs/2508.01306
- Dong, X., Hu, W., Xu, W., & He, T. (2025). SATA: A Paradigm for LLM Jailbreak via Simple Assistive Task Linkage. Findings of the Association for Computational Linguistics: ACL 2025, 1952–1987. 10.18653/v1/2025.findings-acl.100
- McKee, F., & Noever, D. (2024). Transparency Attacks: How Imperceptible Image Layers Can Fool AI Perception. arXiv Preprint arXiv:2401.15817. https://arxiv.org/abs/2401.15817