> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # 答案相似度評分器 `createAnswerSimilarityScorer()` 函式會建立一個評分器,用於評估 Agent 輸出與標準答案的相似程度。此評分器專為 CI/CD 測試情境而設,適合已有預期答案並希望確保結果長期一致的情況。 ## 參數 **model** (`LanguageModel`): 用於評估輸出與標準答案之間語義相似度的語言模型。 **options** (`AnswerSimilarityOptions`): 評分器的設定選項。 **options.requireGroundTruth** (`boolean`): 評估時是否必須提供標準答案。如設為 false,缺少標準答案時會傳回 0 分。 **options.semanticThreshold** (`number`): 語義相符相對於完全相符的權重(0–1)。 **options.exactMatchBonus** (`number`): 完全相符時的額外加分(0–1)。 **options.missingPenalty** (`number`): 每缺少一項標準答案中的關鍵概念所扣的分數。 **options.contradictionPenalty** (`number`): 資訊互相矛盾時所扣的分數。較高的值可確保錯誤答案的分數接近 0。 **options.extraInfoPenalty** (`number`): 包含標準答案中沒有的額外資訊時所扣的少量分數(上限為 0.2)。 **options.scale** (`number`): 分數縮放系數。 此函式會傳回 MastraScorer 類別的實例。`.run()` 方法接受與其他評分器相同的輸入(請參閱 [MastraScorer 參考文件](https://mastra.zisheng.pro/zh-HK/reference/evals/mastra-scorer)),但**必須在執行物件中提供標準答案**。 ## `.run()` 傳回值 **runId** (`string`): 執行的 ID(選填)。 **score** (`number`): 介乎 0–1 的相似度分數(如使用自訂 scale,則為 0–scale)。分數越高,代表與標準答案越相似。 **reason** (`string`): 以易讀方式解釋分數,並提供可採取行動的意見。 **preprocessStepResult** (`object`): 從輸出及標準答案擷取的語義單元。 **analyzeStepResult** (`object`): 相符內容、矛盾內容及額外資訊的詳細分析。 **preprocessPrompt** (`string`): 用於擷取語義單元的提示。 **analyzePrompt** (`string`): 用於分析相似度的提示。 **generateReasonPrompt** (`string`): 用於產生解釋的提示。 ## 評分詳情 評分器採用多步驟流程: 1. **擷取**:將輸出及標準答案拆分為多個語義單元 2. **分析**:比較各單元,並識別相符、矛盾及缺漏的內容 3. **評分**:計算加權相似度,並就矛盾內容扣分 4. **解釋**:產生易讀的解釋 分數計算:`max(0, base_score - contradiction_penalty - missing_penalty - extra_info_penalty) × scale` ## 範例 在不同情境下,評估 Agent 回應與標準答案的相似度: ```typescript import { runEvals } from '@mastra/core/evals' import { createAnswerSimilarityScorer } from '@mastra/evals/scorers/prebuilt' import { myAgent } from './agent' const scorer = createAnswerSimilarityScorer({ model: 'openai/gpt-5.6-sol' }) const result = await runEvals({ data: [ { input: 'What is 2+2?', groundTruth: '4', }, { input: 'What is the capital of France?', groundTruth: 'The capital of France is Paris', }, { input: 'What are the primary colors?', groundTruth: 'The primary colors are red, blue, and yellow', }, ], scorers: [scorer], target: myAgent, onItemComplete: ({ scorerResults }) => { console.log({ score: scorerResults[scorer.id].score, reason: scorerResults[scorer.id].reason, }) }, }) console.log(result.scores) ``` 如要進一步了解 `runEvals`,請參閱 [runEvals 參考文件](https://mastra.zisheng.pro/zh-HK/reference/evals/run-evals)。 如要將此評分器加入 Agent,請參閱[評分器概覽](https://mastra.zisheng.pro/zh-HK/docs/evals/overview)指南。