MastraScorer
MastraScorer クラスは、Mastra のすべての Scorer の基底クラスです。入出力ペアを評価するための標準的な .run() メソッドを提供し、preprocess → analyze → generateScore → generateReason という実行フローによる複数ステップのスコアリング Workflow をサポートします。
ほとんどの場合、Scorer インスタンスの作成には createScorer を使用してください。MastraScorer を直接インスタンス化することは推奨されません。
MastraScorer インスタンスの取得方法how-to-get-a-mastrascorer-instanceへの直接リンク
MastraScorer インスタンスを返す createScorer ファクトリー関数を使用します。
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:
output:
runId:
requestContext:
groundTruth:
.run() の戻り値run-returnsへの直接リンク
runId:
score:
reason:
preprocessStepResult:
analyzeStepResult:
preprocessPrompt:
analyzePrompt:
generateScorePrompt:
generateReasonPrompt:
judge:
Judge の結果Judge の結果への直接リンク
任意の judge レコードには、プロンプトベースの Scorer ステップによって行われた Judge モデル呼び出しの詳細が含まれます。既知のキーは preprocess、analyze、generateScore、generateReason です。各キーには、順序付けられた 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 の値は、評価対象の応答の品質ではなく、論理的なプロンプトステップ実行の結果を表します。構造化出力のフォールバックが最終的に成功した場合、attemptCount が1より大きい success 実行が1件作成されます。すべての試行が失敗した場合は、failed 実行が1件作成されます。
成功した実行には、検証済みの output と正規化された usage が必要です。失敗した実行には error の概要が必要で、ランタイムが受け取った情報だけが含まれます。出力が検証された後にコールバックまたはオーケストレーションでエラーが発生した場合に限り、失敗した実行に output が含まれます。Mastra は rawOutput を解析して output を作成しません。
attemptCount は、構造化出力のフォールバックを含む Judge の呼び出し回数です。modelCallCount は、それらの試行全体で完了したモデルステップの数です。durationMs はプロンプトステップ実行全体にかかった時間です。
関数ステップでは judge エントリは作成されません。このレコードの使用量は、評価対象の Agent や Workflow ではなく、Scorer の Judge モデルに属します。成功した実行を集計する場合は、status で絞り込んでください。完了したすべての Provider 使用量を集計する場合は、両方のステータスを含めてください。任意の cost フィールドは、信頼できるコスト、ソース、単位が直接報告された成功実行にのみ含まれます。
Scorer 実行全体の使用量、レイテンシー、推定コストを集計して照会するには、Mastra metrics を使用します。judge レコードは1回の Scorer 実行を表すものであり、metrics や Trace を照会するものではありません。
失敗した実行失敗した実行への直接リンク
Scorer のステージが失敗した場合も、.run() の Promise は reject されます。完了したステージと、そのステージで生成された結果を調べるには、ScorerRunError を catch します。
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:
completedSteps:
result:
result スナップショットには、完了したステージの出力と Judge 実行情報が含まれます。たとえば、generateScore が 0 を返した後に generateReason が失敗した場合、error.result.score は 0、generateScore 実行は status: 'success'、generateReason 実行は status: 'failed' になります。この実行は失敗したままです。
プロンプトの失敗によって、実行ID、入力、失敗した judge エントリだけを含む error.result が作成される場合があります。Scorer フィールドを生成する前に関数ステージが失敗した場合、結果は作成されません。
JSON.stringify(error) は標準の MastraError シリアライズを使用し、成功および失敗した Judge の情報を含む result を省略します。Scorer の成果物や失敗時の生出力が必要な場合は、result を明示的に読み取ってください。
メモリ内の実験結果には、失敗した Scorer から得られた完了済みのスコアや理由を、error、failedStep、completedSteps とともに保持できます。Scorer は引き続き失敗として扱われ、復元されたスコアは従来の成功スコアストレージには書き込まれません。
ステップの実行フローステップの実行フローへの直接リンク
.run() を呼び出すと、MastraScorer は定義されたステップを次の順序で実行します。
- preprocess(任意):データを抽出または変換します
- analyze(任意):入出力と前処理済みデータを処理します
- generateScore(必須):数値スコアを算出します
- generateReason(任意):スコアの説明を提供します
各ステップは前のステップの結果を受け取るため、複雑な評価パイプラインを構築できます。
使用例使用例への直接リンク
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 リファレンスを参照してください。