How the PyRIT insecure code scorer rates generated code for risk
A team testing a coding assistant or code-writing agent often has a stream of generated snippets that nobody reviews line by line. PyRIT's InsecureCodeScorer rates how risky a code snippet is, flagging vulnerabilities such as injection or weak authentication. In a PyRIT run, the scorer sits after the target returns its response. The attack sends a prompt to the coding assistant, the assistant returns code, and the scorer evaluates that returned code as a float-scale scorer, which means it produces a graded numeric rating rather than a simple yes or no verdict. The rating is then stored with the conversation in PyRIT memory, so the result can be reviewed alongside the prompt that produced it.
The decision to add this scorer depends on what the assistant is expected to produce. A general harm scorer asks whether a response is harmful content, such as hate, violence or dangerous instructions. That question misses a snippet that is perfectly polite and well formatted but builds a SQL query by concatenating user input or stores a password in plain text. A team whose assistant writes application code, infrastructure definitions or scripts needs a scorer aimed at security weaknesses in code. A team whose assistant only answers conversational questions may not need it at all. Teams should confirm in the current PyRIT documentation how the InsecureCodeScorer is configured and what its float output range means before setting pass or fail thresholds.
Configuration options and when each fits
This table compares the four choices a team makes when wiring PyRIT's insecure code scorer: the judge model, the chat target that performs scoring, the category wording, and the pass or fail cut-off. Read each row as a decision with a trade-off, then confirm exact parameter names against the PyRIT 1.1.0 documentation before you write configuration. The main takeaway is that the judge and the cut-off determine most of how trustworthy your verdicts are.
| Decision | Options and when each fits | Trade-off to weigh |
|---|---|---|
| Judge model | A stronger hosted model suits broad code review across many languages and frameworks. | Higher cost per snippet and a dependency on an external provider's data handling terms. |
| Judge model | A smaller or self-hosted model suits high volume scans of code that cannot leave your network. | Lower accuracy on subtle injection or authentication flaws, so calibrate it against reviewed samples. |
| Scoring chat target | A dedicated scoring endpoint separate from the system under test keeps judge traffic and logs apart. | Needs its own credentials, rate limits and memory records to set up and maintain. |
| Scoring chat target | Reusing the target under test as judge is simpler to configure for a quick check. | A model can be biased toward its own output, which weakens the verdict. |
| Category wording | Naming the vulnerability classes you care about, such as injection and weak authentication, suits policy-driven reviews. | Narrow wording misses flaws outside your list. Broad wording raises false positives. |
| Category wording | Language closer to your secure coding standard makes verdicts easier to map to findings. | Changing wording changes scores, so record the exact text used in each run. |
| Float score cut-off | A low threshold suits release gates where any risky pattern should block a merge for human review. | More snippets flagged, so reviewers spend more time on false positives. |
| Float score cut-off | A higher threshold suits triage of large generated-code samples where only severe patterns matter. | Moderate risks can pass unnoticed, so sample passed results periodically. |
Setting up the insecure code scorer in a PyRIT run
This sequence takes a team from a clean Python environment to a PyRIT run that scores generated code for injection and weak authentication. It ends with a calibration check that confirms the scorer ranks known-vulnerable snippets above known-safe ones before you trust it on your assistant's output.
Confirm a supported Python version
Check that the Python interpreter on the test workstation or runner falls within the range the PyPI package supports, which is Python 3.10 up to but not including 3.15. The PyRIT documentation recommends Python 3.13, so use that version if your environment allows it. Run the version check in a shell and record the output in your test notes. The step is done when the reported version is inside the supported range and matches the version you will use for every later run.
Install PyRIT from PyPI
Create an isolated virtual environment so PyRIT's dependencies do not collide with other tooling, then install the
pyritpackage from PyPI with pip. Pin the version you install and write it down, since scorer behavior and configuration can change between releases. Your platform engineering or AI security lead should own this environment. The step is done whenpip show pyritreports the pinned version and a Python import of the package succeeds inside the virtual environment.Configure credentials and settings
Put model endpoint keys and other secrets in
~/.pyrit/.env, and put non-secret run settings in~/.pyrit/.pyrit_conf. Keep the.envfile readable only by the account that runs the tests, and do not commit either file to source control. The scorer needs a judge model for its evaluation, so confirm which model and endpoint your team has approved for judging code. The step is done when a short test script loads the configuration without errors and the judge endpoint responds to a trivial request.Point a target at the coding assistant
Register the coding assistant or agent as a PyRIT target. Depending on how your system is exposed, this may be a built-in model target or a custom HTTP or WebSocket target. Confirm with your platform owner whether the assistant can be called without a human in the loop and whether it has tool access, because agents that execute code change the risk profile of the test. Send one benign coding request and confirm that the response text returns to PyRIT intact. The step is done when the target returns a code-bearing response that is stored in PyRIT memory.
Attach the InsecureCodeScorer
Create an
InsecureCodeScorerand attach it to the run so it evaluates each response the target returns. The PyRIT documentation describes this scorer as rating how risky a code snippet is, flagging vulnerabilities such as injection or weak authentication. Record the scorer class name and version in your run configuration so results can be reproduced later. The step is done when a single test prompt produces a stored score with a numeric value for the response, rather than an error or an empty result.Run known-vulnerable and known-safe snippets
Build a small calibration set of code snippets that your team already knows to be vulnerable, such as a SQL query built by string concatenation or a login check that compares passwords in plain text, alongside snippets known to be safe that use parameterized queries and hashed credentials. Send each snippet through the scorer, either directly or by asking the target to reproduce it, and keep the snippets and their labels in version control. The step is done when every snippet has a stored score and the labels are recorded next to it.
Check that scores separate the two groups
Compare the scores for the vulnerable and safe snippets. The scorer is working for your purposes only if the vulnerable snippets consistently score as riskier than the safe ones, and any overlap or misses are written down. If the scores do not separate, adjust the judge model or the snippet set and rerun before using the scorer on assistant output. Ask your scoring owner to review the calibration results before the scorer is used for pass or fail decisions. The step is done when the calibration report shows the separation, the known misses are documented, and the team agrees the scorer is fit for the next stage.
Security and operational risks when scoring generated code
Scoring generated code means handling untrusted output, a judge that can be wrong, and stored records that may hold secrets. The cards below cover the decisions that keep an insecure code scorer run safe, accurate and reviewable.
The scorer can be wrong
The insecure code scorer's verdict is a model judgment, so it can miss a real injection or weak authentication flaw and it can also over-flag safe code. Before you rely on a score for a release decision, run it against a small set of snippets your team has already labeled by hand, and record where it disagrees. Treat a high score as a reason to review the code, not as proof that the code is exploitable.
Generated code is untrusted input
Code produced by a model during a red team run must never be executed by the scorer, the test harness or the CI pipeline that calls it. Keep the scoring step to reading text: do not import, compile, run or auto-install anything from the snippet. If a follow-up test needs to run the code, do it in a separate, isolated sandbox with no access to production credentials or networks.
Stored conversations may hold sensitive code
PyRIT memory keeps prompts, model responses and scores in SQLite or Azure SQL, so generated snippets can end up in a database file that many people can copy. Generated code may also echo secrets from the prompt or from example configurations. Set file permissions and database access rules before the first run, and decide who can read exported conversations.
Protect credentials in the environment file
PyRIT reads credentials from ~/.pyrit/.env, so any user or service account that runs the scorer can read the model and cloud keys stored there. Restrict the file to the owning account, keep it out of version control and shared CI images, and use a separate, least-privilege key for scoring runs. Rotate the key if the file is copied to a workstation that leaves your control.
Report PyRIT vulnerabilities privately
If your testing reveals a flaw in PyRIT itself, such as a parsing issue that mishandles hostile output, report it privately through the Microsoft Security Response Center under the project's security policy rather than opening a public issue. Keep the report focused on reproduction steps and avoid including live credentials or real customer code. Confirm the current reporting path in the project's README before you rely on it.
Keep scoring results in memory
Store each insecure code score with its snippet reference, scorer version, judge model and timestamp, so a reviewer can trace why a finding was raised. Without that record, a score cannot be reproduced after a model or prompt change. Decide how long results are kept, who can query them and how they are removed when a retention period ends.
What a risk score can and cannot show about code
A float score from the insecure code scorer is a model's judgment about one snippet, not a static analysis result and not proof that the code can be exploited. The scorer sends the generated code to a judge and returns a risk rating on a float scale, so the number reflects how the judge read the text in front of it. It does not trace data flow across files, know which inputs reach the function in production, or confirm that an attacker can reach the code path. A high score is a reason to look closer and open a finding for triage. A low score is not a clean bill of health, because the judge can miss flaws that depend on context outside the snippet. Before your team acts on any threshold, confirm in the PyRIT documentation exactly which vulnerability classes the scorer is prompted to flag, since the page only confirms injection and weak authentication as examples.
Single-snippet scores are weak evidence on their own. Model output varies between runs, the same snippet can score differently under a different judge model or prompt, and a handful of prompts tells you little about how a coding assistant behaves across a whole project. Treat the scorer as a way to rank and prioritize generated code for review, and record the judge model, prompt version and scorer settings alongside each score so a result can be reproduced. Calibrate a threshold against code your team has already reviewed by hand before you let scores gate anything.
The scorer belongs next to, not in place of, static application security testing, dependency scanning and human code review. SAST tools analyze code paths deterministically and can show the source and sink of a flaw, dependency scanners check the libraries an assistant pulls in, and reviewers understand the business context that no scorer sees. Position the insecure code scorer as one signal in a pipeline that tests what a coding assistant produces, and define in advance which findings from each layer block a merge and which go to a backlog.
How a generated snippet moves through PyRIT to a score
The run starts with an attack objective and prompt sent to the coding assistant target. The code that comes back is untrusted output, so it crosses a trust boundary before PyRIT stores it in memory. The InsecureCodeScorer then evaluates the snippet and returns a float score with a rationale to the operator and the results store. Check the boundary first: the scorer judges the code text it receives, not whether the code runs or is exploitable.
Generated code passes from the target through memory into the InsecureCodeScorer, which returns a score and rationale.
Limits to confirm in your environment before relying on scores
The insecure code scorer gives a risk rating, not a security audit, and its verdicts depend on the classes it targets, the languages you ship, the judge behind it and the PyRIT version you pin. The cards below cover what to confirm before any score drives a release or triage decision.
Vulnerability classes the scorer targets
The scorer is documented to flag risks such as injection and weak authentication, but a coding assistant can introduce many other weaknesses, including path traversal, unsafe deserialization, hardcoded secrets and broken access control. List the classes your product must catch, then test a snippet for each one. Anything outside the documented focus should be treated as unscored until you have evidence otherwise.
Float-scale scorer docsBehavior across your languages and frameworks
A rating that looks sensible on a Python snippet may say little about Go, Java, TypeScript or the web framework your team uses. Ask which languages and frameworks you need covered, then run a set of snippets from each stack and record where the ratings fall apart. Frameworks that handle escaping or authentication by default can produce code that looks risky to the scorer but is safe in practice.
False positive and false negative rates
Measure the error rates on your own labeled snippets before relying on the scorer. Label a set of generated code samples as vulnerable or safe with a security reviewer, run the scorer on the same set, and count missed vulnerabilities and wrongly flagged safe code separately. A low false negative rate matters most for release gates, while the false positive rate determines how much review time the scorer adds.
Judge model that scores the code
The scorer relies on a language model to judge the snippet, so the model you choose sets the verdicts you get. Record the model name, version and provider in your test plan, and rerun your labeled set whenever the model changes. Confirm how your team's data policy applies when proprietary source code is sent to that judge, especially if the model is hosted by a third party.
Cost and rate limits of repeated scoring
Every score is a model call, so a scan of a full coding assistant's output in CI adds recurring token charges and can hit provider rate limits. Ask your provider for current pricing and per-minute limits, then estimate call volume from your sample sizes and retry settings. Scoring can run asynchronously or be restricted to changed files to keep both cost and latency under control.
Pinned PyRIT version after upgrades
Scorer behavior and its configuration can change between releases, and the PyRIT 1.1 line includes scoring changes. Pin the exact version in your environment, record the behavior you validated, and rerun your labeled set after every upgrade, including the move to 1.1.0 or later. Keep the pinned version and results together so an auditor can tie a verdict to the scorer that produced it.
PyRIT releasesQuestions teams ask about scoring generated code
Can our own team run PyRIT's insecure code scorer without outside help?
Yes, if you have engineers comfortable with Python, a model endpoint for the scorer to call, and time to build a test set. PyRIT is an open-source framework under the MIT license, installed with pip, and its scorers are configured in Python. The hard part is rarely the install. It is deciding what counts as a risky snippet for your stack, wiring the scorer to a judge model you trust, and proving the verdicts match what your security engineers would say. A team that has done this before, or that has a clear owner for the scoring rubric, can usually run it internally. Teams without a security engineer on the work often benefit from a short advisory engagement to set the rubric and validation plan before they scale it.
How much effort do setup and validation take, and what drives it?
Effort is driven less by installation than by the work around it. The main drivers are the number and variety of languages and frameworks your assistants produce, how many vulnerability classes you want flagged, how precisely you need to define injection and weak authentication for your codebase, and how much validation you require before results are trusted. Setup covers the environment file and configuration, the judge model connection and the memory store, and the scorer's prompt and output handling. Validation covers a labeled set of snippets reviewed by people, then comparing scorer verdicts against those labels. No duration is fixed by the product, so ask any partner for a written breakdown of these phases and what each one assumes about your environment before you agree on scope.
Does the insecure code scorer replace code review or SAST?
No. The scorer rates how risky a model-generated snippet looks, using a language model as the judgment layer, so it complements code review and static application security testing (SAST) rather than substituting for them. A SAST tool applies deterministic rules to your code base and produces traceable findings, while the PyRIT scorer produces a graded estimate for a single snippet that you can use to compare model versions, prompts or agent configurations. Use it to catch regressions and to triage large volumes of generated output, then keep your normal review and scanning gates for code that reaches production. Anything that informs a release decision should still be checked by a qualified engineer.
How do we measure whether the scorer's verdicts can be trusted?
Measure it against human labels before relying on it. Build a representative set of generated snippets, have two or more reviewers label each one for injection, weak authentication and other risks you care about, then run the scorer on the same snippets and compare results. Track agreement with the labels, look closely at false negatives on high-severity patterns, and record the result for each judge model and prompt version you use, because changing either can shift scores. PyRIT provides scorer metrics for comparing verdicts with human labels and for measuring agreement between raters, which lets you set a documented acceptance threshold. Re-run the comparison whenever the model, prompt or code languages change.
What inputs does the work need from our team?
The work needs three things from your side. First, a test snippet set that reflects the code your assistants actually generate, including languages, frameworks, and examples of both safe and unsafe patterns that your reviewers have already seen. Second, a judge model: a language model endpoint the scorer can call, with a clear data handling position, since the code you send to it may be sensitive. Third, memory storage, because PyRIT keeps conversations and results in SQLite or Azure SQL, and those records become your audit trail. Ask where that storage lives, who can read it, how long it is kept and how it is backed up before any scan touches production code.
When should we bring in outside help for scoring generated code?
Bring in outside help when the scorer's verdicts will influence decisions that carry real consequences, such as approving an agent for write access to repositories, or when the scoring has to stand up in a customer or regulator review. Outside help is also useful when your team lacks a security engineer to write the rubric, when the labeled validation set is too large to produce internally, or when the judge model choice must be defended in writing. DeployOpen plans, tests and documents self-hosted setups in your own infrastructure, runs security testing for AI systems and agents, and prepares evidence for compliance assessments, though it does not issue audit reports. Ask for a written scope with deliverables before work starts.
Pairing the code scorer with the rest of your PyRIT scoring
The insecure code scorer answers one question: how risky is this snippet of generated code? It does not answer whether the response broke your acceptance policy, and a team that treats its verdict as a policy verdict will miss failures. Pair it with a second scorer that encodes your rules. An LLM judge built on a true/false question can check whether the response met the objective your policy defines, such as whether the assistant produced a login handler that skips password verification. Use the code risk score for the technical finding and the judge verdict for the policy decision, and record both on the same conversation so a reviewer sees them together.
Composite scoring is where the two verdicts meet. Combine them with an AND composite when a response should fail only if it is both risky code and in scope for your policy, or with an OR composite when either signal alone should block a release. Threshold scorers let you turn the float score from the code scorer into pass or fail at a level your security team agrees on, which is a decision to make before the first run, not after. Confirm in the PyRIT version you deploy how composite and threshold scorers accept float outputs, since the exact wiring should be tested against your own sample responses.
Once the pairing is in place, the next question is how much to trust it. The insecure code scorer is itself a language model judging code, so its verdicts can disagree with a reviewer on borderline snippets. Measuring scorer accuracy with scorer metrics compares scorer output against human labels and shows where the scorer over- or under-flags. Run that check on a labeled set drawn from your own coding assistant before you rely on the combined verdict in a gate. The PyRIT documentation is the reference for confirming the scorer classes available in your version.
How DeployOpen scopes and delivers PyRIT code scoring
DeployOpen plans and runs PyRIT-based testing inside your own infrastructure, then reports what the insecure code scorer found and how to fix it. The cards below describe what a written scope covers, who does what, and what you receive before any work starts.
Written scope before any build
Most engagements are fixed-scope, so the coding assistants, agents, repositories and languages to test are agreed in writing before work begins. The scope names which code-generation paths are in and which are out, such as IDE completions, agent pull requests or CI-generated scripts. A quote follows from that written scope, so unclear boundaries are the main driver of cost to resolve early.
PyRIT deployed in your environment
DeployOpen plans and implements the PyRIT setup in the cloud accounts, data centers or air-gapped networks you control. That includes the model endpoints the insecure code scorer calls, credential handling, and where PyRIT memory stores scored code. Confirm which judge model you can reach from that network, because the scorer depends on it.
Float-scale scorer docsAI and agent security testing
The testing covers the coding assistant or agent as deployed, including its prompts, tools, file access and the code it writes. The insecure code scorer rates generated snippets for issues such as injection and weak authentication, and the test checks whether those ratings hold on the code your team actually accepts. Human review still decides which flagged findings are real.
Findings with fixes and retest
Each finding is written up with the code pattern, the rating the scorer gave, the reproduction steps and a suggested fix, such as parameterized queries or stronger session handling. After fixes are applied, DeployOpen retests the same prompts and scorer settings so you can compare before and after. Ask for the report format and the retest scope in the written agreement.
No audit reports or certifications
DeployOpen prepares test records and evidence, but it does not issue audit reports, attestations or certifications. Independent auditors and certification bodies make those determinations. If an assessor will review scorer results, confirm early which records they need and how the memory and run history will be exported.
Ongoing testing as a retainer
After the initial scope, code scoring can continue as a retainer that covers new coding tools, model upgrades and periodic reruns. Ongoing work is priced from its own written scope, so ask what is recurring, what changes the scope, and who maintains the scorer configuration over time.

