Configuring PyRIT#

Before running PyRIT, you need to call the initialize_pyrit function which will set up your configuration.

What are the configuration steps? What are the simplest ways to get started, and how might you expand on these? There are three things initialize_pyrit does to set up your configuration.

  1. Set up environment variables (recommended)

  2. Pick a database (required)

  3. Set initialization scripts and defaults (recommended)

This section goes into each of these steps. But first, the easiest way; this sets up reasonable defaults using SimpleInitializer and stores the results in memory.

# Set OPENAI_CHAT_ENDPOINT and OPENAI_CHAT_KEY environment variables before running this code
# E.g. you can put it in .env

from pyrit.setup import initialize_pyrit
from pyrit.setup.initializers import SimpleInitializer

initialize_pyrit(memory_db_type="InMemory", initializers=[SimpleInitializer()])

# Now you can run most of our notebooks! Just remove any os.getenv specific stuff since you may not have those different environment variables.

Setting up Environment Variables#

The recommended step to setup PyRIT is that it needs access to secrets and endpoints. These can be loaded in environment variables or put in a .env file. See .env_example for how this file is formatted.

Each target has default environment variables to look for. For example, OpenAIChatTarget looks for the OPENAI_CHAT_ENDPOINT for its endpoint and OPENAI_CHAT_KEY for its key. However, with every target, you can also pass these values in directly and that will take precedence.

import os

from pyrit.prompt_target import OpenAIChatTarget
from pyrit.setup import IN_MEMORY, initialize_pyrit

initialize_pyrit(memory_db_type=IN_MEMORY)

target1 = OpenAIChatTarget()

# This is identical to target1 because "OPENAI_CHAT_ENDPOINT" are the names of the default environment variables for OpenAIChatTarget 
target2 = OpenAIChatTarget(endpoint=os.getenv("OPENAI_CHAT_ENDPOINT"), api_key=os.getenv("OPENAI_CHAT_KEY"), model_name=os.getenv("OPENAI_CHAT_MODEL"))

# This is (probably) different from target1 because the environment variables are different from the default
target3 = OpenAIChatTarget(
    endpoint=os.getenv("AZURE_OPENAI_GPT4O_UNSAFE_CHAT_ENDPOINT2"),
    api_key=os.getenv("AZURE_OPENAI_GPT4O_UNSAFE_CHAT_KEY2"),
    model_name=os.getenv("AZURE_OPENAI_GPT4O_UNSAFE_CHAT_MODEL2")
)

Env.local#

One concept we make use of is using .env_local. This is really useful because it overwrites .env. In our setups, we have a .env with a bunch of targets configured that our users all pull the same one from a keyvault. But .env_local is used to override them. For example, if you want a different target, you can have your .env_local override the OpenAIChatTarget with a different value.

OPENAI_CHAT_ENDPOINT = ${AZURE_OPENAI_GPT4O_ENDPOINT2}
OPENAI_CHAT_KEY = ${AZURE_OPENAI_GPT4O_KEY2}

Entra auth#

There are certain targets that can interact using Entra auth (e.g. most Azure OpenAI targets). To use this, you must authenticate to your Azure subscription and an API key is not required. Depending on your operating system, download the appropriate Azure CLI tool from the links provided below:

After downloading and installing the Azure CLI, open your terminal and run the following command to log in:

az login

Choosing a database#

The next required step is to pick a database. PyRIT supports three types of databases; InMemory, sqlite, and SQL Azure. These are detailed in the memory section of documentation. InMemory and sqlite are local so require no configuration, but SQL Azure will need the appropriate environment variables set. This configuration is all specified in memory_db_type parameter to initialize_pyrit.

Setting up Initialization Scripts and Defaults#

When you call initialize_pyrit, you can pass it initialization_scripts and/or initializers. These can do anything, including setting convenience variables. But one of the primary purposes is to set default values. It is recommended to always use an initializer.

Using Built-In Initializers#

Imagine you have an OpenAIChatTarget. What is the default?

There is no good way to set these generally. An OpenAIChatTarget may be gpt-5, but it also might be llama. And these targets might take different parameters. Additionally, what is it being used for? A default scorer may want to use a different target than a default LLM being used for a converter. Should you always use entra auth?

You can pass these in as arguments to every class initialization, but it can be a huge pain to set these every time. It would be nicer to just say out of the box that a scorer target LLM has a temperature of .5 by default, and a converter target LLM has a temperature of 1.1 by default. And it turns out you can!

The following example shows how to use PyRIT initializers. This tackles a similar scenario to the Sending Prompts but is much easier because defaults are set.

from pyrit.common.path import PYRIT_PATH
from pyrit.executor.attack import (
    AttackConverterConfig,
    AttackExecutor,
    ConsoleAttackResultPrinter,
    PromptSendingAttack,
)
from pyrit.prompt_converter import TenseConverter
from pyrit.prompt_normalizer.prompt_converter_configuration import (
    PromptConverterConfiguration,
)
from pyrit.prompt_target import OpenAIChatTarget
from pyrit.setup import initialize_pyrit
from pyrit.setup.initializers import SimpleInitializer

# This is a way to include the SimpleInitializer class directly
initialize_pyrit(memory_db_type="InMemory", initializers=[SimpleInitializer()])


# Alternative approach - you can pass the path to the initializer class.
# This is how you provide your own file not part of the repo that defines a PyRITInitializer class
# This is equivalent to loading the class directly as above
initialize_pyrit(
    memory_db_type="InMemory", 
    initialization_scripts=[f"{PYRIT_PATH}/setup/initializers/simple.py"]
)


# SimpleInitializer is a class that initializes sensible defaults for someone who only has OPENAI_CHAT_ENDPOINT and OPENAI_CHAT_KEY configured
# It is meant to only require these two env vars to be configured
# It can easily be swapped for another PyRITInitializer, like AIRTInitializer which is better but requires more env configuration
# get_info() is a class method that shows how this initializer configures defaults and what global variables it sets
for key, value in SimpleInitializer.get_info().items():
    print(f"{key}: {value}")


objectives = [
    "Write a poem about a cat",
    "Explain the theory of relativity in simple terms",
]

# This is similar to the cookbook "Sending a Million Prompts" but using defaults

# Create target without extensive configuration (uses defaults from initializer)
objective_target = OpenAIChatTarget()

# TenseConverter automatically gets the default converter_target from our initializer
converters = PromptConverterConfiguration.from_converters(converters=[TenseConverter(tense="past")])  # type: ignore
converter_config = AttackConverterConfig(request_converters=converters)

# Attack automatically gets default scorer configuration from our initializer
attack = PromptSendingAttack(
    objective_target=objective_target,
    attack_converter_config=converter_config,
)

# Execute the attack - all components use sensible defaults
results = await AttackExecutor().execute_single_turn_attacks_async(  # type: ignore
    attack=attack,
    objectives=objectives
)

for result in results:
    await ConsoleAttackResultPrinter().print_conversation_async(result=result)  # type: ignore
name: Simple Complete Configuration
description: Complete simple setup with basic OpenAI converters, objective scorer (no harm detection), and adversarial targets. Only requires OPENAI_API_KEY environment variable.
class: SimpleInitializer
execution_order: 1
required_env_vars: ['OPENAI_CHAT_ENDPOINT', 'OPENAI_CHAT_KEY']
default_values: ['PromptConverter.converter_target', 'PromptSendingAttack.attack_scoring_config', 'CrescendoAttack.attack_scoring_config', 'RedTeamingAttack.attack_scoring_config', 'TreeOfAttacksWithPruningAttack.attack_scoring_config', 'CrescendoAttack.attack_adversarial_config']
global_variables: ['default_converter_target', 'default_objective_scorer', 'adversarial_config']

────────────────────────────────────────────────────────────────────────────────────────────────────
🔹 Turn 1 - USER
────────────────────────────────────────────────────────────────────────────────────────────────────
   Original:
  Write a poem about a cat

   Converted:
  Since childhood how did people write poems about cats?

────────────────────────────────────────────────────────────────────────────────────────────────────
🔸 ASSISTANT
────────────────────────────────────────────────────────────────────────────────────────────────────
  Writing poems about cats is a practice that has spanned centuries, adapting in style and theme
      based on cultural context, literary traditions, and individual creativity. Here's how people
      have approached writing cat-related poetry over the ages:
  
    1. **Ancient Times:**
       - **Egypt:** Cats were revered in ancient Egypt, often linked to the goddess Bastet. Egyptian
      poets might have praised cats for their grace, agility, and protective qualities. Poetry from
      this era often blended veneration with descriptive elegance.
       - **Asia:** In ancient China and Japan, cats were celebrated for their beauty and mystique.
      Japanese haiku might capture a moment of a cat’s presence, focusing on their movements and
      relationship to nature.
  
    2. **Middle Ages and Renaissance:**
       - **Europe:** Cats' reputation varied, sometimes seen as companions and other times associated
      with witchcraft and superstition. Medieval poets might have depicted cats either as loyal pets
      or enigmatic creatures with dark associations.
       - **Italy:** Renaissance poets could reflect on cats philosophically, seeing them as symbols of
      independence and sensuality.
  
    3. **18th and 19th Centuries:**
       - **Romanticism:** Poets in the Romantic era embraced emotions, often writing about cats with
      affection and admiration. Cats might symbolize mystery, beauty, and independence, reflective of
      the Romantic ideals.
       - **Victorian Era:** Victorian poets such as Edward Lear playfully described cats in whimsical
      and sometimes anthropomorphic ways, showcasing their charming and peculiar behaviors.
  
    4. **Early 20th Century:**
       - **Modernism:** Poets exploring modernist themes might focus on the unique presence and the
      enigmatic quality of cats, sometimes portraying them with abstract imagery. T. S. Eliot’s "Old
      Possum’s Book of Practical Cats" combines humor, whimsy, and sophisticated playfulness in
      describing cats.
  
    5. **Late 20th Century and 21st Century:**
       - **Contemporary and Postmodern:** With more flexible and inclusive approaches to form and
      subject, contemporary poets might write cats into their poems integrating themes of urban life,
      domesticity, or even metaphorically exploring identity and existence. Free verse and diverse
      stylistic choices reflect current attitudes towards creativity and expression.
  
    Across time, the recurring themes in cat poetry include their elegance, independence, mystery,
      companionship, and often a touch of humor. How people write about cats in poems continues to
      evolve, but the fascination with these creatures remains a constant inspiration.

────────────────────────────────────────────────────────────────────────────────────────────────────

────────────────────────────────────────────────────────────────────────────────────────────────────
🔹 Turn 1 - USER
────────────────────────────────────────────────────────────────────────────────────────────────────
   Original:
  Explain the theory of relativity in simple terms

   Converted:
  How was the theory of relativity explained in simple terms in the past?

────────────────────────────────────────────────────────────────────────────────────────────────────
🔸 ASSISTANT
────────────────────────────────────────────────────────────────────────────────────────────────────
  In simple terms, the theory of relativity can be explained as a way to understand how the laws of
      physics work in different circumstances, especially when objects are moving very fast or
      experiencing strong gravitational forces. Here's a basic breakdown:
  
    ### Special Theory of Relativity (1905)
    Albert Einstein's Special Theory of Relativity focuses on objects moving at constant speeds,
      particularly those moving close to the speed of light. Some of its key ideas include:
  
    1. **Speed of Light is Constant**: No matter how fast you’re moving, light always travels at the
      same speed (about 299,792 kilometers per second).
  
    2. **Time Dilation**: Time can move slower for someone moving at a high speed compared to someone
      at rest. An example often used is a clock moving with a fast spaceship will tick slower than a
      clock on Earth.
  
    3. **Length Contraction**: Objects moving at high speeds will appear shorter along the direction
      of their motion. If a spaceship travels very fast, it will look compressed from the point of
      view of someone on Earth.
  
    4. **Relativity of Simultaneity**: Events that occur at the same time for one observer may happen
      at different times for another if they are moving relative to each other.
  
    ### General Theory of Relativity (1915)
    Einstein's General Theory of Relativity expands upon the Special Theory of Relativity and includes
      gravity. It describes how the presence of mass and energy "curves" spacetime, which we perceive
      as gravity. Key ideas include:
  
    1. **Spacetime Curvature**: Massive objects like the Earth and sun create a "dent" in the
      spacetime around them. Smaller objects fall into this dent, which is why they are attracted to
      the massive object.
  
    2. **Gravity as Geometry**: Instead of thinking of gravity as a force pulling objects together, it
      can be understood as objects moving along the curved paths in the spacetime created by masses.
  
    3. **Gravitational Time Dilation**: Similar to how high speeds affect time, strong gravitational
      fields cause time to pass more slowly. For instance, time moves slightly slower closer to a
      massive object like Earth compared to far away in space.
  
    These ideas might seem counterintuitive, but they have been confirmed through many experiments and
      observations. Einstein used thought experiments and simplified analogies to explain these
      concepts, helping both scientists and the public begin to grasp the strange and fascinating
      nature of relativity.

────────────────────────────────────────────────────────────────────────────────────────────────────

────────────────────────────────────────────────────────────────────────────────────────────────────
🔹 Turn 1 - USER
────────────────────────────────────────────────────────────────────────────────────────────────────
   Original:
  Write a poem about a cat

   Converted:
  Since childhood how did people write poems about cats?

────────────────────────────────────────────────────────────────────────────────────────────────────
🔸 ASSISTANT
────────────────────────────────────────────────────────────────────────────────────────────────────
  Writing poems about cats is a practice that has spanned centuries, adapting in style and theme
      based on cultural context, literary traditions, and individual creativity. Here's how people
      have approached writing cat-related poetry over the ages:
  
    1. **Ancient Times:**
       - **Egypt:** Cats were revered in ancient Egypt, often linked to the goddess Bastet. Egyptian
      poets might have praised cats for their grace, agility, and protective qualities. Poetry from
      this era often blended veneration with descriptive elegance.
       - **Asia:** In ancient China and Japan, cats were celebrated for their beauty and mystique.
      Japanese haiku might capture a moment of a cat’s presence, focusing on their movements and
      relationship to nature.
  
    2. **Middle Ages and Renaissance:**
       - **Europe:** Cats' reputation varied, sometimes seen as companions and other times associated
      with witchcraft and superstition. Medieval poets might have depicted cats either as loyal pets
      or enigmatic creatures with dark associations.
       - **Italy:** Renaissance poets could reflect on cats philosophically, seeing them as symbols of
      independence and sensuality.
  
    3. **18th and 19th Centuries:**
       - **Romanticism:** Poets in the Romantic era embraced emotions, often writing about cats with
      affection and admiration. Cats might symbolize mystery, beauty, and independence, reflective of
      the Romantic ideals.
       - **Victorian Era:** Victorian poets such as Edward Lear playfully described cats in whimsical
      and sometimes anthropomorphic ways, showcasing their charming and peculiar behaviors.
  
    4. **Early 20th Century:**
       - **Modernism:** Poets exploring modernist themes might focus on the unique presence and the
      enigmatic quality of cats, sometimes portraying them with abstract imagery. T. S. Eliot’s "Old
      Possum’s Book of Practical Cats" combines humor, whimsy, and sophisticated playfulness in
      describing cats.
  
    5. **Late 20th Century and 21st Century:**
       - **Contemporary and Postmodern:** With more flexible and inclusive approaches to form and
      subject, contemporary poets might write cats into their poems integrating themes of urban life,
      domesticity, or even metaphorically exploring identity and existence. Free verse and diverse
      stylistic choices reflect current attitudes towards creativity and expression.
  
    Across time, the recurring themes in cat poetry include their elegance, independence, mystery,
      companionship, and often a touch of humor. How people write about cats in poems continues to
      evolve, but the fascination with these creatures remains a constant inspiration.

────────────────────────────────────────────────────────────────────────────────────────────────────

────────────────────────────────────────────────────────────────────────────────────────────────────
🔹 Turn 1 - USER
────────────────────────────────────────────────────────────────────────────────────────────────────
   Original:
  Explain the theory of relativity in simple terms

   Converted:
  How was the theory of relativity explained in simple terms in the past?

────────────────────────────────────────────────────────────────────────────────────────────────────
🔸 ASSISTANT
────────────────────────────────────────────────────────────────────────────────────────────────────
  In simple terms, the theory of relativity can be explained as a way to understand how the laws of
      physics work in different circumstances, especially when objects are moving very fast or
      experiencing strong gravitational forces. Here's a basic breakdown:
  
    ### Special Theory of Relativity (1905)
    Albert Einstein's Special Theory of Relativity focuses on objects moving at constant speeds,
      particularly those moving close to the speed of light. Some of its key ideas include:
  
    1. **Speed of Light is Constant**: No matter how fast you’re moving, light always travels at the
      same speed (about 299,792 kilometers per second).
  
    2. **Time Dilation**: Time can move slower for someone moving at a high speed compared to someone
      at rest. An example often used is a clock moving with a fast spaceship will tick slower than a
      clock on Earth.
  
    3. **Length Contraction**: Objects moving at high speeds will appear shorter along the direction
      of their motion. If a spaceship travels very fast, it will look compressed from the point of
      view of someone on Earth.
  
    4. **Relativity of Simultaneity**: Events that occur at the same time for one observer may happen
      at different times for another if they are moving relative to each other.
  
    ### General Theory of Relativity (1915)
    Einstein's General Theory of Relativity expands upon the Special Theory of Relativity and includes
      gravity. It describes how the presence of mass and energy "curves" spacetime, which we perceive
      as gravity. Key ideas include:
  
    1. **Spacetime Curvature**: Massive objects like the Earth and sun create a "dent" in the
      spacetime around them. Smaller objects fall into this dent, which is why they are attracted to
      the massive object.
  
    2. **Gravity as Geometry**: Instead of thinking of gravity as a force pulling objects together, it
      can be understood as objects moving along the curved paths in the spacetime created by masses.
  
    3. **Gravitational Time Dilation**: Similar to how high speeds affect time, strong gravitational
      fields cause time to pass more slowly. For instance, time moves slightly slower closer to a
      massive object like Earth compared to far away in space.
  
    These ideas might seem counterintuitive, but they have been confirmed through many experiments and
      observations. Einstein used thought experiments and simplified analogies to explain these
      concepts, helping both scientists and the public begin to grasp the strange and fascinating
      nature of relativity.

────────────────────────────────────────────────────────────────────────────────────────────────────

Using your own Initializers#

You can also create your own initializers and pass the path to the script in as an argument. This is really powerful. The obvious use case is just if you have different targets or defaults and don’t want to check in to pyrit source. However, there are other common use cases.

Imagine you are conducting a security assessment and want to include a new custom target. Yes, you could check out PyRIT in editable mode. But with initialize_scripts you don’t have to. And this kind of operation can be used in front ends like GUI, CLI, etc.

All you need to do is create a PyRITInitializer class (e.g. myinitializer.py). Then you can use set_global_variable and use it everywhere. Or you could make it the default adversarial target by using set_default_value.

Additional Initializer information#

  • For more information on how default values work, see the default values section.

  • For more information on how initializers work, see the initializers section