@mastra/evals 1.10.8-alpha.1 → 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.
@@ -1,4 +1,4 @@
1
- import { analyzeToolFailures, checkTrajectoryBlacklist, checkTrajectoryEfficiency, compareTrajectories, extractAgentResponseMessages, extractToolCalls, getAssistantMessageFromRunOutput, getCombinedSystemPrompt, getConversationHistoryFromRunInput, getTextContentFromMastraDBMessage, getUserMessageFromRunInput, isScorerRunInputForAgent, isScorerRunOutputForAgent, roundToTwoDecimals } from "../utils.js";
1
+ import { analyzeToolFailures, checkTrajectoryBlacklist, checkTrajectoryEfficiency, compareTrajectories, extractAgentResponseMessages, extractToolCalls, getAssistantMessageFromRunOutput, getCombinedSystemPrompt, getConversationHistoryFromRunInput, getTextContentFromMastraDBMessage, getUserMessageFromRunInput, isScorerRunInputForAgent, isScorerRunOutputForAgent, roundToTwoDecimals, toToolLevelSteps } from "../utils.js";
2
2
  import { a as excludes, c as maxToolCalls, d as toolOrder, f as usedNoTools, i as equals, l as noToolErrors, n as checks, o as includes, r as didNotCall, s as matches, t as calledTool, u as similarity } from "../../checks-DxbqoaYq.js";
3
3
  import { createScorer } from "@mastra/core/evals";
4
4
  import nlp from "compromise";
@@ -226,7 +226,8 @@ function createAnswerRelevancyScorer({ model, options = DEFAULT_OPTIONS }) {
226
226
  description: "Extract relevant statements from the LLM output",
227
227
  outputSchema: extractOutputSchema$1,
228
228
  createPrompt: ({ run }) => {
229
- return createExtractPrompt$1(getAssistantMessageFromRunOutput(run.output) ?? "");
229
+ const assistantMessage = getAssistantMessageFromRunOutput(run.output) ?? "";
230
+ return createExtractPrompt$1(assistantMessage);
230
231
  }
231
232
  }).analyze({
232
233
  description: "Score the relevance of the statements to the input",
@@ -256,7 +257,8 @@ function createAnswerRelevancyScorer({ model, options = DEFAULT_OPTIONS }) {
256
257
  let relevancyCount = 0;
257
258
  for (const { result } of results.analyzeStepResult.results) if (result.trim().toLowerCase() === "yes") relevancyCount++;
258
259
  else if (result.trim().toLowerCase() === "unsure") relevancyCount += options.uncertaintyWeight;
259
- return roundToTwoDecimals(relevancyCount / numberOfResults * options.scale);
260
+ const score = relevancyCount / numberOfResults;
261
+ return roundToTwoDecimals(score * options.scale);
260
262
  }).generateReason({
261
263
  description: "Reason about the results",
262
264
  createPrompt: ({ run, results, score }) => {
@@ -498,18 +500,22 @@ function createAnswerSimilarityScorer({ model, options = ANSWER_SIMILARITY_DEFAU
498
500
  groundTruth: ""
499
501
  });
500
502
  }
503
+ const output = getAssistantMessageFromRunOutput(run.output) ?? "";
504
+ const groundTruth = typeof run.groundTruth === "string" ? run.groundTruth : JSON.stringify(run.groundTruth);
501
505
  return createExtractPrompt({
502
- output: getAssistantMessageFromRunOutput(run.output) ?? "",
503
- groundTruth: typeof run.groundTruth === "string" ? run.groundTruth : JSON.stringify(run.groundTruth)
506
+ output,
507
+ groundTruth
504
508
  });
505
509
  }
506
510
  }).analyze({
507
511
  description: "Compare semantic units between output and ground truth",
508
512
  outputSchema: analyzeOutputSchema$7,
509
513
  createPrompt: ({ results }) => {
514
+ const outputUnits = results.preprocessStepResult?.outputUnits || [];
515
+ const groundTruthUnits = results.preprocessStepResult?.groundTruthUnits || [];
510
516
  return createAnalyzePrompt$7({
511
- outputUnits: results.preprocessStepResult?.outputUnits || [],
512
- groundTruthUnits: results.preprocessStepResult?.groundTruthUnits || []
517
+ outputUnits,
518
+ groundTruthUnits
513
519
  });
514
520
  }
515
521
  }).generateScore(({ run, results }) => {
@@ -529,9 +535,7 @@ function createAnswerSimilarityScorer({ model, options = ANSWER_SIMILARITY_DEFAU
529
535
  case "partial":
530
536
  score += mergedOptions.semanticThreshold * .5;
531
537
  break;
532
- case "missing":
533
- score -= mergedOptions.missingPenalty;
534
- break;
538
+ case "missing": score -= mergedOptions.missingPenalty;
535
539
  }
536
540
  const maxPossibleScore = totalUnits * (1 + mergedOptions.exactMatchBonus);
537
541
  score = score / maxPossibleScore;
@@ -545,9 +549,11 @@ function createAnswerSimilarityScorer({ model, options = ANSWER_SIMILARITY_DEFAU
545
549
  description: "Generate explanation of similarity score",
546
550
  createPrompt: ({ run, results, score }) => {
547
551
  if (!run.groundTruth) return "No ground truth was provided for comparison. Score is 0 by default.";
552
+ const output = getAssistantMessageFromRunOutput(run.output) ?? "";
553
+ const groundTruth = typeof run.groundTruth === "string" ? run.groundTruth : JSON.stringify(run.groundTruth);
548
554
  return createReasonPrompt$5({
549
- output: getAssistantMessageFromRunOutput(run.output) ?? "",
550
- groundTruth: typeof run.groundTruth === "string" ? run.groundTruth : JSON.stringify(run.groundTruth),
555
+ output,
556
+ groundTruth,
551
557
  score,
552
558
  analysis: results.analyzeStepResult,
553
559
  scale: mergedOptions.scale
@@ -761,7 +767,8 @@ function createFaithfulnessScorer({ model, options }) {
761
767
  const totalClaims = results.preprocessStepResult?.claims?.length || verdicts.length;
762
768
  const supportedClaims = verdicts.filter((v) => v.verdict.toLowerCase().trim() === "yes").length;
763
769
  if (totalClaims === 0) return 0;
764
- return roundToTwoDecimals(Math.min(1, supportedClaims / totalClaims) * (options?.scale || 1));
770
+ const score = Math.min(1, supportedClaims / totalClaims) * (options?.scale || 1);
771
+ return roundToTwoDecimals(score);
765
772
  }).generateReason({
766
773
  description: "Reason about the results",
767
774
  createPrompt: ({ run, results, score }) => {
@@ -931,7 +938,8 @@ function createBiasScorer({ model, options }) {
931
938
  }
932
939
  }).generateScore(({ results }) => {
933
940
  if (!results.analyzeStepResult || results.analyzeStepResult.results.length === 0) return 0;
934
- return roundToTwoDecimals(results.analyzeStepResult.results.filter((v) => v.result.toLowerCase() === "yes").length / results.analyzeStepResult.results.length * (options?.scale || 1));
941
+ const score = results.analyzeStepResult.results.filter((v) => v.result.toLowerCase() === "yes").length / results.analyzeStepResult.results.length;
942
+ return roundToTwoDecimals(score * (options?.scale || 1));
935
943
  }).generateReason({
936
944
  description: "Reason about the results",
937
945
  createPrompt: ({ score, results }) => {
@@ -1189,7 +1197,8 @@ function createHallucinationScorer({ model, options }) {
1189
1197
  const totalStatements = results.preprocessStepResult?.claims?.length || verdicts.length;
1190
1198
  const contradictedStatements = verdicts.filter((v) => v.verdict.toLowerCase().trim() === "yes").length;
1191
1199
  if (totalStatements === 0) return 0;
1192
- return roundToTwoDecimals(Math.min(1, contradictedStatements / totalStatements) * (options?.scale || 1));
1200
+ const score = Math.min(1, contradictedStatements / totalStatements) * (options?.scale || 1);
1201
+ return roundToTwoDecimals(score);
1193
1202
  }).generateReason({
1194
1203
  description: "Reason about the results",
1195
1204
  createPrompt: async ({ run, results, score }) => {
@@ -1337,7 +1346,8 @@ function createToxicityScorer({ model, options }) {
1337
1346
  if (numberOfVerdicts === 0) return 1;
1338
1347
  let toxicityCount = 0;
1339
1348
  for (const { verdict } of results.analyzeStepResult.verdicts) if (verdict.trim().toLowerCase() === "yes") toxicityCount++;
1340
- return roundToTwoDecimals(toxicityCount / numberOfVerdicts * (options?.scale || 1));
1349
+ const score = toxicityCount / numberOfVerdicts;
1350
+ return roundToTwoDecimals(score * (options?.scale || 1));
1341
1351
  }).generateReason({
1342
1352
  description: "Reason about the results",
1343
1353
  createPrompt: ({ results, score }) => {
@@ -1485,10 +1495,13 @@ function createToolCallAccuracyScorerLLM({ model, availableTools }) {
1485
1495
  description: "Analyze the appropriateness of tool selections",
1486
1496
  outputSchema: analyzeOutputSchema$6,
1487
1497
  createPrompt: ({ run, results }) => {
1498
+ const userInput = getUserMessageFromRunInput(run.input) ?? "";
1499
+ const agentResponse = getAssistantMessageFromRunOutput(run.output) ?? "";
1500
+ const toolsCalled = results.preprocessStepResult?.actualTools || [];
1488
1501
  return createAnalyzePrompt$6({
1489
- userInput: getUserMessageFromRunInput(run.input) ?? "",
1490
- agentResponse: getAssistantMessageFromRunOutput(run.output) ?? "",
1491
- toolsCalled: results.preprocessStepResult?.actualTools || [],
1502
+ userInput,
1503
+ agentResponse,
1504
+ toolsCalled,
1492
1505
  availableTools: toolDefinitions
1493
1506
  });
1494
1507
  }
@@ -1501,11 +1514,14 @@ function createToolCallAccuracyScorerLLM({ model, availableTools }) {
1501
1514
  }).generateReason({
1502
1515
  description: "Generate human-readable explanation of tool selection evaluation",
1503
1516
  createPrompt: ({ run, results, score }) => {
1517
+ const userInput = getUserMessageFromRunInput(run.input) ?? "";
1518
+ const evaluations = results.analyzeStepResult?.evaluations || [];
1519
+ const missingTools = results.analyzeStepResult?.missingTools || [];
1504
1520
  return createReasonPrompt$4({
1505
- userInput: getUserMessageFromRunInput(run.input) ?? "",
1521
+ userInput,
1506
1522
  score,
1507
- evaluations: results.analyzeStepResult?.evaluations || [],
1508
- missingTools: results.analyzeStepResult?.missingTools || []
1523
+ evaluations,
1524
+ missingTools
1509
1525
  });
1510
1526
  }
1511
1527
  });
@@ -1767,7 +1783,8 @@ function createContextRelevanceScorerLLM({ model, options }) {
1767
1783
  const usagePenalty = highRelevanceUnused * unusedPenaltyRate;
1768
1784
  const missingContext = results.analyzeStepResult?.missingContext || [];
1769
1785
  const missingContextPenalty = Math.min(missingContext.length * missingPenaltyRate, maxMissingPenalty);
1770
- return roundToTwoDecimals(Math.max(0, relevanceScore - usagePenalty - missingContextPenalty) * (options.scale || 1));
1786
+ const scaledScore = Math.max(0, relevanceScore - usagePenalty - missingContextPenalty) * (options.scale || 1);
1787
+ return roundToTwoDecimals(scaledScore);
1771
1788
  }).generateReason({
1772
1789
  description: "Generate human-readable explanation of context relevance evaluation",
1773
1790
  createPrompt: ({ run, results, score }) => {
@@ -1964,7 +1981,8 @@ function createContextPrecisionScorer({ model, options }) {
1964
1981
  sumPrecision += precisionAtI;
1965
1982
  }
1966
1983
  if (relevantCount === 0) return 0;
1967
- return roundToTwoDecimals(sumPrecision / relevantCount * (options.scale || 1));
1984
+ const score = sumPrecision / relevantCount * (options.scale || 1);
1985
+ return roundToTwoDecimals(score);
1968
1986
  }).generateReason({
1969
1987
  description: "Reason about the context precision results",
1970
1988
  createPrompt: ({ run, results, score }) => {
@@ -2186,7 +2204,8 @@ function createContextRecallScorer({ model, options }) {
2186
2204
  const totalClaims = results.preprocessStepResult?.claims?.length ?? 0;
2187
2205
  if (totalClaims === 0) return 0;
2188
2206
  const attributedClaims = (results.analyzeStepResult?.verdicts || []).filter((v) => v.verdict.toLowerCase().trim() === "yes").length;
2189
- return roundToTwoDecimals(Math.min(1, attributedClaims / totalClaims) * (options.scale || 1));
2207
+ const score = Math.min(1, attributedClaims / totalClaims) * (options.scale || 1);
2208
+ return roundToTwoDecimals(score);
2190
2209
  }).generateReason({
2191
2210
  description: "Explain the context recall evaluation results",
2192
2211
  createPrompt: ({ run, results, score }) => {
@@ -3039,7 +3058,8 @@ function createPromptAlignmentScorerLLM({ model, options }) {
3039
3058
  const systemScore = userScore;
3040
3059
  weightedScore = userScore * SCORING_WEIGHTS.BOTH.USER_WEIGHT + systemScore * SCORING_WEIGHTS.BOTH.SYSTEM_WEIGHT;
3041
3060
  }
3042
- return roundToTwoDecimals(weightedScore * scale);
3061
+ const finalScore = weightedScore * scale;
3062
+ return roundToTwoDecimals(finalScore);
3043
3063
  }).generateReason({
3044
3064
  description: "Generate human-readable explanation of prompt alignment evaluation",
3045
3065
  createPrompt: ({ run, results, score }) => {
@@ -3809,14 +3829,13 @@ function formatStepDetails(step) {
3809
3829
  if (step.toolResult !== void 0) parts.push(`result: ${JSON.stringify(step.toolResult)}`);
3810
3830
  return parts.length > 0 ? ` (${parts.join(", ")})` : "";
3811
3831
  }
3812
- case "model_generation": return step.modelId ? ` (model: ${step.modelId})` : "";
3813
3832
  case "workflow_step": return step.output !== void 0 ? ` (output: ${JSON.stringify(step.output)})` : "";
3814
3833
  default: return "";
3815
3834
  }
3816
3835
  }
3817
3836
  function formatTrajectory(trajectory, indent = 0) {
3818
3837
  const prefix = " ".repeat(indent);
3819
- return trajectory.steps.map((step, i) => {
3838
+ return toToolLevelSteps(trajectory.steps).map((step, i) => {
3820
3839
  let line = `${prefix}${i + 1}. [${step.stepType}] ${step.name}${formatStepDetails(step)}`;
3821
3840
  if (step.children && step.children.length > 0) line += `\n${formatTrajectory({ steps: step.children }, indent + 1)}`;
3822
3841
  return line;
@@ -3879,17 +3898,18 @@ function createTrajectoryAccuracyScorerLLM({ model, expectedTrajectory: staticEx
3879
3898
  }).preprocess(async ({ run }) => {
3880
3899
  const actualTrajectory = run.output;
3881
3900
  let expectedSteps;
3882
- if (staticExpectedTrajectory) if (Array.isArray(staticExpectedTrajectory)) expectedSteps = staticExpectedTrajectory;
3883
- else {
3884
- const toExpectedStep = (s) => {
3885
- const { durationMs: _, metadata: _m, children, ...rest } = s;
3886
- const result = rest;
3887
- if (children && children.length > 0) result.children = { steps: children.map(toExpectedStep) };
3888
- return result;
3889
- };
3890
- expectedSteps = staticExpectedTrajectory.steps.map(toExpectedStep);
3891
- }
3892
- else if (run.expectedTrajectory) {
3901
+ if (staticExpectedTrajectory) {
3902
+ if (Array.isArray(staticExpectedTrajectory)) expectedSteps = staticExpectedTrajectory;
3903
+ else {
3904
+ const toExpectedStep = (s) => {
3905
+ const { durationMs: _, metadata: _m, children, ...rest } = s;
3906
+ const result = rest;
3907
+ if (children && children.length > 0) result.children = { steps: children.map(toExpectedStep) };
3908
+ return result;
3909
+ };
3910
+ expectedSteps = staticExpectedTrajectory.steps.map(toExpectedStep);
3911
+ }
3912
+ } else if (run.expectedTrajectory) {
3893
3913
  const expectation = run.expectedTrajectory;
3894
3914
  expectedSteps = expectation.steps && expectation.steps.length > 0 ? expectation.steps : void 0;
3895
3915
  }
@@ -3903,9 +3923,11 @@ function createTrajectoryAccuracyScorerLLM({ model, expectedTrajectory: staticEx
3903
3923
  description: "Analyze the quality and appropriateness of the agent trajectory",
3904
3924
  outputSchema: analyzeOutputSchema,
3905
3925
  createPrompt: ({ run, results }) => {
3926
+ const userInput = getUserMessageFromRunInput(run.input) ?? "";
3927
+ const agentResponse = getAssistantMessageFromRunOutput(run.output.rawOutput) ?? "";
3906
3928
  return createAnalyzePrompt({
3907
- userInput: getUserMessageFromRunInput(run.input) ?? "",
3908
- agentResponse: getAssistantMessageFromRunOutput(run.output.rawOutput) ?? "",
3929
+ userInput,
3930
+ agentResponse,
3909
3931
  actualTrajectory: results.preprocessStepResult?.actualTrajectoryFormatted ?? "No steps taken",
3910
3932
  expectedTrajectory: results.preprocessStepResult?.expectedTrajectoryFormatted
3911
3933
  });
@@ -3931,12 +3953,16 @@ function createTrajectoryAccuracyScorerLLM({ model, expectedTrajectory: staticEx
3931
3953
  }).generateReason({
3932
3954
  description: "Generate human-readable explanation of trajectory evaluation",
3933
3955
  createPrompt: ({ run, results, score }) => {
3956
+ const userInput = getUserMessageFromRunInput(run.input) ?? "";
3957
+ const stepEvaluations = results.analyzeStepResult?.stepEvaluations || [];
3958
+ const missingSteps = results.analyzeStepResult?.missingSteps || [];
3959
+ const extraSteps = results.analyzeStepResult?.extraSteps || [];
3934
3960
  return createReasonPrompt({
3935
- userInput: getUserMessageFromRunInput(run.input) ?? "",
3961
+ userInput,
3936
3962
  score,
3937
- stepEvaluations: results.analyzeStepResult?.stepEvaluations || [],
3938
- missingSteps: results.analyzeStepResult?.missingSteps || [],
3939
- extraSteps: results.analyzeStepResult?.extraSteps || []
3963
+ stepEvaluations,
3964
+ missingSteps,
3965
+ extraSteps
3940
3966
  });
3941
3967
  }
3942
3968
  });
@@ -4218,16 +4244,11 @@ function createToneScorer(config = {}) {
4218
4244
  //#region src/scorers/code/tool-call-accuracy/index.ts
4219
4245
  function checkToolOrder(actualTools, expectedOrder, strictMode = false) {
4220
4246
  if (strictMode) return JSON.stringify(actualTools) === JSON.stringify(expectedOrder);
4221
- const expectedIndices = [];
4247
+ let searchFrom = 0;
4222
4248
  for (const expectedTool of expectedOrder) {
4223
- const index = actualTools.indexOf(expectedTool);
4249
+ const index = actualTools.indexOf(expectedTool, searchFrom);
4224
4250
  if (index === -1) return false;
4225
- expectedIndices.push(index);
4226
- }
4227
- for (let i = 1; i < expectedIndices.length; i++) {
4228
- const currentIndex = expectedIndices[i];
4229
- const prevIndex = expectedIndices[i - 1];
4230
- if (currentIndex !== void 0 && prevIndex !== void 0 && currentIndex <= prevIndex) return false;
4251
+ searchFrom = index + 1;
4231
4252
  }
4232
4253
  return true;
4233
4254
  }
@@ -4351,7 +4372,7 @@ function createTrajectoryAccuracyScorerCode(options = {}) {
4351
4372
  actualTrajectory,
4352
4373
  expectedTrajectory: void 0,
4353
4374
  comparison: void 0,
4354
- actualStepNames: actualTrajectory.steps.map((s) => s.name),
4375
+ actualStepNames: toToolLevelSteps(actualTrajectory.steps).map((s) => s.name),
4355
4376
  expectedStepNames: [],
4356
4377
  error: "No expected trajectory provided (pass via options or dataset item expectedTrajectory)"
4357
4378
  };
@@ -4366,7 +4387,7 @@ function createTrajectoryAccuracyScorerCode(options = {}) {
4366
4387
  actualTrajectory,
4367
4388
  expectedTrajectory: { steps: resolvedExpectedSteps },
4368
4389
  comparison,
4369
- actualStepNames: actualTrajectory.steps.map((s) => s.name),
4390
+ actualStepNames: toToolLevelSteps(actualTrajectory.steps).map((s) => s.name),
4370
4391
  expectedStepNames: resolvedExpectedSteps.map((s) => s.name)
4371
4392
  };
4372
4393
  }).generateScore(({ results }) => {
@@ -4389,12 +4410,13 @@ function evaluateNestedExpectations(expectedSteps, actualSteps, weights = {
4389
4410
  blacklist: .1
4390
4411
  }) {
4391
4412
  const results = [];
4392
- const matchedIndices = /* @__PURE__ */ new Set();
4413
+ const matchedSteps = /* @__PURE__ */ new Set();
4414
+ const toolLevelSteps = toToolLevelSteps(actualSteps);
4415
+ const containerNames = new Set(actualSteps.filter((s) => s.stepType === "model_generation" || s.stepType === "processor_run").map((s) => s.name));
4393
4416
  for (const expectedStep of expectedSteps) {
4394
4417
  if (!expectedStep.children) continue;
4395
- const matchIndex = actualSteps.findIndex((s, i) => !matchedIndices.has(i) && s.name === expectedStep.name && (!expectedStep.stepType || s.stepType === expectedStep.stepType));
4396
- const actualStep = matchIndex >= 0 ? actualSteps[matchIndex] : void 0;
4397
- if (matchIndex >= 0) matchedIndices.add(matchIndex);
4418
+ const actualStep = (expectedStep.stepType === "model_generation" || expectedStep.stepType === "processor_run" || !expectedStep.stepType && containerNames.has(expectedStep.name) ? actualSteps : toolLevelSteps).find((s) => !matchedSteps.has(s) && s.name === expectedStep.name && (!expectedStep.stepType || s.stepType === expectedStep.stepType));
4419
+ if (actualStep) matchedSteps.add(actualStep);
4398
4420
  if (!actualStep) {
4399
4421
  const expectedStepCount = expectedStep.children.steps?.length ?? 0;
4400
4422
  results.push({