@mastra/evals 1.10.8-alpha.2 → 1.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{checks-B7c-zPoM.cjs → checks-BX_kIFwJ.cjs} +2 -2
- package/dist/checks-BX_kIFwJ.cjs.map +1 -0
- package/dist/checks.cjs +1 -1
- package/dist/checks.js +1 -2
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/scorers/prebuilt/index.cjs +70 -43
- package/dist/scorers/prebuilt/index.cjs.map +1 -1
- package/dist/scorers/prebuilt/index.js +69 -42
- package/dist/scorers/prebuilt/index.js.map +1 -1
- package/dist/scorers/utils.cjs +18 -15
- package/dist/scorers/utils.cjs.map +1 -1
- package/dist/scorers/utils.js +18 -15
- package/dist/scorers/utils.js.map +1 -1
- package/dist/vitest/index.cjs.map +1 -1
- package/dist/vitest/setup.cjs.map +1 -1
- package/package.json +8 -8
- package/dist/checks-B7c-zPoM.cjs.map +0 -1
|
@@ -15,7 +15,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
15
|
}
|
|
16
16
|
return to;
|
|
17
17
|
};
|
|
18
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
19
19
|
value: mod,
|
|
20
20
|
enumerable: true
|
|
21
21
|
}) : target, mod));
|
|
@@ -489,4 +489,4 @@ Object.defineProperty(exports, "usedNoTools", {
|
|
|
489
489
|
}
|
|
490
490
|
});
|
|
491
491
|
|
|
492
|
-
//# sourceMappingURL=checks-
|
|
492
|
+
//# sourceMappingURL=checks-BX_kIFwJ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checks-BX_kIFwJ.cjs","names":["createScorer","getTextContentFromMastraDBMessage","stringSimilarity","extractToolCalls","mergeToolInvocations"],"sources":["../src/scorers/code/checks/index.ts"],"sourcesContent":["import { createScorer } from '@mastra/core/evals';\nimport stringSimilarity from 'string-similarity';\nimport { extractToolCalls, getTextContentFromMastraDBMessage, mergeToolInvocations } from '../../utils';\n\n// ─── Output Text Checks ───────────────────────────────────────────────────────\n\nexport interface IncludesOptions {\n /** Case-insensitive match (default: true) */\n ignoreCase?: boolean;\n}\n\n/**\n * Scores 1 if the agent's output text contains the expected substring, 0 otherwise.\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.includes('sunny');\n * ```\n */\nexport function includes(expected: string, options: IncludesOptions = {}) {\n const { ignoreCase = true } = options;\n return createScorer({\n id: 'check-includes',\n name: 'Includes Check',\n description: `Checks if output includes \"${expected}\"`,\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n let output = run.output\n .filter(m => m.role === 'assistant')\n .map(m => getTextContentFromMastraDBMessage(m))\n .join(' ');\n let target = expected;\n if (ignoreCase) {\n output = output.toLowerCase();\n target = target.toLowerCase();\n }\n return { output, target, found: output.includes(target) };\n })\n .generateScore(({ results }) => {\n return results.preprocessStepResult?.found ? 1 : 0;\n });\n}\n\n/**\n * Scores 1 if the agent's output text does NOT contain the substring, 0 otherwise.\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.excludes('error');\n * ```\n */\nexport function excludes(unwanted: string, options: IncludesOptions = {}) {\n const { ignoreCase = true } = options;\n return createScorer({\n id: 'check-excludes',\n name: 'Excludes Check',\n description: `Checks that output does not include \"${unwanted}\"`,\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n let output = run.output\n .filter(m => m.role === 'assistant')\n .map(m => getTextContentFromMastraDBMessage(m))\n .join(' ');\n let target = unwanted;\n if (ignoreCase) {\n output = output.toLowerCase();\n target = target.toLowerCase();\n }\n return { output, target, excluded: !output.includes(target) };\n })\n .generateScore(({ results }) => {\n return results.preprocessStepResult?.excluded ? 1 : 0;\n });\n}\n\n/**\n * Scores 1 if the output text exactly equals the expected string (after optional normalization).\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.equals('Hello, world!');\n * ```\n */\nexport function equals(expected: string, options: IncludesOptions = {}) {\n const { ignoreCase = true } = options;\n return createScorer({\n id: 'check-equals',\n name: 'Equals Check',\n description: `Checks if output equals \"${expected}\"`,\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n let output = run.output\n .filter(m => m.role === 'assistant')\n .map(m => getTextContentFromMastraDBMessage(m))\n .join('');\n let target = expected;\n if (ignoreCase) {\n output = output.toLowerCase();\n target = target.toLowerCase();\n }\n return { output, target, isEqual: output === target };\n })\n .generateScore(({ results }) => {\n return results.preprocessStepResult?.isEqual ? 1 : 0;\n });\n}\n\nexport interface MatchesOptions {\n /** If true, the output must match the pattern exactly (anchored). Default: false (substring match). */\n exact?: boolean;\n}\n\n/**\n * Scores 1 if the output matches the given regular expression, 0 otherwise.\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.matches(/\\d{1,3}°[FC]/);\n * ```\n */\nexport function matches(pattern: RegExp, options: MatchesOptions = {}) {\n const { exact = false } = options;\n return createScorer({\n id: 'check-matches',\n name: 'Matches Check',\n description: `Checks if output matches pattern ${pattern}`,\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n const output = run.output\n .filter(m => m.role === 'assistant')\n .map(m => getTextContentFromMastraDBMessage(m))\n .join('');\n const regex = exact ? new RegExp(`^${pattern.source}$`, pattern.flags) : pattern;\n // g/y regexes keep lastIndex between calls, and the scorer is reused across items\n regex.lastIndex = 0;\n const matched = regex.test(output);\n return { output, pattern: pattern.toString(), matched };\n })\n .generateScore(({ results }) => {\n return results.preprocessStepResult?.matched ? 1 : 0;\n });\n}\n\nexport interface SimilarityOptions {\n /** Minimum similarity threshold (0-1) to score 1. Default: 0.7 */\n threshold?: number;\n /** Case-insensitive comparison (default: true) */\n ignoreCase?: boolean;\n}\n\n/**\n * Returns the string similarity score (0-1) between the output and an expected string.\n * Useful for fuzzy matching when exact equality is too strict.\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.similarity('Sunny, 72°F');\n * ```\n */\nexport function similarity(expected: string, options: SimilarityOptions = {}) {\n const { ignoreCase = true, threshold } = options;\n return createScorer({\n id: 'check-similarity',\n name: 'Similarity Check',\n description: `Checks string similarity to \"${expected}\"`,\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n let output = run.output\n .filter(m => m.role === 'assistant')\n .map(m => getTextContentFromMastraDBMessage(m))\n .join(' ');\n let target = expected;\n if (ignoreCase) {\n output = output.toLowerCase();\n target = target.toLowerCase();\n }\n const score = stringSimilarity.compareTwoStrings(output, target);\n return { output, target, score, threshold };\n })\n .generateScore(({ results }) => {\n const score = results.preprocessStepResult?.score ?? 0;\n const t = results.preprocessStepResult?.threshold;\n return t !== undefined ? (score >= t ? 1 : 0) : score;\n });\n}\n\n// ─── Tool Call Checks ─────────────────────────────────────────────────────────\n\nexport interface CalledToolOptions {\n /** Minimum number of times the tool must be called. Default: 1 */\n times?: number;\n}\n\n/**\n * Scores 1 if the agent called the specified tool (at least `times` times).\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.calledTool('get_weather');\n * const twice = checks.calledTool('search', { times: 2 });\n * ```\n */\nexport function calledTool(toolName: string, options: CalledToolOptions = {}) {\n const { times = 1 } = options;\n return createScorer({\n id: 'check-called-tool',\n name: 'Called Tool Check',\n description: `Checks that \"${toolName}\" was called${times > 1 ? ` at least ${times} times` : ''}`,\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n const { tools } = extractToolCalls(run.output);\n const count = tools.filter(t => t === toolName).length;\n return { toolName, expectedTimes: times, actualCount: count, passed: count >= times };\n })\n .generateScore(({ results }) => {\n return results.preprocessStepResult?.passed ? 1 : 0;\n });\n}\n\n/**\n * Scores 1 if the agent did NOT call the specified tool.\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.didNotCall('delete_user');\n * ```\n */\nexport function didNotCall(toolName: string) {\n return createScorer({\n id: 'check-did-not-call',\n name: 'Did Not Call Check',\n description: `Checks that \"${toolName}\" was NOT called`,\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n const { tools } = extractToolCalls(run.output);\n const count = tools.filter(t => t === toolName).length;\n return { toolName, count, passed: count === 0 };\n })\n .generateScore(({ results }) => {\n return results.preprocessStepResult?.passed ? 1 : 0;\n });\n}\n\n/**\n * Scores 1 if the tools were called in the specified order (relaxed: allows other calls in between).\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.toolOrder(['search', 'summarize', 'respond']);\n * ```\n */\nexport function toolOrder(expectedOrder: string[]) {\n return createScorer({\n id: 'check-tool-order',\n name: 'Tool Order Check',\n description: `Checks tool call order: [${expectedOrder.join(' → ')}]`,\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n const { tools } = extractToolCalls(run.output);\n // Check that expectedOrder appears as a subsequence of tools\n let orderIndex = 0;\n for (const tool of tools) {\n if (orderIndex < expectedOrder.length && tool === expectedOrder[orderIndex]) {\n orderIndex++;\n }\n }\n const passed = orderIndex === expectedOrder.length;\n return { actualTools: tools, expectedOrder, passed };\n })\n .generateScore(({ results }) => {\n return results.preprocessStepResult?.passed ? 1 : 0;\n });\n}\n\n/**\n * Scores 1 if the agent used no more than `max` tool calls.\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.maxToolCalls(5);\n * ```\n */\nexport function maxToolCalls(max: number) {\n return createScorer({\n id: 'check-max-tool-calls',\n name: 'Max Tool Calls Check',\n description: `Checks that no more than ${max} tool calls were made`,\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n const { tools } = extractToolCalls(run.output);\n return { count: tools.length, max, passed: tools.length <= max };\n })\n .generateScore(({ results }) => {\n return results.preprocessStepResult?.passed ? 1 : 0;\n });\n}\n\n/**\n * Scores 1 if the agent made no tool calls at all.\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.usedNoTools();\n * ```\n */\nexport function usedNoTools() {\n return createScorer({\n id: 'check-used-no-tools',\n name: 'Used No Tools Check',\n description: 'Checks that no tools were called',\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n const { tools } = extractToolCalls(run.output);\n return { count: tools.length, passed: tools.length === 0 };\n })\n .generateScore(({ results }) => {\n return results.preprocessStepResult?.passed ? 1 : 0;\n });\n}\n\n/**\n * Scores 1 if none of the tool invocations resulted in an error.\n *\n * Treats every failure representation a native run can persist as an error: a\n * thrown call (`state: 'output-error'`), an incomplete call (`state: 'call'`), a\n * result the executor flagged with `isError`, and a result carrying an `error` field.\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n * const scorer = checks.noToolErrors();\n * ```\n */\nexport function noToolErrors() {\n return createScorer({\n id: 'check-no-tool-errors',\n name: 'No Tool Errors Check',\n description: 'Checks that no tool calls resulted in errors',\n type: 'agent',\n })\n .preprocess(async ({ run }) => {\n const invocations = extractRawInvocations(run.output);\n const errorCount = invocations.filter(isErrorInvocation).length;\n return { errorCount, totalCalls: invocations.length, passed: errorCount === 0 };\n })\n .generateScore(({ results }) => {\n return results.preprocessStepResult?.passed ? 1 : 0;\n });\n}\n\n// ─── Internal helpers ──────────────────────────────────────────────────────────\n\n/**\n * True when an invocation represents a tool failure rather than a success.\n *\n * A natively thrown tool call is persisted as `state: 'output-error'` with\n * `errorText`, so keying only on `state: 'call'` or `result.error` lets it pass.\n * `isError` is set alongside `state: 'result'` when the executor reported a failure\n * even though the result carries no `error` field; core's `extractTrajectory`\n * likewise defines success as `state === 'result' && isError !== true`.\n */\nfunction isErrorInvocation(inv: any): boolean {\n return inv.state === 'call' || inv.state === 'output-error' || inv.isError === true || Boolean(inv.result?.error);\n}\n\nfunction extractRawInvocations(output: Parameters<typeof extractToolCalls>[0]) {\n const invocations: any[] = [];\n for (const message of output) {\n // Merge both storage forms so a call present only in `content.parts` — which is\n // where thrown calls live — is never hidden by a legacy `toolInvocations` array.\n for (const inv of mergeToolInvocations(message)) {\n if (inv) invocations.push(inv);\n }\n }\n return invocations;\n}\n\n// ─── Convenience namespace ────────────────────────────────────────────────────\n\n/**\n * Quick Checks — composable micro-scorers for common assertions.\n *\n * These are zero-LLM, zero-ceremony scorers that plug into the existing\n * `scorers: [...]` array anywhere scorers are used. Internally they are\n * standard `createScorer()` instances with the same observability, storage,\n * and pipeline integration as any other scorer.\n *\n * @example\n * ```ts\n * import { checks } from '@mastra/evals';\n *\n * await runEvals({\n * data: [...],\n * target: myAgent,\n * scorers: [\n * checks.includes('sunny'),\n * checks.calledTool('get_weather'),\n * checks.toolOrder(['search', 'summarize']),\n * checks.noToolErrors(),\n * ],\n * });\n * ```\n */\nexport const checks = {\n includes,\n excludes,\n equals,\n matches,\n similarity,\n calledTool,\n didNotCall,\n toolOrder,\n maxToolCalls,\n usedNoTools,\n noToolErrors,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,SAAS,UAAkB,UAA2B,CAAC,GAAG;CACxE,MAAM,EAAE,aAAa,SAAS;CAC9B,QAAA,GAAOA,mBAAAA,aAAAA,CAAa;EAClB,IAAI;EACJ,MAAM;EACN,aAAa,8BAA8B,SAAS;EACpD,MAAM;CACR,CAAC,CAAC,CACC,WAAW,OAAO,EAAE,UAAU;EAC7B,IAAI,SAAS,IAAI,OACd,QAAO,MAAK,EAAE,SAAS,WAAW,CAAC,CACnC,KAAI,MAAKC,sBAAAA,kCAAkC,CAAC,CAAC,CAAC,CAC9C,KAAK,GAAG;EACX,IAAI,SAAS;EACb,IAAI,YAAY;GACd,SAAS,OAAO,YAAY;GAC5B,SAAS,OAAO,YAAY;EAC9B;EACA,OAAO;GAA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C7B,MAAM,EAAE,UAAUG,sBAAAA,iBAAiB,IAAI,MAAM;EAC7C,OAAO;GAAE,OAAO,MAAM;GAAQ,QAAQ,MAAM,WAAW;EAAE;CAC3D,CAAC,CAAC,CACD,eAAe,EAAE,cAAc;EAC9B,OAAO,QAAQ,sBAAsB,SAAS,IAAI;CACpD,CAAC;AACL;;;;;;;;;;;;;;AAeA,SAAgB,eAAe;CAC7B,QAAA,GAAOH,mBAAAA,aAAAA,CAAa;EAClB,IAAI;EACJ,MAAM;EACN,aAAa;EACb,MAAM;CACR,CAAC,CAAC,CACC,WAAW,OAAO,EAAE,UAAU;EAC7B,MAAM,cAAc,sBAAsB,IAAI,MAAM;EACpD,MAAM,aAAa,YAAY,OAAO,iBAAiB,CAAC,CAAC;EACzD,OAAO;GAAE;GAAY,YAAY,YAAY;GAAQ,QAAQ,eAAe;EAAE;CAChF,CAAC,CAAC,CACD,eAAe,EAAE,cAAc;EAC9B,OAAO,QAAQ,sBAAsB,SAAS,IAAI;CACpD,CAAC;AACL;;;;;;;;;;AAaA,SAAS,kBAAkB,KAAmB;CAC5C,OAAO,IAAI,UAAU,UAAU,IAAI,UAAU,kBAAkB,IAAI,YAAY,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAClH;AAEA,SAAS,sBAAsB,QAAgD;CAC7E,MAAM,cAAqB,CAAC;CAC5B,KAAK,MAAM,WAAW,QAGpB,KAAK,MAAM,OAAOI,sBAAAA,qBAAqB,OAAO,GAC5C,IAAI,KAAK,YAAY,KAAK,GAAG;CAGjC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,SAAS;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
package/dist/checks.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_checks = require("./checks-
|
|
2
|
+
const require_checks = require("./checks-BX_kIFwJ.cjs");
|
|
3
3
|
exports.calledTool = require_checks.calledTool;
|
|
4
4
|
exports.checks = require_checks.checks;
|
|
5
5
|
exports.didNotCall = require_checks.didNotCall;
|
package/dist/checks.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { calledTool, checks, didNotCall, equals, excludes, includes, matches, maxToolCalls, noToolErrors, similarity, toolOrder, usedNoTools };
|
|
1
|
+
export { t as calledTool, n as checks, r as didNotCall, i as equals, a as excludes, o as includes, s as matches, c as maxToolCalls, l as noToolErrors, u as similarity, d as toolOrder, f as usedNoTools } from "./checks-DxbqoaYq.js";
|
package/dist/docs/SKILL.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_checks = require("../../checks-
|
|
2
|
+
const require_checks = require("../../checks-BX_kIFwJ.cjs");
|
|
3
3
|
const require_scorers_utils = require("../utils.cjs");
|
|
4
4
|
let _mastra_core_evals = require("@mastra/core/evals");
|
|
5
5
|
let compromise = require("compromise");
|
|
@@ -231,7 +231,8 @@ function createAnswerRelevancyScorer({ model, options = DEFAULT_OPTIONS }) {
|
|
|
231
231
|
description: "Extract relevant statements from the LLM output",
|
|
232
232
|
outputSchema: extractOutputSchema$1,
|
|
233
233
|
createPrompt: ({ run }) => {
|
|
234
|
-
|
|
234
|
+
const assistantMessage = require_scorers_utils.getAssistantMessageFromRunOutput(run.output) ?? "";
|
|
235
|
+
return createExtractPrompt$1(assistantMessage);
|
|
235
236
|
}
|
|
236
237
|
}).analyze({
|
|
237
238
|
description: "Score the relevance of the statements to the input",
|
|
@@ -261,7 +262,8 @@ function createAnswerRelevancyScorer({ model, options = DEFAULT_OPTIONS }) {
|
|
|
261
262
|
let relevancyCount = 0;
|
|
262
263
|
for (const { result } of results.analyzeStepResult.results) if (result.trim().toLowerCase() === "yes") relevancyCount++;
|
|
263
264
|
else if (result.trim().toLowerCase() === "unsure") relevancyCount += options.uncertaintyWeight;
|
|
264
|
-
|
|
265
|
+
const score = relevancyCount / numberOfResults;
|
|
266
|
+
return require_scorers_utils.roundToTwoDecimals(score * options.scale);
|
|
265
267
|
}).generateReason({
|
|
266
268
|
description: "Reason about the results",
|
|
267
269
|
createPrompt: ({ run, results, score }) => {
|
|
@@ -503,18 +505,22 @@ function createAnswerSimilarityScorer({ model, options = ANSWER_SIMILARITY_DEFAU
|
|
|
503
505
|
groundTruth: ""
|
|
504
506
|
});
|
|
505
507
|
}
|
|
508
|
+
const output = require_scorers_utils.getAssistantMessageFromRunOutput(run.output) ?? "";
|
|
509
|
+
const groundTruth = typeof run.groundTruth === "string" ? run.groundTruth : JSON.stringify(run.groundTruth);
|
|
506
510
|
return createExtractPrompt({
|
|
507
|
-
output
|
|
508
|
-
groundTruth
|
|
511
|
+
output,
|
|
512
|
+
groundTruth
|
|
509
513
|
});
|
|
510
514
|
}
|
|
511
515
|
}).analyze({
|
|
512
516
|
description: "Compare semantic units between output and ground truth",
|
|
513
517
|
outputSchema: analyzeOutputSchema$7,
|
|
514
518
|
createPrompt: ({ results }) => {
|
|
519
|
+
const outputUnits = results.preprocessStepResult?.outputUnits || [];
|
|
520
|
+
const groundTruthUnits = results.preprocessStepResult?.groundTruthUnits || [];
|
|
515
521
|
return createAnalyzePrompt$7({
|
|
516
|
-
outputUnits
|
|
517
|
-
groundTruthUnits
|
|
522
|
+
outputUnits,
|
|
523
|
+
groundTruthUnits
|
|
518
524
|
});
|
|
519
525
|
}
|
|
520
526
|
}).generateScore(({ run, results }) => {
|
|
@@ -534,9 +540,7 @@ function createAnswerSimilarityScorer({ model, options = ANSWER_SIMILARITY_DEFAU
|
|
|
534
540
|
case "partial":
|
|
535
541
|
score += mergedOptions.semanticThreshold * .5;
|
|
536
542
|
break;
|
|
537
|
-
case "missing":
|
|
538
|
-
score -= mergedOptions.missingPenalty;
|
|
539
|
-
break;
|
|
543
|
+
case "missing": score -= mergedOptions.missingPenalty;
|
|
540
544
|
}
|
|
541
545
|
const maxPossibleScore = totalUnits * (1 + mergedOptions.exactMatchBonus);
|
|
542
546
|
score = score / maxPossibleScore;
|
|
@@ -550,9 +554,11 @@ function createAnswerSimilarityScorer({ model, options = ANSWER_SIMILARITY_DEFAU
|
|
|
550
554
|
description: "Generate explanation of similarity score",
|
|
551
555
|
createPrompt: ({ run, results, score }) => {
|
|
552
556
|
if (!run.groundTruth) return "No ground truth was provided for comparison. Score is 0 by default.";
|
|
557
|
+
const output = require_scorers_utils.getAssistantMessageFromRunOutput(run.output) ?? "";
|
|
558
|
+
const groundTruth = typeof run.groundTruth === "string" ? run.groundTruth : JSON.stringify(run.groundTruth);
|
|
553
559
|
return createReasonPrompt$5({
|
|
554
|
-
output
|
|
555
|
-
groundTruth
|
|
560
|
+
output,
|
|
561
|
+
groundTruth,
|
|
556
562
|
score,
|
|
557
563
|
analysis: results.analyzeStepResult,
|
|
558
564
|
scale: mergedOptions.scale
|
|
@@ -766,7 +772,8 @@ function createFaithfulnessScorer({ model, options }) {
|
|
|
766
772
|
const totalClaims = results.preprocessStepResult?.claims?.length || verdicts.length;
|
|
767
773
|
const supportedClaims = verdicts.filter((v) => v.verdict.toLowerCase().trim() === "yes").length;
|
|
768
774
|
if (totalClaims === 0) return 0;
|
|
769
|
-
|
|
775
|
+
const score = Math.min(1, supportedClaims / totalClaims) * (options?.scale || 1);
|
|
776
|
+
return require_scorers_utils.roundToTwoDecimals(score);
|
|
770
777
|
}).generateReason({
|
|
771
778
|
description: "Reason about the results",
|
|
772
779
|
createPrompt: ({ run, results, score }) => {
|
|
@@ -936,7 +943,8 @@ function createBiasScorer({ model, options }) {
|
|
|
936
943
|
}
|
|
937
944
|
}).generateScore(({ results }) => {
|
|
938
945
|
if (!results.analyzeStepResult || results.analyzeStepResult.results.length === 0) return 0;
|
|
939
|
-
|
|
946
|
+
const score = results.analyzeStepResult.results.filter((v) => v.result.toLowerCase() === "yes").length / results.analyzeStepResult.results.length;
|
|
947
|
+
return require_scorers_utils.roundToTwoDecimals(score * (options?.scale || 1));
|
|
940
948
|
}).generateReason({
|
|
941
949
|
description: "Reason about the results",
|
|
942
950
|
createPrompt: ({ score, results }) => {
|
|
@@ -1194,7 +1202,8 @@ function createHallucinationScorer({ model, options }) {
|
|
|
1194
1202
|
const totalStatements = results.preprocessStepResult?.claims?.length || verdicts.length;
|
|
1195
1203
|
const contradictedStatements = verdicts.filter((v) => v.verdict.toLowerCase().trim() === "yes").length;
|
|
1196
1204
|
if (totalStatements === 0) return 0;
|
|
1197
|
-
|
|
1205
|
+
const score = Math.min(1, contradictedStatements / totalStatements) * (options?.scale || 1);
|
|
1206
|
+
return require_scorers_utils.roundToTwoDecimals(score);
|
|
1198
1207
|
}).generateReason({
|
|
1199
1208
|
description: "Reason about the results",
|
|
1200
1209
|
createPrompt: async ({ run, results, score }) => {
|
|
@@ -1342,7 +1351,8 @@ function createToxicityScorer({ model, options }) {
|
|
|
1342
1351
|
if (numberOfVerdicts === 0) return 1;
|
|
1343
1352
|
let toxicityCount = 0;
|
|
1344
1353
|
for (const { verdict } of results.analyzeStepResult.verdicts) if (verdict.trim().toLowerCase() === "yes") toxicityCount++;
|
|
1345
|
-
|
|
1354
|
+
const score = toxicityCount / numberOfVerdicts;
|
|
1355
|
+
return require_scorers_utils.roundToTwoDecimals(score * (options?.scale || 1));
|
|
1346
1356
|
}).generateReason({
|
|
1347
1357
|
description: "Reason about the results",
|
|
1348
1358
|
createPrompt: ({ results, score }) => {
|
|
@@ -1490,10 +1500,13 @@ function createToolCallAccuracyScorerLLM({ model, availableTools }) {
|
|
|
1490
1500
|
description: "Analyze the appropriateness of tool selections",
|
|
1491
1501
|
outputSchema: analyzeOutputSchema$6,
|
|
1492
1502
|
createPrompt: ({ run, results }) => {
|
|
1503
|
+
const userInput = require_scorers_utils.getUserMessageFromRunInput(run.input) ?? "";
|
|
1504
|
+
const agentResponse = require_scorers_utils.getAssistantMessageFromRunOutput(run.output) ?? "";
|
|
1505
|
+
const toolsCalled = results.preprocessStepResult?.actualTools || [];
|
|
1493
1506
|
return createAnalyzePrompt$6({
|
|
1494
|
-
userInput
|
|
1495
|
-
agentResponse
|
|
1496
|
-
toolsCalled
|
|
1507
|
+
userInput,
|
|
1508
|
+
agentResponse,
|
|
1509
|
+
toolsCalled,
|
|
1497
1510
|
availableTools: toolDefinitions
|
|
1498
1511
|
});
|
|
1499
1512
|
}
|
|
@@ -1506,11 +1519,14 @@ function createToolCallAccuracyScorerLLM({ model, availableTools }) {
|
|
|
1506
1519
|
}).generateReason({
|
|
1507
1520
|
description: "Generate human-readable explanation of tool selection evaluation",
|
|
1508
1521
|
createPrompt: ({ run, results, score }) => {
|
|
1522
|
+
const userInput = require_scorers_utils.getUserMessageFromRunInput(run.input) ?? "";
|
|
1523
|
+
const evaluations = results.analyzeStepResult?.evaluations || [];
|
|
1524
|
+
const missingTools = results.analyzeStepResult?.missingTools || [];
|
|
1509
1525
|
return createReasonPrompt$4({
|
|
1510
|
-
userInput
|
|
1526
|
+
userInput,
|
|
1511
1527
|
score,
|
|
1512
|
-
evaluations
|
|
1513
|
-
missingTools
|
|
1528
|
+
evaluations,
|
|
1529
|
+
missingTools
|
|
1514
1530
|
});
|
|
1515
1531
|
}
|
|
1516
1532
|
});
|
|
@@ -1772,7 +1788,8 @@ function createContextRelevanceScorerLLM({ model, options }) {
|
|
|
1772
1788
|
const usagePenalty = highRelevanceUnused * unusedPenaltyRate;
|
|
1773
1789
|
const missingContext = results.analyzeStepResult?.missingContext || [];
|
|
1774
1790
|
const missingContextPenalty = Math.min(missingContext.length * missingPenaltyRate, maxMissingPenalty);
|
|
1775
|
-
|
|
1791
|
+
const scaledScore = Math.max(0, relevanceScore - usagePenalty - missingContextPenalty) * (options.scale || 1);
|
|
1792
|
+
return require_scorers_utils.roundToTwoDecimals(scaledScore);
|
|
1776
1793
|
}).generateReason({
|
|
1777
1794
|
description: "Generate human-readable explanation of context relevance evaluation",
|
|
1778
1795
|
createPrompt: ({ run, results, score }) => {
|
|
@@ -1969,7 +1986,8 @@ function createContextPrecisionScorer({ model, options }) {
|
|
|
1969
1986
|
sumPrecision += precisionAtI;
|
|
1970
1987
|
}
|
|
1971
1988
|
if (relevantCount === 0) return 0;
|
|
1972
|
-
|
|
1989
|
+
const score = sumPrecision / relevantCount * (options.scale || 1);
|
|
1990
|
+
return require_scorers_utils.roundToTwoDecimals(score);
|
|
1973
1991
|
}).generateReason({
|
|
1974
1992
|
description: "Reason about the context precision results",
|
|
1975
1993
|
createPrompt: ({ run, results, score }) => {
|
|
@@ -2191,7 +2209,8 @@ function createContextRecallScorer({ model, options }) {
|
|
|
2191
2209
|
const totalClaims = results.preprocessStepResult?.claims?.length ?? 0;
|
|
2192
2210
|
if (totalClaims === 0) return 0;
|
|
2193
2211
|
const attributedClaims = (results.analyzeStepResult?.verdicts || []).filter((v) => v.verdict.toLowerCase().trim() === "yes").length;
|
|
2194
|
-
|
|
2212
|
+
const score = Math.min(1, attributedClaims / totalClaims) * (options.scale || 1);
|
|
2213
|
+
return require_scorers_utils.roundToTwoDecimals(score);
|
|
2195
2214
|
}).generateReason({
|
|
2196
2215
|
description: "Explain the context recall evaluation results",
|
|
2197
2216
|
createPrompt: ({ run, results, score }) => {
|
|
@@ -3044,7 +3063,8 @@ function createPromptAlignmentScorerLLM({ model, options }) {
|
|
|
3044
3063
|
const systemScore = userScore;
|
|
3045
3064
|
weightedScore = userScore * SCORING_WEIGHTS.BOTH.USER_WEIGHT + systemScore * SCORING_WEIGHTS.BOTH.SYSTEM_WEIGHT;
|
|
3046
3065
|
}
|
|
3047
|
-
|
|
3066
|
+
const finalScore = weightedScore * scale;
|
|
3067
|
+
return require_scorers_utils.roundToTwoDecimals(finalScore);
|
|
3048
3068
|
}).generateReason({
|
|
3049
3069
|
description: "Generate human-readable explanation of prompt alignment evaluation",
|
|
3050
3070
|
createPrompt: ({ run, results, score }) => {
|
|
@@ -3883,17 +3903,18 @@ function createTrajectoryAccuracyScorerLLM({ model, expectedTrajectory: staticEx
|
|
|
3883
3903
|
}).preprocess(async ({ run }) => {
|
|
3884
3904
|
const actualTrajectory = run.output;
|
|
3885
3905
|
let expectedSteps;
|
|
3886
|
-
if (staticExpectedTrajectory)
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
const
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
|
|
3896
|
-
|
|
3906
|
+
if (staticExpectedTrajectory) {
|
|
3907
|
+
if (Array.isArray(staticExpectedTrajectory)) expectedSteps = staticExpectedTrajectory;
|
|
3908
|
+
else {
|
|
3909
|
+
const toExpectedStep = (s) => {
|
|
3910
|
+
const { durationMs: _, metadata: _m, children, ...rest } = s;
|
|
3911
|
+
const result = rest;
|
|
3912
|
+
if (children && children.length > 0) result.children = { steps: children.map(toExpectedStep) };
|
|
3913
|
+
return result;
|
|
3914
|
+
};
|
|
3915
|
+
expectedSteps = staticExpectedTrajectory.steps.map(toExpectedStep);
|
|
3916
|
+
}
|
|
3917
|
+
} else if (run.expectedTrajectory) {
|
|
3897
3918
|
const expectation = run.expectedTrajectory;
|
|
3898
3919
|
expectedSteps = expectation.steps && expectation.steps.length > 0 ? expectation.steps : void 0;
|
|
3899
3920
|
}
|
|
@@ -3907,9 +3928,11 @@ function createTrajectoryAccuracyScorerLLM({ model, expectedTrajectory: staticEx
|
|
|
3907
3928
|
description: "Analyze the quality and appropriateness of the agent trajectory",
|
|
3908
3929
|
outputSchema: analyzeOutputSchema,
|
|
3909
3930
|
createPrompt: ({ run, results }) => {
|
|
3931
|
+
const userInput = require_scorers_utils.getUserMessageFromRunInput(run.input) ?? "";
|
|
3932
|
+
const agentResponse = require_scorers_utils.getAssistantMessageFromRunOutput(run.output.rawOutput) ?? "";
|
|
3910
3933
|
return createAnalyzePrompt({
|
|
3911
|
-
userInput
|
|
3912
|
-
agentResponse
|
|
3934
|
+
userInput,
|
|
3935
|
+
agentResponse,
|
|
3913
3936
|
actualTrajectory: results.preprocessStepResult?.actualTrajectoryFormatted ?? "No steps taken",
|
|
3914
3937
|
expectedTrajectory: results.preprocessStepResult?.expectedTrajectoryFormatted
|
|
3915
3938
|
});
|
|
@@ -3935,12 +3958,16 @@ function createTrajectoryAccuracyScorerLLM({ model, expectedTrajectory: staticEx
|
|
|
3935
3958
|
}).generateReason({
|
|
3936
3959
|
description: "Generate human-readable explanation of trajectory evaluation",
|
|
3937
3960
|
createPrompt: ({ run, results, score }) => {
|
|
3961
|
+
const userInput = require_scorers_utils.getUserMessageFromRunInput(run.input) ?? "";
|
|
3962
|
+
const stepEvaluations = results.analyzeStepResult?.stepEvaluations || [];
|
|
3963
|
+
const missingSteps = results.analyzeStepResult?.missingSteps || [];
|
|
3964
|
+
const extraSteps = results.analyzeStepResult?.extraSteps || [];
|
|
3938
3965
|
return createReasonPrompt({
|
|
3939
|
-
userInput
|
|
3966
|
+
userInput,
|
|
3940
3967
|
score,
|
|
3941
|
-
stepEvaluations
|
|
3942
|
-
missingSteps
|
|
3943
|
-
extraSteps
|
|
3968
|
+
stepEvaluations,
|
|
3969
|
+
missingSteps,
|
|
3970
|
+
extraSteps
|
|
3944
3971
|
});
|
|
3945
3972
|
}
|
|
3946
3973
|
});
|