Red teaming attack with an adversarial LLM in PyRIT

PyRIT's adaptive multi-turn attacks use a second model to converse with your target toward an objective. This page covers how to set that up, which adversarial model to choose and host, and how to write the objective and scorer.

On this page

How a PyRIT red teaming attack with an adversarial LLM works

A single prompt test tells you whether a model refuses one request, not whether it holds up under sustained pressure. A PyRIT adaptive multi-turn attack addresses that gap by putting a second model in the attacker's seat. The adversarial model writes each message, reads the target's reply, and adjusts its next move toward an objective you define. The system under test is the objective target, the model or application you deploy. The scorer then reads the conversation and decides whether the objective was reached. Three roles, three configurations, and the team owns every one of them. Keep them separate in your test plan so a result can be traced back to the component that produced it.

In PyRIT's documentation, an adaptive multi-turn attack takes an objective_target for the system under test and an AttackAdversarialConfig that names the adversarial target. Read that pattern as two decisions. First, which model plays the attacker, and whether it is hosted in your environment or reached through an external service, which affects data handling. Second, whether the objective target is a stateful chat endpoint or a stateless one, since that changes how the conversation history is carried between turns. Confirm both against the PyRIT multi-turn attack documentation before you write the harness, because the parameter names and supported target types are the source of truth.

This attack costs more than single-turn testing because every objective needs several model calls for the attacker, the target and the scorer, and those calls repeat across turns. Use it when the risk depends on conversation, such as gradual escalation, persona drift or context accumulated over a session. For a quick check of a single known prompt or a broad refusal sweep, a single-turn attack is usually the better first pass. Ask any partner or internal team to estimate model calls per objective and to show how the turn limit changes that figure, so the budget reflects your own deployment rather than a general rule.

The attack loop between adversarial model, target, and scorer

The loop starts when PyRIT's attack component asks the adversarial model for the next prompt toward the objective. That prompt goes to the objective target, whose response is passed to the scorer, and PyRIT memory records every turn. The scorer's verdict decides whether the loop continues or stops. Check the trust boundaries: the adversarial model and the target are separate endpoints, and the conversation history stored in memory is what each side sees next.

One attack loop: adversarial model, objective target, scorer and memory, with trust boundaries marked.

Configuration options and when each fits

This table compares the four choices that shape a RedTeamingAttack run: the objective target, the adversarial target named in AttackAdversarialConfig, the scorer, and the memory backend. Read each row as a decision: what the option is good for, and what it costs you in control, evidence or setup. The main takeaway is that the adversarial model and the scorer determine how much of the result you can trust, so they deserve the most review time.

ChoiceWhen it fitsTrade-off to weigh
Objective target: hosted commercial modelYou are testing the model your product calls and need the endpoint to match production behaviorEach conversation sends data to a provider you may not control, and provider-side filters can change results between runs
Objective target: custom HTTP or WebSocket appYou are testing the full application, including system prompt, retrieval and output filtersAuthentication, session handling and stateful conversation must be wired correctly or results will not reflect real use
Objective target: self-hosted modelYou need to keep test traffic inside your network or test a model you serve yourselfResults describe the model alone, not the guardrails and wrappers users reach in production
Adversarial target: a model separate from the objectiveYou want an attacker model that is not the one under test, so refusals are not shared between the twoYou must host or pay for a second model, and its capability limits how hard the attack pushes
Adversarial target: the same model as the objectiveOnly as a quick smoke test when no other model is availableShared training or policy can make the attacker reluctant, which understates risk
Scorer: LLM-based judgeYou need a graded verdict on nuanced harms such as persuasion or policy violationsThe judge can be wrong, so measure its accuracy on labeled examples before relying on its scores
Scorer: Azure AI Content SafetyYou want a managed classifier with a fixed set of harm categories inside AzureIt covers categories it was built for, so harms outside those categories may score as passing
Scorer: custom logicThe success condition is objective, such as a string, a tool call or a leaked valueSimple rules miss paraphrased or partial leaks, so pair them with a judge where meaning matters
Memory: SQLiteA single analyst or a local proof of concept where data stays on one machineLimited suited to shared team access, and you must handle backup and retention yourself
Memory: Azure SQLSeveral testers need shared history and results in an Azure environment you governRequires Azure setup, access control and cost planning, and conversation data must be handled under your data policies

Setting up the attack step by step

This sequence takes a team from a clean Python environment to a first RedTeamingAttack run against a target they control. Each step ends with a check so that a failure is caught at the point where it is introduced.

  1. Install PyRIT on a supported Python version

    Create a virtual environment and install the pyrit package with pip. The PyPI package supports Python 3.10 up to but not including 3.15, and the PyRIT documentation recommends Python 3.13, so use 3.13 unless your platform team has a reason to pin something else. Run the installer inside the environment your red team will use, not in a shared system Python. Check is done when importing pyrit from a Python shell succeeds and the installed version matches the release your team has approved (the current release referenced in the project's releases page is v1.1.0).

  2. Configure credentials in the PyRIT environment file

    Create ~/.pyrit/.env and add the API keys or endpoint credentials for the objective target and the adversarial target. Keep this file out of version control and restrict its file permissions to the account that runs the tests. If your organization stores secrets in a vault, confirm with your platform team how values will be loaded into this file before you start, since the file is the single place PyRIT reads credentials from. Check is done when a minimal call to each model endpoint returns a response from a non-scripted prompt.

  3. Set memory and defaults in the PyRIT configuration file

    Create ~/.pyrit/.pyrit_conf to set the settings PyRIT reads at startup, including the memory backend. PyRIT stores conversations and results in SQLite or Azure SQL, so choose the store before the first run because results are kept with the attack that produced them. Use a dedicated database path for this test set so that results from other projects do not mix with the evidence for this assessment. Check is done when a test prompt appears in the memory store after a run and can be queried back.

  4. Define the objective target and the adversarial target

    Decide which system is under test and which model will generate attack turns. The objective target is the application or model you are testing. The adversarial target is a separate model that PyRIT uses to write the attacker messages. In your script, pass the objective target as objective_target and name the adversarial model in AttackAdversarialConfig, as described in the PyRIT multi-turn attack documentation. Confirm that the adversarial model is approved for generating harmful test content under your acceptable use terms. Check is done when both targets resolve to working endpoints and a single prompt sent to each returns a response.

  5. Write the attack objective

    Write a single, testable objective that describes what a successful attack looks like on the target, such as a specific policy-violating output or disclosure. The adversarial model uses this objective to steer every turn, so vague goals produce unfocused conversations and results that are hard to interpret. Have a security owner review the wording against the harm categories your organization has agreed to test. Check is done when someone who did not write the objective can state what success would look like and why it matters.

  6. Attach a scorer that judges each response

    Attach a scorer to the attack so that every target response is evaluated against the objective. PyRIT scorers can use an LLM judge, Azure AI Content Safety or custom logic. Select the scorer type based on what the objective measures, and record which one you chose because the scorer determines what the attack result means. Run the scorer once against a known safe reply and a known unsafe reply that you write by hand, and confirm it labels them differently. Check is done when the scorer's verdicts match both examples.

  7. Run the first attack and review the transcript

    Create the RedTeamingAttack with the objective target, adversarial configuration, objective and scorer, then run it with a small turn limit for the first pass. Open the stored conversation and read each adversarial message and target reply, not just the final score. Confirm that the adversarial turns stay on the objective, that the target responses are recorded in full, and that the score attached to the result matches what you read. Check is done when the transcript, the stored result and the scorer verdict agree, and you have written down any setup changes needed before the next run.

Choosing and hosting the adversarial model

A cloud-hosted adversarial model is the fastest path when your organization already has an approved provider agreement. PyRIT includes targets for OpenAI, Azure, Anthropic, Google and Hugging Face models, so the attack configuration can use a supported target class instead of custom request handling. The main work is identity, egress and data handling rather than model plumbing.

  • Credentials: API keys or cloud identities belong in ~/.pyrit/.env on the runner or in a secrets store your team controls. Keep them out of notebooks and version control.
  • Network path: The runner needs outbound access to the provider endpoint. Confirm proxy and firewall rules before the first run.
  • Data handling: Adversarial prompts and target responses are sent to the provider. Confirm that the provider terms and your data classification permit harmful test content.
  • Usage cost: Multi-turn attacks call the adversarial model on every turn, so billing recurs with each run. Ask the provider for quotas and spending alerts.
  • Memory location: Conversations are stored in PyRIT memory (SQLite or Azure SQL), so decide where that database lives and who can read it.

Before you point the adversarial configuration at a hosted model, test whether it will generate attack prompts for your objectives, because provider safety behavior can refuse them.

Writing the objective and scorer that define success

The objective is the goal the adversarial model pursues against the target, and it defines what a success means before any conversation starts. A usable objective is specific and testable: it names the behavior being sought (for example, a step-by-step answer to a particular request, or disclosure of a system prompt's contents), so that a reviewer can read a transcript and agree whether the goal was met. Vague objectives such as "make the model unsafe" produce conversations that are hard to judge and results that cannot be repeated. In PyRIT's adaptive multi-turn attacks, the objective is passed alongside the objective_target and an AttackAdversarialConfig that names the adversarial target, so the objective text is the single instruction the adversarial model works from. Write it in the language your risk register uses, and keep one objective per run so that results can be traced back to a single harm.

The scorer decides whether the target's responses meet the objective, and it is the component most likely to make or break the result. PyRIT's documented scorer options are LLM-based scoring, Azure AI Content Safety and custom logic. An LLM judge handles nuanced objectives but inherits its own errors and biases, so the judge model and its scoring prompt should be recorded with the run. Azure AI Content Safety suits category-based harms but may not capture the exact behavior your objective describes. Custom logic, such as a pattern check for a leaked secret or a required refusal string, is deterministic and easy to audit, but it only catches what you anticipated. Many teams combine two of these and compare them. Confirm which scorers your PyRIT version supports, and which of them require Azure resources or additional model access, before you commit to one.

Before trusting any attack success rate, measure scorer accuracy against a labeled sample. Have a human reviewer label a set of target responses for the same objective, run the scorer over them, and record agreement and the kinds of errors it makes, especially false negatives that would report a weakness as absent. Repeat this check when you change the judge model, the scoring prompt or the objective wording, because each change can shift results. Ask the team that owns the scorer to state its known failure modes in writing. The output of this step is a short accuracy note that sits beside the run results, so a reviewer can see how much weight a "no success" finding can bear.

Security and operational considerations for live attacks

A red teaming attack with an adversarial model produces two sensitive assets: the credentials that reach the target and adversarial model, and the transcripts that record what the target said. The cards below cover what to protect, what to authorize and what to budget before an attack runs against a live system.

Credential handling in .env files

PyRIT reads credentials for targets and the adversarial model from ~/.pyrit/.env, so one file can grant access to several model endpoints at once. Keep the file out of version control, restrict its file permissions to the account running the tests, and use a separate key with a spending limit for each test environment. Confirm with your secrets team whether a central vault is required by policy before the file is created on a shared runner.

PyRIT docs

Harmful output stored in memory

PyRIT memory keeps full conversations, including the harmful content a target produced, in SQLite or Azure SQL. Treat the memory database as sensitive data: encrypt the storage, limit who can query it, and set a retention rule that deletes transcripts once findings are recorded. Ask whether your data classification policy permits storing such content and where the database may live.

Access controls on the adversarial endpoint

The adversarial model writes the attack prompts, so whoever can call that endpoint can steer it and read its outputs. Restrict network access to the runner, scope API keys to the minimum models needed, and log every request. Confirm that the provider's data handling terms cover the prompts and responses generated during red teaming.

Reporting PyRIT vulnerabilities privately

If testing reveals a flaw in PyRIT itself rather than in the target, do not open a public issue. Vulnerabilities in PyRIT are reported privately through the Microsoft Security Response Center under the project's security policy. Record the PyRIT version in use so the report can be reproduced, and check the project's release notes before relying on a version with known fixes.

PyRIT on GitHub

Rate limits and cost of repeated turns

Multi-turn attacks send the full conversation history with each turn, and every turn calls both the target and the adversarial model. A test that looks small can multiply token usage and hit provider rate limits mid-run. Set a turn limit and a request budget before the run starts, and ask your platform team who pays for the calls and whether quotas are shared with production.

Testing only authorized systems

An adversarial attack against a live endpoint can trigger alerts, degrade service or create records in the target's logs. Run tests only against systems your organization owns or has written authorization to test, and agree on the test window, the contact for stopping a run and the owner of the target. Keep the authorization with the test record so the findings can be traced to approved scope.

Questions teams ask before running adversarial LLM attacks

What drives the effort and cost of running a PyRIT red teaming attack?

The main drivers are the number of model calls per turn, the number of objectives, and the number of scorer calls. A RedTeamingAttack makes calls to three roles on each turn: the adversarial model that writes the next prompt, the target under test that replies, and the scorer that judges the reply. Each objective multiplies that loop, and a longer turn limit multiplies it again. Costs fall into two groups. Model and API usage is recurring and paid per run to whichever provider hosts the models. Engineering time to configure targets, write objectives and review results is largely one-time per program, with recurring effort for every rerun after the target changes. Ask any partner to show how their quote maps to objectives, turn limits, and the number of target configurations to be tested.

How long does setup usually take for a PyRIT red teaming attack?

Setup time depends mostly on how complex the target is to reach and authenticate against. A single OpenAI-compatible endpoint with a known API key is quick to connect. A custom HTTP or WebSocket application, or a web chat UI driven through Playwright, needs request mapping, session handling, and response parsing before the first attack runs. Hosting a self-managed adversarial model adds model serving, GPU capacity and network routing work. Writing good objectives and choosing a scorer that matches the harm also takes review time with the application owners. Teams should ask for a written setup checklist that names each target, the credentials it needs and the validation run that closes setup, rather than relying on a general duration.

What must our team provide before a PyRIT attack engagement starts?

Your team needs to provide four things before testing begins:

  • Target access: endpoints, API routes or a test deployment of the application, with a non-production environment where possible.
  • Credentials: scoped test accounts and API keys, stored in a secrets manager or in the ~/.pyrit/.env file on the test machine, never in source control.
  • An authorized scope: a written statement naming the systems, the harm categories, the time window and the people allowed to approve changes.
  • Contacts: an owner for the application who can answer questions about expected behavior and who will receive findings.

If the target sits behind your identity provider, confirm which accounts the tests may use and whether rate limits or logging will flag the traffic. Agree on these points in writing before any attack runs.

Can our in-house security team run PyRIT attacks without a partner?

Yes, a team with Python experience and access to the target can run PyRIT attacks in-house. PyRIT is an open-source framework from Microsoft under the MIT license, and it installs with pip on Python versions that the PyPI package supports. The harder part is judgment: deciding which objectives matter for your application, interpreting scorer results, and deciding when a finding is reproducible enough to report. Teams often start in-house for a first run and bring in outside help for scope design, complex target integration, or independent retesting. DeployOpen can plan and run this work, or support your team, under a written scope. Confirm your team's skills against the attack list in the pillar documentation before deciding.

How do we know whether a PyRIT attack success is meaningful?

A success is meaningful when it is reproducible, matches a defined objective, and is judged by a scorer you have checked. An automated scorer can flag a response that looks harmful, but scorers make mistakes in both directions, so review a sample of flagged and unflagged conversations by hand. Record the full conversation in PyRIT memory, the objective used, the adversarial model version, and the turn at which the target complied. Rerun the same objective several times, because adaptive attacks are not deterministic. A success also needs context: a reply that discloses an example of a harmful procedure matters more in a customer-facing application than in an internal test sandbox. Ask any partner how they validate scorer accuracy and how they separate one-off results from repeatable findings.

Does running adversarial LLM attacks create security or data risks?

Yes, the attack itself creates risks that need controls. Adversarial prompts can trigger harmful outputs, and those outputs are stored in memory, which means your test records may contain sensitive or harmful text. Credentials for the target and any hosted adversarial model must be scoped to test use and stored securely. Traffic can trigger rate limits, alerts, or account lockouts on production systems, so run against test environments first. Limit who can read memory, decide retention periods, and agree on how findings are disclosed. Vulnerabilities in PyRIT itself are reported privately through the Microsoft Security Response Center under the project's security policy.

Which parts of the attack are one-time work and which recur?

Target integration, scope agreement, objective writing and scorer selection are mostly one-time work for a given application. Model usage, scorer calls and result review recur with every run. Reruns become necessary after the target's model, system prompt, filters or application code change, and after a PyRIT upgrade that alters attack behavior. Plan for the recurring cost in the operating model, not only in the first engagement. Ask whether a quote includes reruns, the retest of fixed findings, and the time to update the target configuration when the application changes.

How DeployOpen scopes and delivers PyRIT red teaming

DeployOpen scopes PyRIT red teaming in writing before any work starts. The scope names the target systems, the harm categories to test, the adversarial model and where it runs, the attack strategies in use, and the evidence the client expects at the end. Because PyRIT's adaptive multi-turn attacks depend on an objective target and an adversarial target named in the configuration, the agreed scope fixes which endpoints are in play and who controls each one. DeployOpen configures PyRIT inside the client's own infrastructure, including its memory store, credential handling and network access to the target, so that conversations and results stay where the client's security team can review them.

Objectives and scorers are written with the client's security team, not guessed by the tester. The client owns the definition of a failure, such as which disclosures count as a leak or which policy breaches matter for their product, and DeployOpen turns those definitions into objective text and a scorer that the client can read and challenge. Before the full run, DeployOpen checks the scorer against a small set of responses the client has already labeled, so that disagreements are found early. Attacks are then run against the agreed target, and each run is recorded in PyRIT memory so that every finding can be traced back to its conversation.

Findings are delivered as a written report with reproduction steps, the affected conversations, severity against the agreed criteria, and recommended fixes such as system prompt changes, filter tuning or access restrictions. After the client applies fixes, DeployOpen reruns the affected attacks and reports what changed. DeployOpen prepares systems, controls and evidence for compliance assessments, but it does not issue audit reports, attestations or certifications. Independent auditors and certification bodies make those determinations, so the client should confirm with its auditor what red teaming evidence that auditor will accept.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.