Answer similarity scorer
The createAnswerSimilarityScorer() function creates a scorer that evaluates how similar an agent's output is to a ground truth answer. This scorer is specifically designed for CI/CD testing scenarios where you have expected answers and want to ensure consistency over time.
ParametersParameters的直接链接
model:
options:
requireGroundTruth:
semanticThreshold:
exactMatchBonus:
missingPenalty:
contradictionPenalty:
extraInfoPenalty:
scale:
This function returns an instance of the MastraScorer class. The .run() method accepts the same input as other scorers (see the MastraScorer reference), but expects ground truth to be provided in the run object. When options.requireGroundTruth is true (the default), a run without ground truth throws an error. Set it to false to score runs without ground truth as 0.
.run() returnsrun-returns的直接链接
runId:
score:
reason:
preprocessStepResult:
analyzeStepResult:
preprocessPrompt:
analyzePrompt:
generateReasonPrompt:
Scoring detailsScoring details的直接链接
The scorer uses a multi-step process:
- Extract: Breaks down output and ground truth into semantic units
- Analyze: Compares units and identifies matches, contradictions, and gaps
- Score: Calculates weighted similarity with penalties for contradictions
- Reason: Generates human-readable explanation
Score calculation: max(0, base_score - contradiction_penalty - missing_penalty - extra_info_penalty) × scale
ExampleExample的直接链接
Evaluate agent responses for similarity to ground truth across different scenarios:
import { runEvals } from '@mastra/core/evals'
import { createAnswerSimilarityScorer } from '@mastra/evals/scorers/prebuilt'
import { myAgent } from './agent'
const scorer = createAnswerSimilarityScorer({ model: 'openai/gpt-5.6-sol' })
const result = await runEvals({
data: [
{
input: 'What is 2+2?',
groundTruth: '4',
},
{
input: 'What is the capital of France?',
groundTruth: 'The capital of France is Paris',
},
{
input: 'What are the primary colors?',
groundTruth: 'The primary colors are red, blue, and yellow',
},
],
scorers: [scorer],
target: myAgent,
onItemComplete: ({ scorerResults }) => {
console.log({
score: scorerResults[scorer.id].score,
reason: scorerResults[scorer.id].reason,
})
},
})
console.log(result.scores)
For more details on runEvals, see the runEvals reference.
To add this scorer to an agent, see the Scorers overview guide.