跳至主要內容

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:

string
評分器的唯一識別碼。若未提供 name,會以此值作為名稱。

name?:

string
評分器名稱。若未提供,預設為 id

description:

string
評分器功能的說明。

judge?:

object
以 LLM 為基礎之步驟的選用 judge 設定。
object

model:

LanguageModel
用於評估的 LLM 模型執行個體。

instructions:

string
提供給 LLM 的系統提示詞/指示。

jsonPromptInjection?:

boolean | 'system' | 'inline' | 'auto'
控制 judge 的結構化輸出 schema 如何傳遞給模型。預設為 'auto';模型支援時使用原生結構化輸出,否則在提示詞內嵌入 schema。明確設定的值會覆寫自動路由。

inputProcessors?:

Processor[]
在內部 judge Agent 的訊息送達模型前,套用至訊息的輸入 Processor(例如遮蔽、驗證)。

outputProcessors?:

Processor[]
在傳回內部 judge Agent 的輸出前,套用至輸出的 Processor(例如內容審核、轉換)。

errorProcessors?:

Processor[]
適用於使用 Mastra 目前生成 API 的 judge 模型之錯誤 Processor。這些 Processor 會實作 processAPIError,可檢查 LLM API 拒絕要求的情況並發出重試訊號,例如 StreamErrorRetryProcessor。舊版模型轉接器使用 generateLegacy(),不會執行錯誤 Processor。

maxProcessorRetries?:

number
錯誤 Processor 可針對一次 judge 生成重試的次數上限。若已設定 errorProcessors 但未提供此值,執行階段預設為 10。請明確設定此值,以限制重試預算。

type?:

string
輸入/輸出的型別規格。使用 'agent' 可自動取得 Agent 型別。自訂型別請改用泛型方式。

prepareRun?:

(run: ScorerRun) => ScorerRun | Promise<ScorerRun>
在管線執行前轉換評分器的執行資料。可用於篩選訊息、限制上下文大小,或移除評分器不需要的欄位。`filterRun()` 公用程式可根據宣告式選項建立此函式。此函式可以是非同步函式。

此函式會傳回評分器 builder,你可以對它鏈式呼叫步驟方法。如需 .run() 方法及其輸入/輸出的詳細資訊,請參閱 MastraScorer 參考文件

judge 只會針對定義為提示詞物件的步驟執行(提示詞模式下的 preprocessanalyzegenerateScoregenerateReason)。若只使用函式步驟,則絕不會呼叫 judge,也不會有可供檢查的 LLM 輸出。在此情況下,所有分數/理由都必須由你的函式產生。

提示詞物件步驟執行時,其結構化 LLM 輸出會儲存在對應的結果欄位中(preprocessStepResultanalyzeStepResult,或供 calculateScoregenerateScore 中使用的值)。

重試 judge 要求
「重試 judge 要求」的直接連結

使用現有的 judge errorProcessors 設定,在失敗的 judge 要求中重試暫時性失敗。這不會重試評分器 Workflow、Trace 目標、批次項目、分數寫入或已完成的評分器步驟。

@mastra/core 1.49.0 不包含評分器錯誤 Processor 設定。使用此設定前,請升級至支援評分器 Processor 的版本,或向後移植該項特定變更。

下列範例使用一組有上限的重試預算。請將 Processor 的 maxRetriesjudge.maxProcessorRetries 設為相同值。內部 judge Agent 的模型重試次數請維持預設值 0,避免模型重試導致 Processor 嘗試次數成倍增加。

src/mastra/scorers/response-quality.ts
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 嘗試三次:第一次要求加上兩次 Processor 重試。若 generateScore 已完成,而 generateReason 遇到可重試的失敗,則只會重試 generateReason

StreamErrorRetryProcessor 會遵循 Provider 的可重試中繼資料與範圍明確的自訂 matcher。它預設停用 retryUnknownErrors,因此除非明確比對,否則驗證、無效要求及上下文長度錯誤都會立即失敗。它預設會將 Retry-After 值限制在 30_000 毫秒內。使用 maxRetryAfterMs 可變更此上限。

請避免加入外層評分器或 Workflow 重試。除非有意接受額外嘗試次數,否則請避免將非零的模型重試設定與此 Processor 搭配使用。

覆寫單一步驟的重試設定
「覆寫單一步驟的重試設定」的直接連結

步驟的 judge 設定會覆寫評分器層級的 judge 欄位。Processor 陣列會取代評分器層級的陣列。在步驟設定中省略 maxProcessorRetries,即可繼承評分器層級的數值上限。

協調 Processor 重試需要 judge 模型使用 Mastra 目前的生成 API。舊版模型轉接器會呼叫 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 評估的 inputMessagesrememberedMessagessystemMessagestaggedSystemMessages
  • 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,
},
})

步驟方法簽章
「步驟方法簽章」的直接連結

preprocess
「preprocess」的直接連結

選用的預處理步驟,可在分析前擷取或轉換資料。

函式模式: 函式:({ run, results }) => any

run.input:

any
提供給評分器的輸入記錄。若將評分器加入 Agent,這會是使用者訊息陣列,例如 [{ role: 'user', content: 'hello world' }]。若在 Workflow 中使用評分器,這會是 Workflow 的輸入。

run.output:

any
提供給評分器的輸出記錄。對 Agent 而言,通常是 Agent 的回應;對 Workflow 而言,則是 Workflow 的輸出。

run.runId:

string
此次評分執行的唯一識別碼。

run.requestContext?:

object
來自受評估 Agent 或 Workflow 步驟的 Request Context(選填)。

results:

object
空物件(沒有先前步驟)。

傳回值:any
此方法可傳回任何值。傳回值可供後續步驟透過 preprocessStepResult 取得。

提示詞物件模式:

description:

string
此預處理步驟功能的說明。

outputSchema:

StandardJSONSchemaV1
預處理步驟預期輸出的標準 JSON Schema。

createPrompt:

function
函式:({ run, results }) => string。傳回提供給 LLM 的提示詞。

judge?:

object
此步驟選用的 LLM judge(可覆寫主要 judge)。請參閱 Judge 物件一節。

analyze
「analyze」的直接連結

選用的分析步驟,用於處理輸入/輸出及任何預處理資料。

函式模式: 函式:({ run, results }) => any

run.input:

any
提供給評分器的輸入記錄。若將評分器加入 Agent,這會是使用者訊息陣列,例如 [{ role: 'user', content: 'hello world' }]。若在 Workflow 中使用評分器,這會是 Workflow 的輸入。

run.output:

any
提供給評分器的輸出記錄。對 Agent 而言,通常是 Agent 的回應;對 Workflow 而言,則是 Workflow 的輸出。

run.runId:

string
此次評分執行的唯一識別碼。

run.requestContext?:

object
來自受評估 Agent 或 Workflow 步驟的 Request Context(選填)。

results.preprocessStepResult?:

any
預處理步驟的結果(若有定義,選填)。

傳回值:any
此方法可傳回任何值。傳回值可供後續步驟透過 analyzeStepResult 取得。

提示詞物件模式:

description:

string
此分析步驟功能的說明。

outputSchema:

StandardJSONSchemaV1
分析步驟預期輸出的標準 JSON Schema。

createPrompt:

function
函式:({ run, results }) => string。傳回提供給 LLM 的提示詞。

judge?:

object
此步驟選用的 LLM judge(可覆寫主要 judge)。請參閱 Judge 物件一節。

generateScore
「generatescore」的直接連結

計算最終數值分數的必要步驟。

函式模式: 函式:({ run, results }) => number

run.input:

any
提供給評分器的輸入記錄。若將評分器加入 Agent,這會是使用者訊息陣列,例如 [{ role: 'user', content: 'hello world' }]。若在 Workflow 中使用評分器,這會是 Workflow 的輸入。

run.output:

any
提供給評分器的輸出記錄。對 Agent 而言,通常是 Agent 的回應;對 Workflow 而言,則是 Workflow 的輸出。

run.runId:

string
此次評分執行的唯一識別碼。

run.requestContext?:

object
來自受評估 Agent 或 Workflow 步驟的 Request Context(選填)。

results.preprocessStepResult?:

any
預處理步驟的結果(若有定義,選填)。

results.analyzeStepResult?:

any
分析步驟的結果(若有定義,選填)。

傳回值:number
此方法必須傳回數值分數。

提示詞物件模式:

description:

string
此評分步驟功能的說明。

outputSchema:

StandardJSONSchemaV1
generateScore 步驟預期輸出的標準 JSON Schema。

createPrompt:

function
函式:({ run, results }) => string。傳回提供給 LLM 的提示詞。

judge?:

object
此步驟選用的 LLM judge(可覆寫主要 judge)。請參閱 Judge 物件一節。

使用提示詞物件模式時,也必須提供 calculateScore 函式,將 LLM 輸出轉換為數值分數:

calculateScore:

function
函式:({ run, results, analyzeStepResult }) => number。將 LLM 的結構化輸出轉換為數值分數。

generateReason
「generatereason」的直接連結

提供分數說明的選用步驟。

函式模式: 函式:({ run, results, score }) => string

run.input:

any
提供給評分器的輸入記錄。若將評分器加入 Agent,這會是使用者訊息陣列,例如 [{ role: 'user', content: 'hello world' }]。若在 Workflow 中使用評分器,這會是 Workflow 的輸入。

run.output:

any
提供給評分器的輸出記錄。對 Agent 而言,通常是 Agent 的回應;對 Workflow 而言,則是 Workflow 的輸出。

run.runId:

string
此次評分執行的唯一識別碼。

run.requestContext?:

object
來自受評估 Agent 或 Workflow 步驟的 Request Context(選填)。

results.preprocessStepResult?:

any
預處理步驟的結果(若有定義,選填)。

results.analyzeStepResult?:

any
分析步驟的結果(若有定義,選填)。

score:

number
由 generateScore 步驟計算出的分數。

傳回值:string
此方法必須傳回說明分數的字串。

提示詞物件模式:

description:

string
此理由產生步驟功能的說明。

createPrompt:

function
函式:({ run, results, score }) => string。傳回提供給 LLM 的提示詞。

judge?:

object
此步驟選用的 LLM judge(可覆寫主要 judge)。請參閱 Judge 物件一節。

所有步驟函式都可以是非同步函式。