> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # MastraScorer `MastraScorer` 類別是 Mastra 中所有評分器的基礎類別。它提供標準 `.run()` 方法來評估輸入/輸出配對,並支援依 preprocess → analyze → generateScore → generateReason 執行流程運作的多步驟評分 Workflow。 大部分使用者都應使用 [`createScorer`](https://mastra.zisheng.pro/zh-HK/reference/evals/create-scorer) 建立評分器實例。不建議直接實例化 `MastraScorer`。 ## 如何取得 `MastraScorer` 實例 使用 `createScorer` 工廠函式,它會傳回一個 `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 步驟的可選請求情境。 **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`): 以提示為基礎的評分器步驟之執行詳情(如有;可選)。 ### Judge 結果 可選的 `judge` 記錄包含以提示為基礎的評分器步驟所作 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` 大於一的 `success` 執行記錄。用盡所有嘗試後,則會建立一筆 `failed` 執行記錄。 成功的執行必須具備已驗證的 `output` 及標準化的 `usage`。失敗的執行必須具備 `error` 摘要,並只包含執行階段收到的證據。只有在輸出已通過驗證,但其後的回呼或編排失敗時,失敗的執行才會包含 `output`。Mastra 不會剖析 `rawOutput` 來建立 `output`。 `attemptCount` 計算 judge 調用次數,包括結構化輸出後備機制。`modelCallCount` 計算這些嘗試中已完成的模型步驟數目。`durationMs` 涵蓋整個提示步驟的執行時間。 函式步驟不會建立 `judge` 項目。此記錄中的用量屬於評分器的 judge 模型,而非受評估的 Agent 或 Workflow。彙總成功執行時,請按 `status` 篩選。彙總所有已完成的 Provider 用量時,請包括兩種狀態。可選的 `cost` 欄位只會出現在直接報告具權威性的成本、來源及單位之成功執行中。 使用 Mastra 指標查詢各次評分器執行的彙總用量、延遲及估算成本。`judge` 記錄描述單次評分器執行,並不會查詢指標或 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`): 已完成評分器階段的輸出,以及曾嘗試的提示階段之 judge 執行證據。兩者皆無時會省略此屬性。 `result` 快照包含已完成階段的輸出及 judge 執行證據。例如,如果 `generateScore` 傳回 `0` 後 `generateReason` 失敗,`error.result.score` 會是 `0`,`generateScore` 執行的 `status: 'success'`,而 `generateReason` 執行的 `status: 'failed'`。整次執行仍視為失敗。 提示失敗時,可以建立只包含執行識別資料、輸入及失敗 `judge` 項目的 `error.result`。函式階段若在產生評分器欄位前失敗,則不會建立結果。 `JSON.stringify(error)` 會使用標準 `MastraError` 序列化,並省略 `result`,包括成功及失敗的 judge 證據。需要評分器產出內容或原始失敗輸出時,請明確讀取 `result`。 記憶體內的實驗結果可保留失敗評分器已完成的分數或理由,以及 `error`、`failedStep` 和 `completedSteps`。該評分器仍視為失敗,而復原的分數不會寫入舊有的成功分數儲存空間。 ## 步驟執行流程 呼叫 `.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/zh-HK/reference/evals/create-scorer)。