> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # MastraScorer `MastraScorer` クラスは、Mastra のすべての Scorer の基底クラスです。入出力ペアを評価するための標準的な `.run()` メソッドを提供し、preprocess → analyze → generateScore → generateReason という実行フローによる複数ステップのスコアリング Workflow をサポートします。 ほとんどの場合、Scorer インスタンスの作成には [`createScorer`](https://mastra.zisheng.pro/ja/reference/evals/create-scorer) を使用してください。`MastraScorer` を直接インスタンス化することは推奨されません。 ## `MastraScorer` インスタンスの取得方法 `MastraScorer` インスタンスを返す `createScorer` ファクトリー関数を使用します。 ```typescript 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()` メソッドは、Scorer を実行して入出力ペアを評価するための主な方法です。定義したステップ(preprocess → analyze → generateScore → generateReason)に沿ってデータを処理し、スコア、理由、中間結果を含む詳細な結果オブジェクトを返します。 ```typescript 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()` の入力 **input** (`any`): 評価対象の入力データ。Scorer の要件に応じて任意の型を使用できます。 **output** (`any`): 評価対象の出力データ。Scorer の要件に応じて任意の型を使用できます。 **runId** (`string`): このスコアリング実行の任意の一意識別子。 **requestContext** (`any`): 評価対象の Agent または Workflow ステップから渡される任意のリクエストコンテキスト。 **groundTruth** (`any`): スコアリング時の比較に使用する任意の期待出力または参照出力。runEvals を使用すると自動的に渡されます。 ## `.run()` の戻り値 **runId** (`string`): このスコアリング実行の一意識別子。 **score** (`number`): generateScore ステップで算出された数値スコア。 **reason** (`string`): generateReason ステップが定義されている場合のスコアの説明(任意)。 **preprocessStepResult** (`any`): preprocess ステップが定義されている場合の結果(任意)。 **analyzeStepResult** (`any`): analyze ステップが定義されている場合の結果(任意)。 **preprocessPrompt** (`string`): preprocess プロンプトが定義されている場合の値(任意)。 **analyzePrompt** (`string`): analyze プロンプトが定義されている場合の値(任意)。 **generateScorePrompt** (`string`): スコア生成プロンプトが定義されている場合の値(任意)。 **generateReasonPrompt** (`string`): 理由生成プロンプトが定義されている場合の値(任意)。 **judge** (`ScorerJudgeResults`): プロンプトベースの Scorer ステップがある場合の実行詳細(任意)。 ### Judge の結果 任意の `judge` レコードには、プロンプトベースの Scorer ステップによって行われた Judge モデル呼び出しの詳細が含まれます。既知のキーは `preprocess`、`analyze`、`generateScore`、`generateReason` です。各キーには、順序付けられた `executions` 配列が含まれます。 ```typescript 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 実行の詳細にアクセスします。 ```typescript 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 します。 ```typescript 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 ステージの出力と、試行されたプロンプトステージの Judge 実行情報。どちらも利用できない場合、このプロパティは省略されます。 `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 は定義されたステップを次の順序で実行します。 1. **preprocess**(任意):データを抽出または変換します 2. **analyze**(任意):入出力と前処理済みデータを処理します 3. **generateScore**(必須):数値スコアを算出します 4. **generateReason**(任意):スコアの説明を提供します 各ステップは前のステップの結果を受け取るため、複雑な評価パイプラインを構築できます。 ## 使用例 ```typescript 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 リファレンス](https://mastra.zisheng.pro/ja/reference/evals/create-scorer)を参照してください。