Skip to content
AgenticAIWiki
  1. Learn
  2. Part 12
  3. 66. Governance and compliance
  4. 66.4

Lesson 66.4 · 4 of 7 · 6 min read · Reviewed 24 Nov 2026

Bias and fairness audits

By the end, you can

  • Plan a bias and fairness audit for an AI feature.
  • Run counterfactual tests and compare outcomes and error rates across groups.

A model can be accurate on average and still treat some people worse. A fairness audit looks for those gaps on purpose, measures them, and records what you did about them.

Start from the harm

Kind of harm Example What to measure
Allocation A screener passes fewer applicants from one group Selection rate per group
Quality of service A voice assistant misunderstands some accents more often Error rate per group
Representation Generated text links a job or trait to a gender or ethnicity Rate of stereotyped outputs

NIST’s work on AI bias stresses that bias is not only in data: it also comes from how a system is designed, deployed and used. So an audit looks at the whole feature, not just the model.

Measures that compare groups

Two common families:

  • Outcome parity: do groups receive the positive outcome at similar rates? A rough rule of thumb used in US employment selection, the four-fifths rule, flags concern when one group’s selection rate is below 80% of the highest group’s.
  • Error parity: are false positives and false negatives similar across groups? A screener that wrongly rejects qualified people from one group more often fails here even if overall pass rates match.

Worked example, illustrative numbers:

Group Applicants Passed Pass rate Qualified but rejected
A 500 200 40% 5%
B 400 120 30% 12%

Ratio of pass rates: 30 / 40 = 0.75, below the 0.8 rule of thumb. The error gap (12% against 5%) says the model, not only the applicant pool, is part of the cause. Both are findings to investigate.

These measures can conflict: when groups have different base rates, you usually cannot equalise every metric at once. Pick the measures that match the harm, and record why.

Counterfactual tests for LLMs

For text features you often don’t have group labels. Instead, make counterfactual pairs: identical inputs that differ only in a name, pronoun, dialect or age marker.

"Summarise this CV for a nursing role. Candidate: James Okafor, ..."
"Summarise this CV for a nursing role. Candidate: Maria Okafor, ..."

Then compare: the score given, the length and tone of the summary, the skillsSkill: A folder of instructions, scripts and resources that an agent loads when relevant to a task. mentioned. Run hundreds of pairs, not three, and count how often the outcome changes. Published benchmarks such as BBQ test question answering for social bias in a similar spirit, and toolkits such as Fairlearn compute group metrics for classifiers.

Running the audit

  1. Scope: which decisions, which groups, which harms. Involve people who know the affected users.
  2. Data: a labelled test set with enough examples per group to compare. Small groups need more care, because their rates are noisy.
  3. Measure: group metrics and counterfactual pairs, sliced like any evalEval: A repeatable test that measures how well an AI system performs on a set of cases with defined success criteria. (chapter 18).
  4. Act: change the prompt, data, model or process; often add a human review for borderline cases.
  5. Record: findings, decisions, trade-offs and owners, in a document you can show later.
  6. Repeat after model upgrades (72.4), prompt changes and on a schedule.

Common mistakes

  • Removing the protected attribute and declaring the system fair. Other fields (postcode, school, gaps in a CV) can stand in for it.
  • Reporting one metric that looks good and skipping the ones that don’t.
  • Auditing once at launch and never again.
  • Testing with three hand-picked examples.

This is engineering guidance, not legal advice. Anti-discrimination law differs by country and sector.

Key points

  • Start from the harm: unfair allocation (who gets a loan or an interview), worse quality of service for some groups, or stereotyped and demeaning content.
  • Compare outcomes and error rates per group; one overall accuracy number can hide a large gap.
  • For LLM features, counterfactual tests swap only a name, pronoun or dialect and check whether the answer changes.
  • Fairness metrics can conflict; choose the ones that match the harm, write down the trade-off, and repeat the audit after every major change.
Hands-on labRuns in the Playground

Measure group gaps and counterfactual flips

Compare pass rates and error rates per group, then find a hidden bias with name-swap pairs.

You will have: A small audit script that prints per-group rates, the pass-rate ratio and the counterfactual flip rate.

Steps

  1. Run the starter: one overall pass rate hides the groups.
  2. Write group_report() to give each group's pass rate and qualified-but-rejected rate.
  3. Read the pass-rate ratio against the 0.8 rule of thumb.
  4. Count counterfactual flips where only the first name changed.
  5. Write two sentences for the audit record: what you found and who should act.

Done when

  • Group A passes 40% and group B 30%, a ratio of 0.75.
  • Qualified applicants in group B are rejected more than twice as often (12% against 5%).
  • Counterfactual flips are above zero, so the name alone changes some decisions.

Open in the Playground No API key needed.

Starter code (Python)
# A small fairness audit: compare pass rates and errors per group, then run counterfactual name swaps.
import random

# Illustrative screening results, built from counts per group.
COUNTS = {  # group: (applicants, passed, qualified, qualified but rejected)
    "A": (500, 200, 200, 10),
    "B": (400, 120, 125, 15),
}
records = []
for g, (n, passed, qual, qual_rej) in COUNTS.items():
    unqual_passed = passed - (qual - qual_rej)
    rows = ([(True, True)] * (qual - qual_rej) + [(True, False)] * qual_rej
            + [(False, True)] * unqual_passed + [(False, False)] * (n - qual - unqual_passed))
    records += [{"group": g, "qualified": q, "passed": p} for q, p in rows]


def group_report(rows):
    # TODO 1: for each group return {"pass_rate": ..., "qualified_rejected": ...}
    # (qualified_rejected = share of qualified applicants in that group who did not pass)
    return {"all": {"pass_rate": sum(r["passed"] for r in rows) / len(rows), "qualified_rejected": 0.0}}


rep = group_report(records)
for g, m in rep.items():
    print(f"group {g}: pass rate {m['pass_rate']:.0%}, qualified but rejected {m['qualified_rejected']:.0%}")
ratio = min(m["pass_rate"] for m in rep.values()) / max(m["pass_rate"] for m in rep.values())
print(f"pass-rate ratio: {ratio:.2f}" + ("  flag: below the 0.8 rule of thumb" if ratio < 0.8 else ""))


# Counterfactual pairs: a stand-in screener scores two CVs that differ only in the first name.
def screener(cv):  # pretend this is your LLM step; it has a hidden bias you are trying to find
    score = 12 * len(cv["skills"]) + 4 * cv["years"]
    if cv["name"].startswith("Maria"):
        score -= 6
    return score >= 60


rng = random.Random(7)
SKILLS = ["triage", "wound care", "paediatrics", "ICU", "records", "medication"]
flips = 0
PAIRS = 200
for _ in range(PAIRS):
    base = {"skills": rng.sample(SKILLS, rng.randint(1, 5)), "years": rng.randint(0, 10)}
    a = screener({**base, "name": "James Okafor"})
    b = screener({**base, "name": "Maria Okafor"})
    # TODO 2: count the pair as a flip when the two decisions differ
print(f"counterfactual flips: {flips} of {PAIRS} pairs ({flips / PAIRS:.0%})")
Show a solution
# A small fairness audit: compare pass rates and errors per group, then run counterfactual name swaps.
import random

# Illustrative screening results, built from counts per group.
COUNTS = {  # group: (applicants, passed, qualified, qualified but rejected)
    "A": (500, 200, 200, 10),
    "B": (400, 120, 125, 15),
}
records = []
for g, (n, passed, qual, qual_rej) in COUNTS.items():
    unqual_passed = passed - (qual - qual_rej)
    rows = ([(True, True)] * (qual - qual_rej) + [(True, False)] * qual_rej
            + [(False, True)] * unqual_passed + [(False, False)] * (n - qual - unqual_passed))
    records += [{"group": g, "qualified": q, "passed": p} for q, p in rows]


def group_report(rows):
    out = {}
    for g in sorted({r["group"] for r in rows}):
        rs = [r for r in rows if r["group"] == g]
        q = [r for r in rs if r["qualified"]]
        out[g] = {"pass_rate": sum(r["passed"] for r in rs) / len(rs),
                  "qualified_rejected": sum(not r["passed"] for r in q) / len(q)}
    return out


rep = group_report(records)
for g, m in rep.items():
    print(f"group {g}: pass rate {m['pass_rate']:.0%}, qualified but rejected {m['qualified_rejected']:.0%}")
ratio = min(m["pass_rate"] for m in rep.values()) / max(m["pass_rate"] for m in rep.values())
print(f"pass-rate ratio: {ratio:.2f}" + ("  flag: below the 0.8 rule of thumb" if ratio < 0.8 else ""))


# Counterfactual pairs: a stand-in screener scores two CVs that differ only in the first name.
def screener(cv):  # pretend this is your LLM step; it has a hidden bias you are trying to find
    score = 12 * len(cv["skills"]) + 4 * cv["years"]
    if cv["name"].startswith("Maria"):
        score -= 6
    return score >= 60


rng = random.Random(7)
SKILLS = ["triage", "wound care", "paediatrics", "ICU", "records", "medication"]
flips = 0
PAIRS = 200
for _ in range(PAIRS):
    base = {"skills": rng.sample(SKILLS, rng.randint(1, 5)), "years": rng.randint(0, 10)}
    a = screener({**base, "name": "James Okafor"})
    b = screener({**base, "name": "Maria Okafor"})
    flips += a != b
print(f"counterfactual flips: {flips} of {PAIRS} pairs ({flips / PAIRS:.0%})")
Quick checkAn LLM screens job applications. Overall accuracy against human reviewers is 92%. What should the fairness audit check next?
How sure are you?
Pick an answer and how sure you are