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?:
此函式會傳回評分器 builder,你可以對它鏈式呼叫步驟方法。如需 .run() 方法及其輸入/輸出的詳細資訊,請參閱 MastraScorer 參考文件。
judge 只會針對定義為提示詞物件的步驟執行(提示詞模式下的 preprocess、analyze、generateScore、generateReason)。若只使用函式步驟,則絕不會呼叫 judge,也不會有可供檢查的 LLM 輸出。在此情況下,所有分數/理由都必須由你的函式產生。
提示詞物件步驟執行時,其結構化 LLM 輸出會儲存在對應的結果欄位中(preprocessStepResult、analyzeStepResult,或供 calculateScore 在 generateScore 中使用的值)。
重試 judge 要求「重試 judge 要求」的直接連結
使用現有的 judge errorProcessors 設定,在失敗的 judge 要求中重試暫時性失敗。這不會重試評分器 Workflow、Trace 目標、批次項目、分數寫入或已完成的評分器步驟。
@mastra/core 1.49.0 不包含評分器錯誤 Processor 設定。使用此設定前,請升級至支援評分器 Processor 的版本,或向後移植該項特定變更。
下列範例使用一組有上限的重試預算。請將 Processor 的 maxRetries 與 judge.maxProcessorRetries 設為相同值。內部 judge Agent 的模型重試次數請維持預設值 0,避免模型重試導致 Processor 嘗試次數成倍增加。
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 評估的inputMessages、rememberedMessages、systemMessages與taggedSystemMessagesScorerRunOutputForAgent- 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:
[{ role: 'user', content: 'hello world' }]。若在 Workflow 中使用評分器,這會是 Workflow 的輸入。run.output:
run.runId:
run.requestContext?:
results:
傳回值:any
此方法可傳回任何值。傳回值可供後續步驟透過 preprocessStepResult 取得。
提示詞物件模式:
description:
outputSchema:
createPrompt:
judge?:
analyze「analyze」的直接連結
選用的分析步驟,用於處理輸入/輸出及任何預處理資料。
函式模式:
函式:({ 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?:
generateScore「generatescore」的直接連結
計算最終數值分數的必要步驟。
函式模式:
函式:({ 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?:
使用提示詞物件模式時,也必須提供 calculateScore 函式,將 LLM 輸出轉換為數值分數:
calculateScore:
generateReason「generatereason」的直接連結
提供分數說明的選用步驟。
函式模式:
函式:({ 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?:
所有步驟函式都可以是非同步函式。