跳到主要内容

MastraScorer

MastraScorer 类是 Mastra 中所有 Scorer 的基类。它提供标准的 .run() 方法来评估输入/输出对,并支持采用 preprocess → analyze → generateScore → generateReason 执行流程的多步骤评分 Workflow。

大多数用户应使用 createScorer 创建 Scorer 实例。不建议直接实例化 MastraScorer

如何获取 MastraScorer 实例
how-to-get-a-mastrascorer-instance的直接链接

使用 createScorer factory 函数,它会返回一个 MastraScorer 实例:

import { createScorer } from '@mastra/core/evals'

const scorer = createScorer({
name: 'My Custom Scorer',
description: 'Evaluates responses based on custom criteria',
}).generateScore(({ run, results }) => {
// scoring logic
return 0.85
})

// scorer is now a MastraScorer instance

.run() 方法
run-method的直接链接

.run() 方法是执行 Scorer 并评估输入/输出对的主要方式。它通过你定义的步骤(preprocess → analyze → generateScore → generateReason)处理数据,并返回包含分数、原因和中间结果的详细结果对象。

const result = await scorer.run({
input: 'What is machine learning?',
output: 'Machine learning is a subset of artificial intelligence...',
runId: 'optional-run-id',
requestContext: {/* optional context */},
})

.run() 输入
run-input的直接链接

input:

any
要评估的输入数据。根据 Scorer 的要求,可以是任意类型。

output:

any
要评估的输出数据。根据 Scorer 的要求,可以是任意类型。

runId:

string
此评分 run 的可选唯一标识符。

requestContext:

any
来自所评估 Agent 或 Workflow 步骤的可选 request context。

groundTruth:

any
评分时用于比较的可选预期输出或参考输出。使用 runEvals 时会自动传入。

.run() 返回值
run-returns的直接链接

runId:

string
此评分 run 的唯一标识符。

score:

number
generateScore 步骤计算出的数值分数。

reason:

string
分数的说明(如果定义了 generateReason 步骤,则为可选)。

preprocessStepResult:

any
preprocess 步骤的结果(如果定义,则为可选)。

analyzeStepResult:

any
analyze 步骤的结果(如果定义,则为可选)。

preprocessPrompt:

string
预处理 prompt(如果定义,则为可选)。

analyzePrompt:

string
分析 prompt(如果定义,则为可选)。

generateScorePrompt:

string
生成分数的 prompt(如果定义,则为可选)。

generateReasonPrompt:

string
生成原因的 prompt(如果定义,则为可选)。

judge:

ScorerJudgeResults
基于 prompt 的 Scorer 步骤的执行详情(如果存在,则为可选)。

Judge 结果
Judge 结果的直接链接

可选的 judge 记录包含基于 prompt 的 Scorer 步骤调用 Judge 模型的详情。已知键包括 preprocessanalyzegenerateScoregenerateReason。每个键都包含一个有序的 executions 数组。

interface ScorerJudgeExecutionBase {
prompt: string
judgeModelId: string
judgeProvider?: string
attemptCount: number
modelCallCount: number
durationMs: number
}

interface ScorerJudgeExecutionSuccess extends ScorerJudgeExecutionBase {
status: 'success'
output: JSONValue
usage: ScorerJudgeUsage
cost?: {
amount: number
unit: string
source: string
}
}

interface ScorerJudgeExecutionFailure extends ScorerJudgeExecutionBase {
status: 'failed'
output?: JSONValue
rawOutput?: string
usage?: ScorerJudgeUsage
finishReason?: string
error: {
name: string
message: string
code?: string
}
}

type ScorerJudgeExecution = ScorerJudgeExecutionSuccess | ScorerJudgeExecutionFailure

interface ScorerJudgeUsage {
inputTokens?: number
outputTokens?: number
totalTokens?: number
reasoningTokens?: number
cachedInputTokens?: number
cacheCreationInputTokens?: number
}

type ScorerJudgeResults = Partial<
Record<
'preprocess' | 'analyze' | 'generateScore' | 'generateReason',
{ executions: ScorerJudgeExecution[] }
>
>

使用步骤键访问其 Judge 执行详情:

const execution = result.judge?.generateScore?.executions[0]

console.log(execution?.status)
console.log(execution?.judgeModelId)
console.log(execution?.usage?.totalTokens)
console.log(execution?.durationMs)

status 值描述的是逻辑 prompt 步骤的执行结果,而不是所评估响应的质量。如果 structured-output fallback 最终成功,则会创建一条 success execution,其 attemptCount 大于 1。尝试次数耗尽时,会创建一条 failed execution。

成功的 execution 必须包含已验证的 output 和规范化的 usage。失败的 execution 必须包含 error 摘要,并且只包含 runtime 收到的证据。只有当输出在之后的 callback 或 orchestration 失败前已通过验证时,失败的 execution 才会包含 output。Mastra 不会解析 rawOutput 来创建 output

attemptCount 统计 Judge 调用次数,包括 structured-output fallback。modelCallCount 统计这些尝试中完成的模型步骤数。durationMs 涵盖整个 prompt 步骤的执行时间。

函数步骤不会创建 judge 条目。此记录中的 usage 属于 Scorer 的 Judge 模型,而不是被评估的 Agent 或 Workflow。汇总成功的 execution 时,应按 status 筛选。汇总 Provider 已完成的全部 usage 时,应包含两种状态。可选的 cost 字段仅出现在直接报告权威 cost、source 和 unit 的成功 execution 中。

使用 Mastra metrics 可以查询多个 Scorer run 的聚合 usage、latency 和预估 cost。judge 记录描述单个 Scorer run,不会查询 metrics 或 Trace。

失败的 run
失败的 run的直接链接

Scorer 阶段失败时,.run() promise 仍会被拒绝。捕获 ScorerRunError 可检查已完成的阶段及其生成的结果:

import { ScorerRunError } from '@mastra/core/evals'

try {
const result = await scorer.run({ input, output })
console.log(result.score)
} catch (error) {
if (error instanceof ScorerRunError) {
console.log(error.failedStep)
console.log(error.completedSteps)
console.log(error.result?.score)

const failedExecution = error.result?.judge?.[error.failedStep]?.executions.find(
execution => execution.status === 'failed',
)
console.log(failedExecution?.error)
}

throw error
}

ScorerRunError 提供以下属性:

failedStep:

ScorerStepName
失败的 Scorer 阶段。

completedSteps:

ScorerStepName[]
失败前已完成的 Scorer 阶段,按执行顺序排列。

result:

ScorerRunResultSnapshot | undefined
已完成 Scorer 阶段的输出,以及已尝试 prompt 阶段的 Judge 执行证据。两者均不可用时会省略此属性。

result snapshot 包含已完成阶段的输出和 Judge 执行证据。例如,如果 generateScore 返回 0generateReason 失败,则 error.result.score0generateScore execution 的 status: 'success',而 generateReason execution 的 status: 'failed'。该 run 仍然是失败的。

prompt 失败时可能会创建只包含 run 标识、输入和失败 judge 条目的 error.result。函数阶段在生成 Scorer 字段前失败时,不会创建结果。

JSON.stringify(error) 使用标准 MastraError 序列化,并省略 result,包括成功和失败的 Judge 证据。需要 Scorer 产物或原始失败输出时,请显式读取 result

内存中的实验结果可以保留失败 Scorer 已完成的 score 或 reason,以及 errorfailedStepcompletedSteps。该 Scorer 仍被视为失败,恢复的 score 不会写入旧版成功分数存储。

步骤执行流程
步骤执行流程的直接链接

调用 .run() 时,MastraScorer 会按以下顺序执行已定义的步骤:

  1. preprocess(可选):提取或转换数据
  2. analyze(可选):处理输入/输出和预处理后的数据
  3. generateScore(必需):计算数值分数
  4. generateReason(可选):提供分数说明

每个步骤都会接收之前步骤的结果,便于构建复杂的评估 pipeline。

使用示例
使用示例的直接链接

const scorer = createScorer({
name: 'Quality Scorer',
description: 'Evaluates response quality',
})
.preprocess(({ run }) => {
// Extract key information
return { wordCount: run.output.split(' ').length }
})
.analyze(({ run, results }) => {
// Analyze the response
const hasSubstance = results.preprocessStepResult.wordCount > 10
return { hasSubstance }
})
.generateScore(({ results }) => {
// Calculate score
return results.analyzeStepResult.hasSubstance ? 1.0 : 0.0
})
.generateReason(({ score, results }) => {
// Explain the score
const wordCount = results.preprocessStepResult.wordCount
return `Score: ${score}. Response has ${wordCount} words.`
})

// Use the scorer
const result = await scorer.run({
input: 'What is machine learning?',
output: 'Machine learning is a subset of artificial intelligence...',
})

console.log(result.score) // 1.0
console.log(result.reason) // "Score: 1.0. Response has 12 words."

集成
集成的直接链接

MastraScorer 实例可用于 Agent 和 Workflow 步骤

有关定义自定义评分逻辑的详细信息,请参阅 createScorer 参考