Using classifier and moderation assertions in promptfoo

Add Hugging Face classifiers and moderation APIs to promptfoo tests to check LLM outputs for toxicity, bias and PII, and decide when a classifier is cheaper than a model grader.

On this page

When promptfoo classifier and moderation assertions catch output problems

When an LLM feature is about to ship, the team needs checks on outputs that run the same way on every build, not a reviewer reading samples by hand. Classifier assertions and moderation assertions are the promptfoo tools for this. A classifier assertion runs a Hugging Face classifier over each model output and compares its label or score against a threshold you set, covering sentiment, toxicity, bias, PII detection and custom labels you define. A moderation assertion sends the output to a moderation API that flags harmful content. Both produce a pass or fail for each test case, so they fit into the same eval run as your other assertions. Teams usually need them when outputs reach customers unreviewed, when the feature handles personal data, or when a compliance or risk reviewer asks how output safety is measured.

Before you write any assertion, decide which failure matters for the feature and which label set matches it. A toxicity classifier tuned for general web text may score domain language differently from your users' messages, so run a small set of known-good and known-bad outputs through the classifier first and check where it draws the line. For PII, confirm which entity types the detector covers and whether it runs on the output text alone or also needs the prompt for context. For moderation, confirm which provider and categories your chosen API supports, what it costs per call, and whether your data may leave your environment. Record these answers in the eval config so the reviewer can see what was tested and with which model.

Classifier and moderation checks are usually cheaper and more stable than a model grader because they return the same answer for the same text, and a local Hugging Face model adds no per-call charge beyond compute. A model grader is still needed when the check depends on meaning, such as whether an answer is correct or follows a policy. The cost split changes with the choice: a hosted moderation API bills per request, so the run cost grows with the number of test cases, while a self-hosted classifier shifts cost to the machines that run it. Ask the team who will operate that infrastructure and what each eval run will cost before you commit. Expect to revisit thresholds after the first few runs, since borderline outputs will show where a classifier is too strict or too loose.

Classifier, moderation or model grader: choosing the check

Classifier assertions run a Hugging Face classifier over the model output and compare its predicted label or score against a threshold you set. The check measures one narrow property that the classifier was trained to recognize, such as toxicity, bias, sentiment, PII presence or a custom label set. Because the classifier is a fixed model, the same output gets the same verdict on every run, and the check does not spend tokens on a judge model. It needs the classifier model to be downloadable or reachable from your run environment, and it needs enough compute to load that model. Its judgment is weakest outside the training distribution: a toxicity model trained on one kind of text may miss coded insults, and a PII model may miss identifiers in formats it has not seen.

  • What it checks: one property from the classifier's label set, returned as a label or score.
  • What it needs: a Hugging Face model reference, the supported label names and a run environment able to load the model.
  • Where it is weak: domain shift, sarcasm, non-English text and labels that do not match your policy definition.
  • Cost profile: no per-call API fee for the judge, but compute and model download time are real costs.
  • Stability: deterministic for a given model version, which makes regressions easier to attribute.

Before relying on a classifier, confirm the supported models, label sets and provider requirements in the promptfoo classifier documentation.

Configuration options and when each fits

This table compares the main settings for classifier and moderation assertions, with the situations where each one fits. Read it as a starting map: confirm exact key names and defaults against the promptfoo docs for the version you install, because both change between releases. The main takeaway is that a classifier scores one property of an output, while a moderation check asks a moderation service to flag harmful content, so the two rarely substitute for each other.

SettingWhat it controlsWhen it fits
Assertion type (classifier)Runs a Hugging Face classifier on the output and checks its label or scoreScoring one measurable property such as toxicity, sentiment or bias on many outputs
Assertion type (moderation)Sends the output to a moderation API and checks the returned flagsBlocking or flagging harmful content categories when a provider's moderation service is already in your stack
Hugging Face modelThe classifier model that scores the outputChoose a model whose training data and label set match your language and risk category, then confirm its license and hosting terms
Expected label or classThe label the output must receive, or must not receivePass when a label is absent for unsafe-content checks, or present for a required tone or class
ThresholdThe score cut-off that separates a pass from a failTune on a labeled sample of your own outputs, since the default may not match your tolerance for false positives
Moderation providerThe service the moderation check callsPick the provider that covers the categories you test, and confirm its data handling, region and rate limits before sending production text
Custom labelsClassifier labels defined for your own categoriesUse when none of the built-in categories match, such as a policy category specific to your product
Model selection and runtimeWhere the classifier runs, locally or through a hosted endpointLocal runs keep text inside your environment, but you carry the compute and model-update work

How to add a classifier or moderation check to a promptfoo test

This sequence takes a team from a clean promptfoo install to a working eval that flags toxic, biased or PII-containing outputs, and proves the check catches a known bad case before anyone trusts it.

  1. Confirm Node.js and install promptfoo

    Check that Node.js is version 22.22.0 or newer, since the current npm release of promptfoo (0.124.1) requires it. Install promptfoo globally or into the project with npm, then run the version command to confirm the CLI resolves. The step is done when the version command prints 0.124.1 or the release you intentionally pinned. If the version differs, record which release your team is standardizing on before writing tests.

  2. Create a config with a baseline test

    Create a promptfoo configuration file with one provider pointing at the model under test and one plain test case with a harmless prompt. Keep the first run to a single assertion-free or simple assertion so any failure points to setup, not to the classifier. The step is done when running the eval against this config completes and reports a result for the test case, which confirms the provider call works before you add classifier logic.

  3. Add a classifier or moderation assertion

    Add a classifier assertion that uses a Hugging Face toxicity, bias or PII model, or a moderation assertion that calls a moderation API, to the test's assert list. Set the threshold or flagged-category options that match your policy, and document why each threshold was chosen. Classifier assertions cover sentiment, toxicity, bias, PII detection and custom labels, while moderation assertions flag harmful outputs. The step is done when the config validates and the assertion appears in the eval's output for that test.

  4. Supply credentials for the chosen service

    Set the API token for the Hugging Face classifier or the key for the moderation service as environment variables in the shell or CI runner, not in the config file. Confirm which account pays for the calls, because classifier and moderation requests are billed or rate limited by that provider, and ask your provider what they charge for each call. The step is done when a minimal eval runs without authentication errors from the classifier or moderation endpoint.

  5. Add a deliberately unsafe control case

    Add a test case with an output you know must fail the check, such as a clearly abusive sentence for a toxicity assertion or a fake card number and email address for a PII assertion. Use a labeled, illustrative example written by your team and keep it in the test file as a permanent control. The step is done when the eval reports this case as failed. If it passes, the assertion is not wired to the output you expect, and you should fix the configuration before continuing.

  6. Add a safe control and run the full eval

    Add a benign test case that must pass, then run the full eval with the complete set of test cases and assertions. Use the eval's output options to write results to a file so the run is reproducible. The step is done when the safe case passes, the unsafe control fails, and the summary counts match the cases you wrote.

  7. Review failing outputs and tune thresholds

    Open the failing rows in the results view or output file and read the actual model output alongside the classifier score or moderation flag. Decide whether each failure is a real policy violation, a false positive from the classifier, or a case that needs a different threshold or category. Record the decision in the test file comments. The step is done when every failure has a documented reason and the control cases still behave as intended after any threshold change.

How an eval request flows through the target, the checker and the report

The flow starts with a test case in the promptfoo config, which is sent to the target model or application under test. The target's output then goes to the assertion stage, where a classifier or moderation assertion scores it. Hugging Face classifiers and moderation APIs sit outside your machine, so that hand-off crosses an external service boundary. Check that each result returns a pass or fail that lands in the report, and confirm what text leaves your environment at that boundary.

Output text is scored by an external classifier or moderation API before the result reaches the report.

When a classifier is cheaper than a model grader

A classifier assertion is usually the cheaper check when the question is narrow and label-based, such as whether an output is toxic, contains personal data or falls into a known category. A model grader, by contrast, sends the output and a rubric to a judge model on every run, so its cost is a full model call per test. Each test that uses an llm-rubric or similar grader therefore adds a judge request, and the judge's input includes the output plus the grading prompt, which makes longer outputs and longer rubrics more expensive. A Hugging Face classifier or moderation API call is typically a smaller, single-purpose request, but you still pay for it: check whether your classifier runs on your own hardware, through a hosted inference endpoint, or through a moderation API, because each has a different billing or capacity model. Confirm the pricing and rate limits with the provider before you estimate a suite.

The cost multiplies with repetition. A suite of 200 test cases run on every pull request, several times a day, produces the same number of grader calls each time, so a per-test cost that looks negligible in a single run becomes a monthly line item. Test count, output length and the choice of judge model are the three drivers to model. Moving a check from a large judge model to a narrow classifier reduces both price and variance, because a fixed label set such as toxic or not toxic, with a documented threshold, gives the same answer far more consistently than a free-text judgment. Run the same suite twice on unchanged outputs to see how much the scores move, and keep judge-based checks for criteria that no label set captures.

When you request a quote or evaluate a vendor, ask which classifier models and moderation endpoints are supported, how each is billed, what rate limits apply, and whether results are deterministic for the same input. In your own environment, measure the per-run call count from your current suite, record the latency and cost of one full CI run, and compare that against the same checks run with a classifier. Treat classifier thresholds as tunable settings that need validation on examples from your own product, not defaults you accept without testing.

Security and data handling for outputs sent to classifiers

Classifier and moderation assertions send model outputs to places outside the promptfoo process. The cards below cover where that text goes, what sits inside test data and logs, and what must be approved before real customer data enters an eval.

Where output text travels

promptfoo runs on your machine and calls the target LLM directly, so the target model sees your prompts from there. Hugging Face classifier and moderation API assertions are different: the output text being graded is sent to that third-party service. Unless you run the classifier yourself, treat every graded output as data leaving your environment. Confirm the destination for each assertion type before the first run.

Classifier docs

PII in test datasets

Test cases often contain names, account numbers or addresses copied from production tickets. Those values reach the target model and, through classifier or moderation checks, possibly a second provider. Use synthetic or masked records for the first suites, and keep a documented list of which fields are real. Your PII assertions are only meaningful if the seeded values are known in advance.

API key handling

Hugging Face tokens and moderation provider keys need to live in environment variables or your secrets manager, never in a committed promptfooconfig.yaml. Scope each token to the minimum permission the classifier needs and rotate it on the schedule your security team sets. Check CI logs, since verbose runs can echo configuration values.

Result reports and logs

Eval outputs, grader reasons and failed examples are written to result files, reports and any shared server. A flagged output can contain the sensitive text itself, so the report carries the data forward. Decide who can read result files, how long they are kept, and whether reports are shared outside the test team before you turn on verbose output.

Self-hosted server limits

The self-hosted promptfoo app stores data in a local SQLite database that cannot be shared across replicas, has no RBAC or built-in authentication, and is not recommended for production use. Teams that persist eval results to that server must place it behind access controls they run themselves, or evaluate the Enterprise and On-Premise options for shared access.

Self-hosting docs

Approved data path before real data

Before any customer records reach an eval, get written approval from security, privacy and the data owner for each hop: the target model, every classifier or moderation API, the CI runner and the report store. Ask whether a self-hosted classifier or in-region moderation option is available. Record the decision so auditors can trace where the data went.

Keeping classifier checks stable in CI and over releases

Classifier assertions are only useful if a failing score means the output changed, not that the grader did. Start by pinning everything that can move under you: the promptfoo version installed in CI (the npm package and its Node.js runtime requirement, which should be confirmed against your pipeline image), the Hugging Face classifier model identifier and revision used by the assertion, and the moderation provider and model named in your config. Record these in the same commit as the eval suite so that a rerun six months later uses the same grader. For hosted moderation APIs, confirm with the vendor whether model identifiers are aliased to a floating version, since a silent upgrade can shift scores with no change in your repository.

Track pass rates per assertion over time, not just the overall suite result. Store each run's results as an artifact or in a dashboard, and compare the rate for toxicity, bias and PII checks separately, so a drop in one category is not hidden by stable results elsewhere. When a promptfoo upgrade or a classifier change moves the rate, rerun the previous and new configurations side by side on the same test set before deciding whether the shift is a real regression. Plan for outages and rate limits as well: a moderation API timeout should produce an explicit error state in the report rather than a silent pass, and your pipeline should decide whether to retry, skip or fail the stage. The promptfoo CI and operations content group covers retries, caching and gate design in detail.

Review classifier thresholds whenever the target model changes. A new model may phrase refusals, hedges or quoted slurs differently, and a threshold tuned on the previous model can start flagging benign output or missing harmful output. Treat a change of target model as a trigger for a threshold review: rerun the labeled examples, check false positives and false negatives by hand, and record the decision alongside the version pins. Confirm with your classifier and moderation vendors how their scores are calibrated, because a threshold that is meaningful for one label set may not transfer to another.

Questions teams ask before adding classifier and moderation checks

How much effort does setting up classifier and moderation checks take in-house?

For a team already running promptfoo, adding a classifier or moderation assertion is a configuration change, so the effort sits in deciding what to measure and how to judge the results. The in-house work usually includes choosing which classifiers match your risks (toxicity, bias, PII or custom labels), wiring them into the config, running them on representative outputs, and setting thresholds that your reviewers accept. Teams without a prior promptfoo setup also need to install the tool, which requires Node.js 22.22.0 or newer, and agree on where results are stored. Ask any partner to separate configuration effort from the labeling and threshold-tuning work, since the second part usually takes longer.

What drives the cost of running classifiers compared with a model grader?

A classifier runs a fixed model over each output, so its cost is mostly compute or API calls per test, and it does not need a second language model to reason about the answer. A model grader sends each output, plus a rubric, to a judge model, which adds token charges and usually more latency. Moderation APIs are billed per request by their provider, so the cost depends on your volume and the provider's terms. Hosted classifiers and self-hosted ones differ in infrastructure cost, and self-hosting adds sizing and patching work. Ask for the per-test cost of each option on your own sample, not a generic rate.

What does the work need from our team: data, labels, credentials and a review owner?

You need four things before the first suite runs. First, a sample of real or realistic model outputs that reflects your product, with any personal data handled under your own policies. Second, labeled examples showing which outputs should fail, so you can test whether a classifier's threshold matches your judgment. Third, credentials for any moderation API or model host, stored in your secrets tooling. Fourth, a named owner who decides what a failing check means and signs off on threshold changes. Without the last item, flagged outputs pile up with no clear action. Confirm who on your side can approve each of these before work starts.

Can our own engineers build and maintain these checks without a partner?

Yes, if your engineers have experience with test pipelines, can review model outputs critically, and have time to maintain the suite as models and classifiers change. Teams with a strong evaluation practice often add the assertions themselves and bring in outside help for threshold design, data handling review or a first rollout. A partner is more useful when the scope spans several applications, when the team lacks people to label data, or when the results must be defended in a compliance review. DeployOpen plans and implements this work inside your infrastructure under a written scope, and offers ongoing support as a retainer.

How long does a first working classifier suite take?

The duration depends mainly on how many output types you check, how much labeled data exists, and whether the classifiers run hosted or self-hosted. A narrow suite for one application with one or two checks, using data you already have, is much faster to stand up than a suite covering several applications with custom labels. Timing also depends on how quickly your review owner can approve thresholds and on how many rounds of tuning the results need. No duration applies until a written scope exists, so ask for a timeline tied to specific deliverables and a stated set of assumptions.

Do classifier checks replace a model grader or a human review?

No. Classifiers are good at flagging known categories such as toxicity or PII at low cost and with stable results, but they miss context, nuance and task-specific failures such as a wrong answer that is polite. A model grader or a deterministic assertion covers those cases better. In practice, teams run cheap classifier checks on every output and reserve model graders for the cases that need judgment, then sample flagged and passing outputs for human review. Deciding this split is part of the scope, and a written plan should state which checks run where.

What should we ask for in a quote for this work?

Ask for a written scope that lists the applications covered, the output types and risk categories checked, the classifiers and moderation APIs in use, and where each one runs. Request the deliverables explicitly: the promptfoo configuration, the test data set, threshold rationale, run instructions, and documentation for your review owner. Ask which costs are one-time and which recur, such as API usage, hosting, retesting after model changes and support hours. Also confirm what the client must provide, the assumptions behind the timeline, and how changes to scope are priced. Because DeployOpen does not publish a price list, a quote follows from this written scope.

Are classifier checks safe to run on sensitive outputs such as PII?

They can be, provided the checks run in infrastructure your policies allow. Confirm where each classifier executes: a hosted service receives the output text, while a self-hosted model keeps it inside your environment. Review what the provider retains, how logs store flagged content, and who can read results. Treat the test data set as sensitive, because it often contains real examples of the content you are screening for. Ask your security team to review the data flow before the first run, and document the decision so an auditor can follow it later.

How DeployOpen scopes and delivers promptfoo evaluation checks

DeployOpen treats classifier and moderation assertions as part of a wider promptfoo eval suite, not as a standalone filter. We agree in writing which outputs are checked, which classifiers or moderation endpoints grade them, and what evidence the client receives. The work is delivered inside the client's own infrastructure and CI pipelines.

How we scope

  • Inventory the output types that need checks for toxicity, bias, PII or harmful content, and the users who read them
  • Agree in writing which classifiers or moderation APIs will run, and where each one is hosted
  • Set the pass criteria and the review process for flagged outputs before any test is written

How we build

  • Write promptfoo configs that combine classifier and moderation assertions with deterministic checks in the same suite
  • Test each assertion against known-good and known-bad sample outputs to confirm it flags what it should
  • Wire the suite into the client's pipeline so results are reproducible across runs and environments

How we hand over

  • Deliver the config files, assertion rationale, sample datasets and run instructions in a repository the client controls
  • Document which classifier or moderation provider was used, its settings and known blind spots for the client's review
  • Walk the client's engineers through triage of flagged results and how to update thresholds safely

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers after the initial handover
  • Retesting after model, prompt or classifier changes can be included in a retainer or agreed as a separate scope
  • Confirm with us during scoping which support level and response expectations apply to your suite

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.