createScorer
Mastra は、入出力のペアを評価するカスタムスコアラーを定義できる、統一された createScorer ファクトリーを提供します。各評価ステップには、ネイティブ JavaScript 関数または LLM ベースのプロンプトオブジェクトを使用できます。カスタムスコアラーは Agent と Workflow のステップに追加できます。
カスタムスコアラーの作成方法カスタムスコアラーの作成方法への直接リンク
createScorer ファクトリーを使用し、名前、説明、任意の judge 設定を指定してスコアラーを定義します。その後、ステップメソッドをチェーンして評価パイプラインを構築します。少なくとも generateScore ステップを指定する必要があります。
プロンプトオブジェクトステップは、description + createPrompt と、outputSchema(preprocess/analyze の場合)を持つオブジェクトとして表すステップ設定です。これらのステップは judge LLM を呼び出します。関数ステップは通常の関数であり、judge を呼び出しません。
import { createScorer } from '@mastra/core/evals'
const scorer = createScorer({
id: 'my-custom-scorer',
name: 'My Custom Scorer', // Optional, defaults to id
description: 'Evaluates responses based on custom criteria',
type: 'agent', // Optional: for agent evaluation with automatic typing
judge: {
model: myModel,
instructions: 'You are an expert evaluator...',
},
})
.preprocess({/* step config */})
.analyze({/* step config */})
.generateScore(({ run, results }) => {
// Return a number
})
.generateReason({/* step config */})
createScorer のオプションcreatescorer-optionsへの直接リンク
id:
name が指定されていない場合は名前として使用されます。name?:
id がデフォルトになります。description:
judge?:
model:
instructions:
jsonPromptInjection?:
inputProcessors?:
outputProcessors?:
errorProcessors?:
processAPIError を実装し、LLM API の拒否を検査して再試行を指示できます(例:StreamErrorRetryProcessor)。従来のモデルアダプターは generateLegacy() を使用するため、エラー Processor を実行しません。maxProcessorRetries?:
type?:
prepareRun?:
この関数は、ステップメソッドをチェーンできるスコアラービルダーを返します。.run() メソッドとその入出力の詳細は、MastraScorer リファレンスを参照してください。
judge は、プロンプトオブジェクトとして定義されたステップ(プロンプトモードの preprocess、analyze、generateScore、generateReason)でのみ実行されます。関数ステップだけを使用する場合、judge は呼び出されず、確認できる LLM 出力もありません。その場合、スコアと理由は関数で生成する必要があります。
プロンプトオブジェクトステップを実行すると、構造化された LLM 出力は対応する結果フィールド(preprocessStepResult、analyzeStepResult、または calculateScore が generateScore で受け取る値)に保存されます。
judge リクエストの再試行judge リクエストの再試行への直接リンク
失敗した judge リクエスト内の一時的なエラーを再試行するには、既存の judge errorProcessors 設定を使用します。スコアラーの Workflow、Trace の対象、バッチ項目、スコアの書き込み、完了済みのスコーラーステップは再試行されません。
@mastra/core 1.49.0 にはスコアラーのエラー Processor 設定が含まれていません。この設定を使用する前に、スコアラーの Processor をサポートするバージョンへアップグレードするか、その変更だけをバックポートしてください。
次の例では、上限付きの再試行予算を1つ使用します。Processor の maxRetries と judge.maxProcessorRetries を同じ値に設定してください。Processor の試行回数にモデルの再試行が掛け合わされないよう、内部 judge Agent のモデル再試行はデフォルトの 0 のままにします。
import { createScorer } from '@mastra/core/evals'
import { StreamErrorRetryProcessor } from '@mastra/core/processors'
const isTransientNetworkError = (error: unknown) =>
error instanceof Error && /ECONNRESET|ETIMEDOUT|socket hang up/i.test(error.message)
const retryProcessor = new StreamErrorRetryProcessor({
maxRetries: 2,
maxRetryAfterMs: 30_000,
delayMs: ({ retryCount }) => Math.min(1_000 * 2 ** retryCount, 30_000),
matchers: [isTransientNetworkError],
retryUnknownErrors: false,
})
export const responseQuality = createScorer({
id: 'response-quality',
description: 'Scores response quality',
judge: {
model: myModel,
instructions: 'Return a score and concise reason.',
errorProcessors: [retryProcessor],
maxProcessorRetries: 2,
},
})
.generateScore({
description: 'Score the response quality.',
createPrompt: ({ run }) => `Score: ${run.output}`,
})
.generateReason({
description: 'Explain the score.',
createPrompt: () => 'Explain the score.',
})
この設定では、失敗したリクエストに対する Provider の試行は最大3回です。初回リクエストに、Processor による2回の再試行を加えた回数です。generateScore が完了した後で generateReason に再試行可能なエラーが発生した場合、generateReason だけが再試行されます。
StreamErrorRetryProcessor は、Provider が提供する再試行可能メタデータと、対象を限定したカスタム matcher を尊重します。retryUnknownErrors はデフォルトで無効なため、認証、無効なリクエスト、コンテキスト長のエラーは、明示的に一致させない限り直ちに失敗します。Retry-After の値はデフォルトで 30_000 ミリ秒を上限とします。この上限を変更するには maxRetryAfterMs を使用します。
外側のスコアラーや Workflow に再試行を追加しないでください。追加の試行を意図的に許容する場合を除き、0以外のモデル再試行設定とこの Processor を組み合わせないでください。
1つのステップの再試行を上書きする1つのステップの再試行を上書きするへの直接リンク
ステップの judge 設定は、スコアラーレベルの judge フィールドを上書きします。Processor 配列はスコアラーレベルの配列を置き換えます。スコアラーレベルの数値上限を継承するには、ステップ設定で maxProcessorRetries を省略します。
連携した Processor の再試行には、Mastra の現行生成 API を使用する judge モデルが必要です。従来のモデルアダプターは generateLegacy() を呼び出してエラー Processor を迂回し、その API に固有の AI SDK maxRetries のデフォルト値 2 を使用します。
型安全性型安全性への直接リンク
型推論と IntelliSense のサポートを向上させるため、スコアラー作成時に入出力型を指定できます。
Agent 型のショートカットAgent 型のショートカットへの直接リンク
Agent を評価する場合は、type: 'agent' を使用すると Agent の入出力に適切な型が自動的に設定されます。
import { createScorer } from '@mastra/core/evals'
// Agent scorer with automatic typing
const agentScorer = createScorer({
id: 'agent-response-quality',
description: 'Evaluates agent responses',
type: 'agent', // Automatically provides ScorerRunInputForAgent/ScorerRunOutputForAgent
})
.preprocess(({ run }) => {
// run.input is automatically typed as ScorerRunInputForAgent
const userMessage = run.inputData.inputMessages[0]?.content
return { userMessage }
})
.generateScore(({ run, results }) => {
// run.output is automatically typed as ScorerRunOutputForAgent
const response = run.output[0]?.content
return response.length > 10 ? 1.0 : 0.5
})
ジェネリックによるカスタム型ジェネリックによるカスタム型への直接リンク
カスタムの入出力型には、ジェネリックを使用します。
import { createScorer } from '@mastra/core/evals'
type CustomInput = { query: string; context: string[] }
type CustomOutput = { answer: string; confidence: number }
const customScorer = createScorer<CustomInput, CustomOutput>({
id: 'custom-scorer',
description: 'Evaluates custom data',
}).generateScore(({ run }) => {
// run.input is typed as CustomInput
// run.output is typed as CustomOutput
return run.output.confidence
})
組み込みの Agent 型組み込みの Agent 型への直接リンク
ScorerRunInputForAgent- Agent の評価用にinputMessages、rememberedMessages、systemMessages、taggedSystemMessagesを含みますScorerRunOutputForAgent- Agent の応答メッセージの配列です
これらの型を使用すると、スコアリングロジックで自動補完、コンパイル時の検証、より分かりやすいドキュメントを利用できます。
Agent 型による Trace のスコアリングAgent 型による Trace のスコアリングへの直接リンク
type: 'agent' を使用すると、スコアラーを Agent に直接追加する場合と、Agent のインタラクションから得た Trace をスコアリングする場合の両方に対応できます。スコアラーは、Trace データを適切な Agent の入出力形式へ自動的に変換します。
const agentTraceScorer = createScorer({
id: 'agent-trace-length',
description: 'Evaluates agent response length',
type: 'agent',
}).generateScore(({ run }) => {
// Trace data is automatically transformed to agent format
const userMessages = run.inputData.inputMessages
const agentResponse = run.output[0]?.content
// Score based on response length
return agentResponse?.length > 50 ? 0 : 1
})
// Register with Mastra for trace scoring
const mastra = new Mastra({
scorers: {
agentTraceScorer,
},
})
ステップメソッドのシグネチャステップメソッドのシグネチャへの直接リンク
preprocesspreprocessへの直接リンク
分析前にデータを抽出または変換できる、任意の前処理ステップです。
関数モード:
関数:({ run, results }) => any
run.input:
[{ role: 'user', content: 'hello world' }] のようなユーザーメッセージの配列です。Workflow で使用した場合は、Workflow の入力です。run.output:
run.runId:
run.requestContext?:
results:
戻り値:any
任意の値を返せます。戻り値は、後続ステップで preprocessStepResult として使用できます。
プロンプトオブジェクトモード:
description:
outputSchema:
createPrompt:
judge?:
analyzeanalyzeへの直接リンク
入出力と前処理済みデータを処理する、任意の分析ステップです。
関数モード:
関数:({ run, results }) => any
run.input:
[{ role: 'user', content: 'hello world' }] のようなユーザーメッセージの配列、Workflow では Workflow の入力です。run.output:
run.runId:
run.requestContext?:
results.preprocessStepResult?:
戻り値:any
任意の値を返せます。戻り値は、後続ステップで analyzeStepResult として使用できます。
プロンプトオブジェクトモード:
description:
outputSchema:
createPrompt:
judge?:
generateScoregeneratescoreへの直接リンク
最終的な数値スコアを計算する必須ステップです。
関数モード:
関数:({ run, results }) => number
run.input:
[{ role: 'user', content: 'hello world' }] のようなユーザーメッセージの配列、Workflow では Workflow の入力です。run.output:
run.runId:
run.requestContext?:
results.preprocessStepResult?:
results.analyzeStepResult?:
戻り値:number
このメソッドは数値スコアを返す必要があります。
プロンプトオブジェクトモード:
description:
outputSchema:
createPrompt:
judge?:
プロンプトオブジェクトモードを使用する場合は、LLM の出力を数値スコアに変換する calculateScore 関数も指定する必要があります。
calculateScore:
generateReasongeneratereasonへの直接リンク
スコアの説明を提供する任意のステップです。
関数モード:
関数:({ run, results, score }) => string
run.input:
[{ role: 'user', content: 'hello world' }] のようなユーザーメッセージの配列、Workflow では Workflow の入力です。run.output:
run.runId:
run.requestContext?:
results.preprocessStepResult?:
results.analyzeStepResult?:
score:
戻り値:string
このメソッドはスコアを説明する文字列を返す必要があります。
プロンプトオブジェクトモード:
description:
createPrompt:
judge?:
すべてのステップ関数は非同期にできます。