Skip to main content

Quality scorer

quality-scorer checks a finished answer before your application receives it. It can require a minimum length, score the answer with local benchmarks, and run your assertions. The gateway blocks a failed answer, replaces it with a fixed message, or asks the provider for a new answer.

It runs on Chat Completions, Responses, and Messages. A good score does not prove that the facts in an answer are correct.

Configuration​

Start with one measurable rule. Add it to a test gateway with the config-first workflow:

policy-config.yaml
pack:
  name: minimum-answer-length
  version: 1.0.0
  enabled: true
policies:
  chain:
    - quality-scorer
policy:
  quality-scorer:
    min_output_chars: 20
    failure_action:
      action: block

Fields​

FieldTypeDefaultDescription
modestringbufferbuffer holds a stream until the answer is scored. stream_through sends the stream frames immediately and scores the answer after the stream ends, without enforcement.
min_output_charsinteger0Fails an answer with fewer characters. 0 turns it off.
min_sentencesinteger0Fails an answer with fewer sentences. 0 turns it off.
benchmarksobject{}Switches: ragas_faithfulness, ragas_relevancy, bleu_score, nli_entailment, coherence, completeness
bleu_referencestringReference text for bleu_score when the request has no context documents
assertionsarray[]Assertions. See the fields below.
thresholdsobject{}Minimum scores: min_aggregate, min_faithfulness, min_relevancy, min_bleu, min_accuracy, min_coherence, min_completeness. A threshold turns on its benchmark if the benchmark is not set.
weightsobject{}Weights in the aggregate: faithfulness, relevancy, bleu, accuracy, coherence, completeness. An enabled benchmark without a weight uses 1.0.
failure_action.actionstringblockblock, fallback, or retry
failure_action.fallback_messagestringBuilt-in textReplacement text with action: fallback. The default is I apologize, but I cannot provide a sufficiently accurate response to this query.
failure_action.max_retriesinteger0Number of provider retries with action: retry, from 0 to 5
providersarray[]Graders of the LLM-graded assertions. See the grader fields below.
targetsarray[]Graders that the gateway uses when providers is empty
pass_policy.strategystringallall, quorum, or weighted_average, for assertions with mode: enforce and severity: critical
pass_policy.quorumnumber0.5Share of those assertions that must pass with quorum
pass_policy.thresholdnumber0.5Minimum weighted score with weighted_average
industry_profiles.<industry>object{}Threshold overrides for requests with verdictan.industry set to this name
judgeobjectOptional judge model call. A sampled fail verdict fails the answer, except with regression_monitoring.

Assertion fields​

FieldTypeDefaultDescription
typestringAssertion type. Required. An unsupported type shows as an assertion error.
namestringThe typeName in the details
enabledbooleantruefalse skips the assertion
thresholdnumberDepends on typeMinimum score that passes
weightnumber1.0Weight with weighted_average
modestringenforceenforce, audit, or shadow. Only enforce can fail an answer.
severitystringcriticalcritical, warning, or info. Only critical can fail an answer.
configobject{}Options of the type, such as value for contains or rubric for llm-rubric

Quality assertion configuration lists the types and their options.

Grader fields​

Each entry of providers or targets is a string or an object. A string such as openai:gpt-5.4-mini sets the model of a grader that uses the OpenAI API.

FieldTypeDefaultDescription
id, label, target, providerstringName of the grader in the details. provider can also be <provider>:<model>.
modelstringgpt-5.4-miniModel of the grader
base_urlstringOpenAI APIBase URL of an OpenAI-compatible API, or its full /chat/completions URL
secret_key_refobjectCredential reference with env. The gateway sends it as a bearer token.
headersobject{}More request headers for the grader

The gateway tries the graders in list order. It uses the next grader only when a grader does not return a score. If no grader returns a score, the assertion fails. An enabled judge block supplies the timeout, the thresholds, and the prompt template. The gateway does not send config.

Phase and verdicts​

ItemValue
Phaseoutput
Enforced pathChat Completions, Responses, and Messages. Streams with mode: buffer.
Verdictsallow, block
Reason codesok, quality.fallback, quality.stream_through_failed, and one or more of quality.too_short, quality.too_few_sentences, quality.<metric>_below_threshold, quality.aggregate_below_threshold, or an assertion name

A block returns HTTP 400 with error code content_policy_violation and a verdictan.decision object with verdict BLOCK. A fallback returns HTTP 200 with the replacement text and quality.fallback in verdictan.decision.

Compare a short and a long answer​

Test the rule offline with two JSON test files that give the provider answer in upstream_response:

tests/short.json
{"name": "short answer blocks",
 "input": {"messages": [{"role": "user", "content": "Is the report ready?"}],
           "upstream_response": {"choices": [{"message": {"role": "assistant", "content": "OK"}}]}},
 "expected": {"verdict": "block", "reason_code": "quality.too_short"}}
tests/long.json
{"name": "long answer passes",
 "input": {"messages": [{"role": "user", "content": "Is the report ready?"}],
           "upstream_response": {"choices": [{"message": {"role": "assistant", "content": "The requested report is ready for review."}}]}},
 "expected": {"verdict": "allow", "reason_code": "ok"}}

Run verdictan policy test --json. Both pass. Through a gateway, the short answer returns HTTP 400 with quality.too_short in the decision. Another control can still block an answer that passes this rule, so read the nested policy results to find the failing check.

To return a fixed message instead of an error, use:

Inside policy.quality-scorer
failure_action:
  action: fallback
  fallback_message: "The answer did not meet the minimum length."

The gateway then returns HTTP 200 with that message and reason code quality.fallback. It does not call the model again.

Retry a failed answer​

To ask the provider for a new answer, use:

Inside policy.quality-scorer
failure_action:
  action: retry
  max_retries: 2

When an answer fails, the gateway sends the same request to the provider again. It sends the request a maximum of max_retries times. Then it scores each new answer with all the output controls of the chain. The first answer that passes goes to your application. If all the answers fail, the gateway blocks the last answer.

Each retry is a full provider call. It adds the latency and the cost of that call to the request. Set max_retries to the lowest value that is necessary.

Retries obey these rules:

  • A retry uses the same provider routing, fallback, provider retry policy, and budget checks as the first call. A retry does not use the provider cache.
  • The gateway stops the retries when the spend of the answers uses all of the API token budget. On Chat Completions, the token rate limit also stops the retries.
  • A retry is not a new client request. Request rate limits do not count it.
  • The provider charges for each answer. The gateway records a different spend log for each discarded answer. The quality_retry metadata of that log gives the request ID and the attempt number.
  • Only the served or blocked answer counts as the usage of the request. The response usage, the token rate limit, and the agent usage counters do not include the discarded answers.
  • A request with a usage authorization does not retry, because the authorization holds the funds for one provider call.
  • Retries apply only to responses with stream: false.

The retry object in the details of the quality result shows the number of answers, the reason code of each discarded answer, and the reason when a retry stopped.

When the basic rule works, add quality assertions for JSON, required phrases, or a rubric.

Score a stream without delay​

With stream: true and mode: buffer, the gateway holds the stream until the answer is complete. Then it scores the answer, and it releases or blocks the stream.

To send each stream frame to your application immediately, use mode: stream_through. The gateway scores the complete text after the provider ends the stream. It records the result in the decision event. Your application has the frames already, so the result cannot block or replace the stream. A failed answer has the allow verdict with reason code quality.stream_through_failed, and the failure reasons are in the details.

A request with stream: false gets the same scoring and enforcement in the two modes.

Use a model for LLM-graded assertions​

By default, the llm-rubric, g-eval, model-graded-closedqa, and factuality assertions use local heuristics. To score them with a model, add a grader to providers:

Inside policy.quality-scorer
providers:
  - id: quality-grader
    base_url: https://api.openai.com/v1
    model: gpt-5.4-mini
    secret_key_ref:
      env: QUALITY_GRADER_API_KEY
assertions:
  - type: llm-rubric
    threshold: 0.8
    config:
      rubric: The answer names the correct capital city.

The gateway sends the rubric, the user question, and the answer to the Chat Completions endpoint of the grader. The model score is the assertion score.

How it works​

  1. The control reads the answer from choices[0].message.content, and the query and context documents from the request.
  2. An answer shorter than min_output_chars records quality.too_short. Fewer sentences than min_sentences records quality.too_few_sentences.
  3. If the request has verdictan.industry and industry_profiles has that name, the profile thresholds replace the top-level ones.
  4. Each enabled benchmark is scored with local heuristics. If the process environment has VERDICTAN_NLI_ENDPOINT, nli_entailment calls that endpoint with a 5-second timeout.
  5. Each enabled assertion is evaluated and scored. With providers or targets, a grader model scores the LLM-graded assertions.
  6. The aggregate combines the weighted benchmark and assertion scores.
  7. Each score below its threshold records a failure, such as quality.faithfulness_below_threshold or quality.aggregate_below_threshold.
  8. pass_policy is applied to the enforced, critical assertions. A failure records the names of the failed assertions.
  9. No failure: allow with ok.
  10. A failure with fallback: the gateway replaces the answer with fallback_message, and the verdict is allow with quality.fallback.
  11. A failure with retry: the gateway asks the provider for a new answer and starts the output controls again, until an answer passes or the retries stop.
  12. A failure with any other action, or after the last retry: block, with the comma-separated failures as the reason code, such as quality.too_short,quality.aggregate_below_threshold.

The details contain output_chars, sentence_count, metrics, thresholds, weights, has_context, assertions, failures, pass_policy_result, and judge. Scores in the details are percentages.

Limits and failure behavior​

  • With mode: stream_through, a failed stream reaches your application. Use mode: buffer when a failed answer must not reach it.
  • Each retry adds a provider call, its latency, and its cost to the request.
  • Benchmarks are local heuristics, not model evaluations. Measure the thresholds on your own traffic before you block on them.
  • thresholds.min_aggregate without benchmarks or assertions turns on ragas_relevancy and completeness to calculate an aggregate.
  • ragas_faithfulness needs context documents in the request. Without them, there is no faithfulness score, and min_faithfulness cannot fail. Without context, bleu_score uses bleu_reference.
  • Audit and shadow assertion results stay available in the details but never block.
  • The judge adds latency and provider cost to every response it evaluates.
  • A grader model adds a provider call, its latency, and its cost for each LLM-graded assertion.
  • Lint also accepts industry, mock_scoring, and regression_monitoring. This page does not cover them.

Next steps​