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

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

pyrit.exceptions

Exception classes, retry helpers, and execution context utilities.

Functions

clear_execution_context

clear_execution_context() → None

Clear the current execution context.

execution_context

execution_context(component_role: ComponentRole, attack_strategy_name: Optional[str] = None, attack_identifier: Optional[ComponentIdentifier] = None, component_identifier: Optional[ComponentIdentifier] = None, objective_target_conversation_id: Optional[str] = None, objective: Optional[str] = None) → ExecutionContextManager

Create an execution context manager with the specified parameters.

ParameterTypeDescription
component_roleComponentRoleThe role of the component being executed.
attack_strategy_nameOptional[str]The name of the attack strategy class. Defaults to None.
attack_identifierOptional[ComponentIdentifier]The attack identifier. Defaults to None.
component_identifierOptional[ComponentIdentifier]The identifier from component.get_identifier(). Defaults to None.
objective_target_conversation_idOptional[str]The objective target conversation ID if available. Defaults to None.
objectiveOptional[str]The attack objective if available. Defaults to None.

Returns:

get_execution_context

get_execution_context() → Optional[ExecutionContext]

Get the current execution context.

Returns:

get_retry_max_num_attempts

get_retry_max_num_attempts() → int

Get the maximum number of retry attempts.

Returns:

handle_bad_request_exception

handle_bad_request_exception(response_text: str, request: MessagePiece, is_content_filter: bool = False, error_code: int = 400) → Message

Handle bad request responses and map them to standardized error messages.

ParameterTypeDescription
response_textstrRaw response text from the target.
requestMessagePieceOriginal request piece that caused the error.
is_content_filterboolWhether the response is known to be content-filtered. Defaults to False.
error_codeintStatus code to include in the generated error payload. Defaults to 400.

Returns:

Raises:

pyrit_custom_result_retry

pyrit_custom_result_retry(retry_function: Callable[..., bool], retry_max_num_attempts: Optional[int] = None) → Callable[..., Any]

Apply retry logic with exponential backoff to a function.

Retries the function if the result of the retry_function is True, with a wait time between retries that follows an exponential backoff strategy. Logs retry attempts at the INFO level and stops after a maximum number of attempts.

ParameterTypeDescription
retry_functionCallableThe boolean function to determine if a retry should occur based on the result of the decorated function.
retry_max_num_attempts(Optional, int)The maximum number of retry attempts. Defaults to environment variable CUSTOM_RESULT_RETRY_MAX_NUM_ATTEMPTS or 10. Defaults to None.

Returns:

pyrit_json_retry

pyrit_json_retry(func: Callable[..., Any]) → Callable[..., Any]

Apply retry logic to a function.

Retries the function if it raises a JSON error. Logs retry attempts at the INFO level and stops after a maximum number of attempts.

ParameterTypeDescription
funcCallableThe function to be decorated.

Returns:

pyrit_placeholder_retry

pyrit_placeholder_retry(func: Callable[..., Any]) → Callable[..., Any]

Apply retry logic.

Retries the function if it raises MissingPromptPlaceholderException. Logs retry attempts at the INFO level and stops after a maximum number of attempts.

ParameterTypeDescription
funcCallableThe function to be decorated.

Returns:

pyrit_target_retry

pyrit_target_retry(func: Callable[..., Any]) → Callable[..., Any]

Apply retry logic with exponential backoff to a function.

Retries the function if it raises RateLimitError or EmptyResponseException, with a wait time between retries that follows an exponential backoff strategy. Logs retry attempts at the INFO level and stops after a maximum number of attempts.

ParameterTypeDescription
funcCallableThe function to be decorated.

Returns:

remove_markdown_json

remove_markdown_json(response_msg: str) → str

Remove markdown wrappers and return a JSON payload when possible.

ParameterTypeDescription
response_msgstrThe response message to check.

Returns:

set_execution_context

set_execution_context(context: ExecutionContext) → None

Set the current execution context.

ParameterTypeDescription
contextExecutionContextThe execution context to set.

BadRequestException

Bases: PyritException

Exception class for bad client requests.

Constructor Parameters:

ParameterTypeDescription
status_codeintStatus code for the error. Defaults to 400.
messagestrError message. Defaults to 'Bad Request'.

ComponentRole

Bases: Enum

Identifies the role of a component within an attack execution.

This enum is used to provide meaningful context in error messages and retry logs, helping users identify which part of an attack encountered an issue.

EmptyResponseException

Bases: BadRequestException

Exception class for empty response errors.

Constructor Parameters:

ParameterTypeDescription
status_codeintStatus code for the error. Defaults to 204.
messagestrError message. Defaults to 'No Content'.

ExecutionContext

Holds context information about the currently executing component.

This context is used to enrich error messages and retry logs with information about which component failed and its configuration.

Methods:

get_exception_details

get_exception_details() → str

Generate detailed exception context for error messages.

Returns:

get_retry_context_string

get_retry_context_string() → str

Generate a concise context string for retry log messages.

Returns:

ExecutionContextManager

A context manager for setting execution context during component operations.

This class provides a convenient way to set and automatically clear execution context when entering and exiting a code block.

On successful exit, the context is restored to its previous value. On exception, the context is preserved so exception handlers can access it.

InvalidJsonException

Bases: PyritException

Exception class for blocked content errors.

Constructor Parameters:

ParameterTypeDescription
messagestrError message. Defaults to 'Invalid JSON Response'.

MissingPromptPlaceholderException

Bases: PyritException

Exception class for missing prompt placeholder errors.

Constructor Parameters:

ParameterTypeDescription
messagestrError message. Defaults to 'No prompt placeholder'.

PyritException

Bases: Exception, ABC

Base exception class for PyRIT components.

Constructor Parameters:

ParameterTypeDescription
status_codeintHTTP-style status code associated with the error. Defaults to 500.
messagestrHuman-readable error description. Defaults to 'An error occurred'.

Methods:

process_exception

process_exception() → str

Log and return a JSON string representation of the exception.

Returns:

RateLimitException

Bases: PyritException

Exception class for authentication errors.

Constructor Parameters:

ParameterTypeDescription
status_codeintStatus code for the error. Defaults to 429.
messagestrError message. Defaults to 'Rate Limit Exception'.