> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # MastraScorer `MastraScorer` 類別是 Mastra 中所有評分器的基礎類別。它提供標準的 `.run()` 方法來評估輸入/輸出組合,並支援依照 preprocess → analyze → generateScore → generateReason 流程執行的多步驟評分 Workflow。 大多數使用者應透過 [`createScorer`](https://mastra.zisheng.pro/zh-TW/reference/evals/create-scorer) 建立評分器執行個體。不建議直接具現化 `MastraScorer`。 ## 如何取得 `MastraScorer` 執行個體 使用 `createScorer` factory 函式,它會傳回 `MastraScorer` 執行個體: ```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()` 方法是執行評分器並評估輸入/輸出組合的主要方式。它會讓資料依序通過你定義的步驟(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`): 要評估的輸入資料。依評分器的需求,可以是任何型別。 **output** (`any`): 要評估的輸出資料。依評分器的需求,可以是任何型別。 **runId** (`string`): 此次評分執行的選填唯一識別碼。 **requestContext** (`any`): 來自受評估 Agent 或 Workflow 步驟的選填 request context。 **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`): generate score 提示詞(若已定義,選填)。 **generateReasonPrompt** (`string`): generate reason 提示詞(若已定義,選填)。 **judge** (`ScorerJudgeResults`): 以提示詞為基礎的評分器步驟之執行詳情(若有,選填)。 ### 裁判結果 選填的 `judge` 記錄包含以提示詞為基礎的評分器步驟呼叫裁判模型的詳細資訊。已知的 key 為 `preprocess`、`analyze`、`generateScore` 與 `generateReason`。每個 key 都包含依順序排列的 `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[] } > > ``` 使用步驟 key 來存取其裁判執行詳情: ```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` 值描述的是提示詞邏輯步驟的執行結果,而非受評估回應的品質。結構化輸出的後援機制若最終成功,會建立一筆 `success` 執行記錄,且其 `attemptCount` 大於一。若用盡所有嘗試,則會建立一筆 `failed` 執行記錄。 成功的執行需要經過驗證的 `output` 與標準化的 `usage`。失敗的執行需要 `error` 摘要,且只會包含 runtime 收到的證據。只有在後續 callback 或協調作業失敗前已驗證輸出時,失敗的執行才會包含 `output`。Mastra 不會剖析 `rawOutput` 來建立 `output`。 `attemptCount` 計算裁判呼叫次數,其中包括結構化輸出的後援嘗試。`modelCallCount` 計算這些嘗試中已完成的模型步驟數。`durationMs` 涵蓋完整的提示詞步驟執行時間。 函式步驟不會建立 `judge` 項目。此記錄中的用量屬於評分器的裁判模型,而非受評估的 Agent 或 Workflow。彙總成功執行時,請依 `status` 篩選。彙總所有已完成的 Provider 用量時,請包含兩種狀態。選填的 `cost` 欄位只會出現在直接回報具權威性之成本、來源與單位的成功執行記錄上。 使用 Mastra metrics 查詢多次評分器執行的彙總用量、延遲與估計成本。`judge` 記錄只描述一次評分器執行,不會查詢 metrics 或 Trace。 ### 失敗的執行 即使評分器階段失敗,`.run()` promise 仍會遭到拒絕。捕捉 `ScorerRunError`,即可檢查已完成的階段及其產生的任何結果: ```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`): 失敗的評分器階段。 **completedSteps** (`ScorerStepName[]`): 失敗前已完成的評分器階段,依執行順序排列。 **result** (`ScorerRunResultSnapshot | undefined`): 已完成評分器階段的輸出,以及已嘗試之提示詞階段的裁判執行證據。若兩者皆無,此屬性會省略。 `result` 快照包含已完成階段的輸出與裁判執行證據。例如,若 `generateReason` 在 `generateScore` 傳回 `0` 後失敗,`error.result.score` 會是 `0`,`generateScore` 執行的 `status: 'success'`,而 `generateReason` 執行的 `status: 'failed'`。此次執行仍視為失敗。 提示詞失敗時可能建立 `error.result`,其中只包含執行識別資訊、輸入與一筆失敗的 `judge` 項目。若函式階段在產生評分器欄位前失敗,則不會建立結果。 `JSON.stringify(error)` 會使用標準 `MastraError` 序列化方式,並省略 `result`,包括成功與失敗的裁判證據。如需評分器成品或失敗時的原始輸出,請明確讀取 `result`。 記憶體內的實驗結果可保留評分器失敗前已完成的分數或理由,以及 `error`、`failedStep` 與 `completedSteps`。該評分器仍會視為失敗,復原的分數也不會寫入舊版的成功分數儲存空間。 ## 步驟執行流程 呼叫 `.run()` 時,MastraScorer 會依下列順序執行已定義的步驟: 1. **preprocess**(選填):擷取或轉換資料 2. **analyze**(選填):處理輸入/輸出與預先處理過的資料 3. **generateScore**(必要):計算數值分數 4. **generateReason**(選填):提供分數的說明 每個步驟都會收到先前步驟的結果,因此你可以建立複雜的評估 pipeline。 ## 使用範例 ```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/zh-TW/reference/evals/create-scorer)。