@mastra/evals 0.0.0-commonjs-20250227130920

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.
Files changed (95) hide show
  1. package/.turbo/turbo-build.log +37 -0
  2. package/CHANGELOG.md +777 -0
  3. package/LICENSE +44 -0
  4. package/README.md +185 -0
  5. package/dist/_tsup-dts-rollup.d.cts +764 -0
  6. package/dist/_tsup-dts-rollup.d.ts +764 -0
  7. package/dist/chunk-4VNS5WPM.js +37 -0
  8. package/dist/chunk-TXXJUIES.js +15 -0
  9. package/dist/dist-MSGH6PAG.js +17947 -0
  10. package/dist/index.cjs +19675 -0
  11. package/dist/index.d.cts +3 -0
  12. package/dist/index.d.ts +3 -0
  13. package/dist/index.js +86 -0
  14. package/dist/magic-string.es-5UDOWOAZ.js +1296 -0
  15. package/dist/metrics/judge/index.cjs +17 -0
  16. package/dist/metrics/judge/index.d.cts +1 -0
  17. package/dist/metrics/judge/index.d.ts +1 -0
  18. package/dist/metrics/judge/index.js +2 -0
  19. package/dist/metrics/llm/index.cjs +2482 -0
  20. package/dist/metrics/llm/index.d.cts +11 -0
  21. package/dist/metrics/llm/index.d.ts +11 -0
  22. package/dist/metrics/llm/index.js +2459 -0
  23. package/dist/metrics/nlp/index.cjs +202 -0
  24. package/dist/metrics/nlp/index.d.cts +5 -0
  25. package/dist/metrics/nlp/index.d.ts +5 -0
  26. package/dist/metrics/nlp/index.js +189 -0
  27. package/eslint.config.js +6 -0
  28. package/package.json +89 -0
  29. package/src/attachListeners.ts +40 -0
  30. package/src/constants.ts +1 -0
  31. package/src/evaluation.test.ts +29 -0
  32. package/src/evaluation.ts +58 -0
  33. package/src/index.ts +2 -0
  34. package/src/metrics/index.ts +3 -0
  35. package/src/metrics/judge/index.ts +14 -0
  36. package/src/metrics/llm/answer-relevancy/index.test.ts +156 -0
  37. package/src/metrics/llm/answer-relevancy/index.ts +58 -0
  38. package/src/metrics/llm/answer-relevancy/metricJudge.ts +56 -0
  39. package/src/metrics/llm/answer-relevancy/prompts.ts +214 -0
  40. package/src/metrics/llm/bias/index.test.ts +152 -0
  41. package/src/metrics/llm/bias/index.ts +52 -0
  42. package/src/metrics/llm/bias/metricJudge.ts +53 -0
  43. package/src/metrics/llm/bias/prompts.ts +109 -0
  44. package/src/metrics/llm/context-position/index.test.ts +275 -0
  45. package/src/metrics/llm/context-position/index.ts +69 -0
  46. package/src/metrics/llm/context-position/metricJudge.ts +55 -0
  47. package/src/metrics/llm/context-position/prompts.ts +135 -0
  48. package/src/metrics/llm/context-precision/index.test.ts +213 -0
  49. package/src/metrics/llm/context-precision/index.ts +68 -0
  50. package/src/metrics/llm/context-precision/metricJudge.ts +55 -0
  51. package/src/metrics/llm/context-precision/prompts.ts +139 -0
  52. package/src/metrics/llm/context-relevancy/index.test.ts +162 -0
  53. package/src/metrics/llm/context-relevancy/index.ts +59 -0
  54. package/src/metrics/llm/context-relevancy/metricJudge.ts +51 -0
  55. package/src/metrics/llm/context-relevancy/prompts.ts +111 -0
  56. package/src/metrics/llm/contextual-recall/index.test.ts +90 -0
  57. package/src/metrics/llm/contextual-recall/index.ts +56 -0
  58. package/src/metrics/llm/contextual-recall/metricJudge.ts +52 -0
  59. package/src/metrics/llm/contextual-recall/prompts.ts +82 -0
  60. package/src/metrics/llm/faithfulness/index.test.ts +254 -0
  61. package/src/metrics/llm/faithfulness/index.ts +59 -0
  62. package/src/metrics/llm/faithfulness/metricJudge.ts +62 -0
  63. package/src/metrics/llm/faithfulness/prompts.ts +166 -0
  64. package/src/metrics/llm/hallucination/index.test.ts +214 -0
  65. package/src/metrics/llm/hallucination/index.ts +59 -0
  66. package/src/metrics/llm/hallucination/metricJudge.ts +44 -0
  67. package/src/metrics/llm/hallucination/prompts.ts +143 -0
  68. package/src/metrics/llm/index.ts +11 -0
  69. package/src/metrics/llm/prompt-alignment/index.test.ts +335 -0
  70. package/src/metrics/llm/prompt-alignment/index.ts +116 -0
  71. package/src/metrics/llm/prompt-alignment/metricJudge.ts +43 -0
  72. package/src/metrics/llm/prompt-alignment/prompts.ts +224 -0
  73. package/src/metrics/llm/summarization/index.test.ts +274 -0
  74. package/src/metrics/llm/summarization/index.ts +72 -0
  75. package/src/metrics/llm/summarization/metricJudge.ts +101 -0
  76. package/src/metrics/llm/summarization/prompts.ts +252 -0
  77. package/src/metrics/llm/toxicity/index.test.ts +84 -0
  78. package/src/metrics/llm/toxicity/index.ts +54 -0
  79. package/src/metrics/llm/toxicity/metricJudge.ts +39 -0
  80. package/src/metrics/llm/toxicity/prompts.ts +87 -0
  81. package/src/metrics/llm/types.ts +7 -0
  82. package/src/metrics/llm/utils.ts +20 -0
  83. package/src/metrics/nlp/completeness/index.test.ts +98 -0
  84. package/src/metrics/nlp/completeness/index.ts +121 -0
  85. package/src/metrics/nlp/content-similarity/index.test.ts +76 -0
  86. package/src/metrics/nlp/content-similarity/index.ts +49 -0
  87. package/src/metrics/nlp/index.ts +5 -0
  88. package/src/metrics/nlp/keyword-coverage/index.test.ts +85 -0
  89. package/src/metrics/nlp/keyword-coverage/index.ts +49 -0
  90. package/src/metrics/nlp/textual-difference/index.test.ts +88 -0
  91. package/src/metrics/nlp/textual-difference/index.ts +38 -0
  92. package/src/metrics/nlp/tone/index.test.ts +100 -0
  93. package/src/metrics/nlp/tone/index.ts +55 -0
  94. package/tsconfig.json +5 -0
  95. package/vitest.config.ts +12 -0
@@ -0,0 +1,121 @@
1
+ import { Metric } from '@mastra/core/eval';
2
+ import type { MetricResult } from '@mastra/core/eval';
3
+ import nlp from 'compromise';
4
+
5
+ interface CompletenessMetricResult extends MetricResult {
6
+ info: {
7
+ inputElements: string[];
8
+ outputElements: string[];
9
+ missingElements: string[];
10
+ elementCounts: {
11
+ input: number;
12
+ output: number;
13
+ };
14
+ };
15
+ }
16
+
17
+ export class CompletenessMetric extends Metric {
18
+ async measure(input: string, output: string): Promise<CompletenessMetricResult> {
19
+ // Handle null/undefined inputs
20
+ if (input === null || input === undefined || output === null || output === undefined) {
21
+ throw new Error('Inputs cannot be null or undefined');
22
+ }
23
+
24
+ // Trim both inputs
25
+ input = input.trim();
26
+ output = output.trim();
27
+
28
+ const inputDoc = nlp(input);
29
+ const outputDoc = nlp(output);
30
+
31
+ // Extract and log elements
32
+ const inputElements = this.extractElements(inputDoc);
33
+ const outputElements = this.extractElements(outputDoc);
34
+ // Maybe we need a more sophisticated matching approach
35
+ const coverage = this.calculateCoverage(inputElements, outputElements);
36
+
37
+ return {
38
+ score: coverage,
39
+ info: {
40
+ inputElements,
41
+ outputElements,
42
+ missingElements: inputElements.filter(e => !outputElements.includes(e)),
43
+ elementCounts: {
44
+ input: inputElements.length,
45
+ output: outputElements.length,
46
+ },
47
+ },
48
+ };
49
+ }
50
+
51
+ private extractElements(doc: any): string[] {
52
+ // Get more specific elements and ensure they're arrays
53
+ const nouns = doc.nouns().out('array') || [];
54
+ const verbs = doc.verbs().toInfinitive().out('array') || [];
55
+ const topics = doc.topics().out('array') || [];
56
+ const terms = doc.terms().out('array') || [];
57
+
58
+ // Helper function to clean and split terms
59
+ const cleanAndSplitTerm = (term: string): string[] => {
60
+ // First normalize the string
61
+ const normalized = this.normalizeString(term);
62
+
63
+ // Split on word boundaries and filter out empty strings
64
+ return normalized
65
+ .replace(/([a-z])([A-Z])/g, '$1 $2') // Split camelCase
66
+ .replace(/[^a-z0-9]+/g, ' ') // Replace non-alphanumeric with spaces
67
+ .trim()
68
+ .split(/\s+/)
69
+ .filter(word => word.length > 0);
70
+ };
71
+
72
+ // Process all elements
73
+ const processedTerms = [
74
+ ...nouns.flatMap(cleanAndSplitTerm),
75
+ ...verbs.flatMap(cleanAndSplitTerm),
76
+ ...topics.flatMap(cleanAndSplitTerm),
77
+ ...terms.flatMap(cleanAndSplitTerm),
78
+ ];
79
+
80
+ // Remove duplicates
81
+ return [...new Set(processedTerms)];
82
+ }
83
+
84
+ private normalizeString(str: string): string {
85
+ // Remove diacritics and convert to lowercase
86
+ return str
87
+ .normalize('NFD')
88
+ .replace(/[\u0300-\u036f]/g, '')
89
+ .toLowerCase();
90
+ }
91
+
92
+ private calculateCoverage(original: string[], simplified: string[]): number {
93
+ if (original.length === 0) {
94
+ return simplified.length === 0 ? 1 : 0;
95
+ }
96
+
97
+ // Exact matching for short words (3 chars or less), substring matching for longer words
98
+ const covered = original.filter(element =>
99
+ simplified.some(s => {
100
+ const elem = this.normalizeString(element);
101
+ const simp = this.normalizeString(s);
102
+
103
+ // For short words (3 chars or less), require exact match
104
+ if (elem.length <= 3) {
105
+ return elem === simp;
106
+ }
107
+
108
+ // For longer words, require substantial overlap (more than 60% of the longer word)
109
+ const longer = elem.length > simp.length ? elem : simp;
110
+ const shorter = elem.length > simp.length ? simp : elem;
111
+
112
+ if (longer.includes(shorter)) {
113
+ return shorter.length / longer.length > 0.6;
114
+ }
115
+
116
+ return false;
117
+ }),
118
+ );
119
+ return covered.length / original.length;
120
+ }
121
+ }
@@ -0,0 +1,76 @@
1
+ import { describe, it, expect } from 'vitest';
2
+
3
+ import { ContentSimilarityMetric } from './index';
4
+
5
+ describe('ContentSimilarityMetric', () => {
6
+ const metric = new ContentSimilarityMetric();
7
+
8
+ it('should return perfect similarity for identical strings', async () => {
9
+ const result = await metric.measure('The quick brown fox', 'The quick brown fox');
10
+ expect(result.score).toBe(1);
11
+ expect(result.info?.similarity).toBe(1);
12
+ });
13
+
14
+ it('should handle case differences with default options', async () => {
15
+ const result = await metric.measure('The Quick Brown Fox', 'the quick brown fox');
16
+ expect(result.score).toBe(1);
17
+ });
18
+
19
+ it('should handle whitespace differences with default options', async () => {
20
+ const result = await metric.measure('The quick\nbrown fox', 'The quick brown fox');
21
+ expect(result.score).toBe(1);
22
+ });
23
+
24
+ it('should be case sensitive when ignoreCase is false', async () => {
25
+ const caseSensitiveMetric = new ContentSimilarityMetric({ ignoreCase: false });
26
+ const result = await caseSensitiveMetric.measure('The Quick Brown FOX', 'the quick brown fox');
27
+ expect(result.score).toBeLessThan(0.8);
28
+ });
29
+
30
+ it('should preserve whitespace differences when ignoreWhitespace is true', async () => {
31
+ const whitespaceMetric = new ContentSimilarityMetric({
32
+ ignoreCase: true,
33
+ ignoreWhitespace: true,
34
+ });
35
+ const result = await whitespaceMetric.measure('The\tquick brown\n\nfox', 'The quick brown fox');
36
+ expect(result.score).toBe(1);
37
+ });
38
+
39
+ it('should handle both case and whitespace sensitivity', async () => {
40
+ const sensitiveMetric = new ContentSimilarityMetric({
41
+ ignoreCase: false,
42
+ ignoreWhitespace: true,
43
+ });
44
+ const result = await sensitiveMetric.measure('The\tQuick Brown\n\nFOX', 'the quick brown fox');
45
+ expect(result.score).toBeLessThan(0.8);
46
+ });
47
+
48
+ it('should handle partial similarity', async () => {
49
+ const result = await metric.measure(
50
+ 'The quick brown fox jumps over the lazy dog',
51
+ 'The quick brown fox runs past the lazy dog',
52
+ );
53
+ expect(result.score).toBeGreaterThan(0.7);
54
+ expect(result.score).toBeLessThan(0.8);
55
+ });
56
+
57
+ it('should handle completely different strings', async () => {
58
+ const result = await metric.measure('The quick brown fox', 'Lorem ipsum dolor sit amet');
59
+ expect(result.score).toBeLessThan(0.3);
60
+ });
61
+
62
+ it('should handle empty strings', async () => {
63
+ const result = await metric.measure('', '');
64
+ expect(result.score).toBe(1);
65
+ });
66
+
67
+ it('should handle one empty string', async () => {
68
+ const result = await metric.measure('The quick brown fox', '');
69
+ expect(result.score).toBe(0);
70
+ });
71
+
72
+ it('should include similarity details in result', async () => {
73
+ const result = await metric.measure('The quick brown fox', 'The quick brown fox');
74
+ expect(result.info).toEqual({ similarity: 1 });
75
+ });
76
+ });
@@ -0,0 +1,49 @@
1
+ import { Metric } from '@mastra/core/eval';
2
+ import type { MetricResult } from '@mastra/core/eval';
3
+ import stringSimilarity from 'string-similarity';
4
+
5
+ interface ContentSimilarityResult extends MetricResult {
6
+ info: {
7
+ similarity: number;
8
+ };
9
+ }
10
+
11
+ interface ContentSimilarityOptions {
12
+ ignoreCase?: boolean;
13
+ ignoreWhitespace?: boolean;
14
+ }
15
+
16
+ export class ContentSimilarityMetric extends Metric {
17
+ private options: ContentSimilarityOptions;
18
+
19
+ constructor(options: ContentSimilarityOptions = {}) {
20
+ super();
21
+ this.options = {
22
+ ignoreCase: true,
23
+ ignoreWhitespace: true,
24
+ ...options,
25
+ };
26
+ }
27
+
28
+ async measure(input: string, output: string): Promise<ContentSimilarityResult> {
29
+ let processedInput = input;
30
+ let processedOutput = output;
31
+
32
+ if (this.options.ignoreCase) {
33
+ processedInput = processedInput.toLowerCase();
34
+ processedOutput = processedOutput.toLowerCase();
35
+ }
36
+
37
+ if (this.options.ignoreWhitespace) {
38
+ processedInput = processedInput.replace(/\s+/g, ' ').trim();
39
+ processedOutput = processedOutput.replace(/\s+/g, ' ').trim();
40
+ }
41
+
42
+ const similarity = stringSimilarity.compareTwoStrings(processedInput, processedOutput);
43
+
44
+ return {
45
+ score: similarity,
46
+ info: { similarity },
47
+ };
48
+ }
49
+ }
@@ -0,0 +1,5 @@
1
+ export { CompletenessMetric } from './completeness';
2
+ export { ContentSimilarityMetric } from './content-similarity';
3
+ export { TextualDifferenceMetric } from './textual-difference';
4
+ export { KeywordCoverageMetric } from './keyword-coverage';
5
+ export { ToneConsistencyMetric } from './tone';
@@ -0,0 +1,85 @@
1
+ import { describe, it, expect } from 'vitest';
2
+
3
+ import { KeywordCoverageMetric } from './index';
4
+
5
+ describe('KeywordCoverageMetric', () => {
6
+ const metric = new KeywordCoverageMetric();
7
+
8
+ it('should return perfect coverage for identical text', async () => {
9
+ const result = await metric.measure(
10
+ 'The quick brown fox jumps over the lazy dog',
11
+ 'The quick brown fox jumps over the lazy dog',
12
+ );
13
+ expect(result.score).toBe(1);
14
+ expect(result.info?.matchedKeywords).toBe(6);
15
+ expect(result.info?.totalKeywords).toBe(6);
16
+ });
17
+
18
+ it('should handle partial keyword coverage', async () => {
19
+ const result = await metric.measure(
20
+ 'The quick brown fox jumps over the lazy dog',
21
+ 'A quick brown fox runs past a sleeping cat',
22
+ );
23
+ expect(result.score).toBeGreaterThan(0.3);
24
+ expect(result.score).toBeLessThan(0.7);
25
+ const matched = result.info?.matchedKeywords as number;
26
+ const total = result.info?.totalKeywords as number;
27
+ expect(matched).toBeLessThan(total);
28
+ });
29
+
30
+ it('should ignore common words and stop words', async () => {
31
+ const result = await metric.measure('The quick brown fox', 'A quick brown fox');
32
+ expect(result.score).toBe(1); // "the" and "a" should be ignored
33
+ const matched = result.info?.matchedKeywords as number;
34
+ const total = result.info?.totalKeywords as number;
35
+ expect(matched).toBe(total);
36
+ });
37
+
38
+ it('should handle case differences', async () => {
39
+ const result = await metric.measure('The Quick Brown Fox', 'the quick brown fox');
40
+ expect(result.score).toBe(1);
41
+ const matched = result.info?.matchedKeywords as number;
42
+ const total = result.info?.totalKeywords as number;
43
+ expect(matched).toBe(total);
44
+ });
45
+
46
+ it('should handle empty strings', async () => {
47
+ const result = await metric.measure('', '');
48
+ expect(result.score).toBe(1);
49
+ expect(result.info?.totalKeywords).toBe(0);
50
+ expect(result.info?.matchedKeywords).toBe(0);
51
+ });
52
+
53
+ it('should handle one empty string', async () => {
54
+ const result = await metric.measure('The quick brown fox', '');
55
+ expect(result.score).toBe(0);
56
+ expect(result.info?.matchedKeywords).toBe(0);
57
+ expect(result.info?.totalKeywords).toBeGreaterThan(0);
58
+ });
59
+
60
+ it('should ignore numbers by default', async () => {
61
+ const result = await metric.measure('The 123 quick 456 brown fox', 'The quick brown fox');
62
+ expect(result.score).toBe(1);
63
+ });
64
+
65
+ it('should handle special characters', async () => {
66
+ const result = await metric.measure('The quick-brown fox!', 'The quick brown fox');
67
+ // Hyphenated words are treated as separate keywords
68
+ expect(result.score).toBeGreaterThanOrEqual(0.5);
69
+ expect(result.score).toBeLessThan(1);
70
+ });
71
+
72
+ it('should handle completely different content', async () => {
73
+ const result = await metric.measure('The quick brown fox jumps over the lazy dog', 'Lorem ipsum dolor sit amet');
74
+ expect(result.score).toBe(0);
75
+ expect(result.info?.matchedKeywords).toBe(0);
76
+ });
77
+
78
+ it('should include coverage details in result', async () => {
79
+ const result = await metric.measure('quick brown fox', 'quick brown fox');
80
+ expect(result.info).toEqual({
81
+ totalKeywords: 3,
82
+ matchedKeywords: 3,
83
+ });
84
+ });
85
+ });
@@ -0,0 +1,49 @@
1
+ import { Metric } from '@mastra/core/eval';
2
+ import type { MetricResult } from '@mastra/core/eval';
3
+ import keyword_extractor from 'keyword-extractor';
4
+
5
+ interface KeywordCoverageResult extends MetricResult {
6
+ info: {
7
+ totalKeywords: number;
8
+ matchedKeywords: number;
9
+ };
10
+ }
11
+
12
+ export class KeywordCoverageMetric extends Metric {
13
+ async measure(input: string, output: string): Promise<KeywordCoverageResult> {
14
+ // Handle empty strings case
15
+ if (!input && !output) {
16
+ return {
17
+ score: 1,
18
+ info: {
19
+ totalKeywords: 0,
20
+ matchedKeywords: 0,
21
+ },
22
+ };
23
+ }
24
+
25
+ const extractKeywords = (text: string) => {
26
+ return keyword_extractor.extract(text, {
27
+ language: 'english',
28
+ remove_digits: true,
29
+ return_changed_case: true,
30
+ remove_duplicates: true,
31
+ });
32
+ };
33
+
34
+ const referenceKeywords = new Set(extractKeywords(input));
35
+ const responseKeywords = new Set(extractKeywords(output));
36
+
37
+ const matchedKeywords = [...referenceKeywords].filter(k => responseKeywords.has(k));
38
+ const totalKeywords = referenceKeywords.size;
39
+ const coverage = totalKeywords > 0 ? matchedKeywords.length / totalKeywords : 0;
40
+
41
+ return {
42
+ score: coverage,
43
+ info: {
44
+ totalKeywords: referenceKeywords.size,
45
+ matchedKeywords: matchedKeywords.length,
46
+ },
47
+ };
48
+ }
49
+ }
@@ -0,0 +1,88 @@
1
+ import { describe, it, expect } from 'vitest';
2
+
3
+ import { TextualDifferenceMetric } from './index';
4
+
5
+ describe('TextualDifferenceMetric', () => {
6
+ const metric = new TextualDifferenceMetric();
7
+
8
+ it('should return perfect match for identical strings', async () => {
9
+ const result = await metric.measure('The quick brown fox', 'The quick brown fox');
10
+ expect(result.score).toBe(1);
11
+ expect(result.info).toEqual({
12
+ confidence: 1,
13
+ ratio: 1,
14
+ changes: 0,
15
+ lengthDiff: 0,
16
+ });
17
+ });
18
+
19
+ it('should handle small differences', async () => {
20
+ const result = await metric.measure('The quick brown fox', 'The quick brown cat');
21
+ expect(result.score).toBeGreaterThan(0.8);
22
+ expect(result.info?.changes).toBe(1);
23
+ });
24
+
25
+ it('should handle word additions', async () => {
26
+ const result = await metric.measure('The quick brown fox', 'The very quick brown fox');
27
+ expect(result.score).toBeGreaterThan(0.7);
28
+ expect(result.info?.changes).toBe(1);
29
+ });
30
+
31
+ it('should handle word deletions', async () => {
32
+ const result = await metric.measure('The quick brown fox jumps', 'The quick fox jumps');
33
+ expect(result.score).toBeGreaterThan(0.7);
34
+ expect(result.info?.changes).toBe(1);
35
+ });
36
+
37
+ it('should handle multiple changes', async () => {
38
+ const result = await metric.measure(
39
+ 'The quick brown fox jumps over the lazy dog',
40
+ 'The slow black fox runs under the active cat',
41
+ );
42
+ expect(result.score).toBeGreaterThan(0.4);
43
+ expect(result.score).toBeLessThan(0.7);
44
+ expect(result.info?.changes).toBeGreaterThan(3);
45
+ });
46
+
47
+ it('should handle completely different strings', async () => {
48
+ const result = await metric.measure('The quick brown fox', 'Lorem ipsum dolor sit amet');
49
+ expect(result.score).toBeLessThan(0.3);
50
+ expect(result.info?.changes).toBeGreaterThan(3);
51
+ });
52
+
53
+ it('should handle empty strings', async () => {
54
+ const result = await metric.measure('', '');
55
+ expect(result.score).toBe(1);
56
+ expect(result.info?.changes).toBe(0);
57
+ expect(result.info?.lengthDiff).toBe(0);
58
+ });
59
+
60
+ it('should handle one empty string', async () => {
61
+ const result = await metric.measure('The quick brown fox', '');
62
+ expect(result.score).toBe(0);
63
+ expect(result.info?.changes).toBeGreaterThan(0);
64
+ expect(result.info?.lengthDiff).toBe(1);
65
+ });
66
+
67
+ it('should handle case sensitivity', async () => {
68
+ const result = await metric.measure('The Quick Brown Fox', 'the quick brown fox');
69
+ expect(result.score).toBeLessThan(1);
70
+ expect(result.info?.changes).toBeGreaterThan(0);
71
+ });
72
+
73
+ it('should handle whitespace sensitivity', async () => {
74
+ const result = await metric.measure('The quick\nbrown fox', 'The quick brown fox');
75
+ expect(result.score).toBeLessThan(1);
76
+ expect(result.info?.changes).toBeGreaterThan(0);
77
+ });
78
+
79
+ it('should include difference details in result', async () => {
80
+ const result = await metric.measure('The quick brown fox', 'The quick brown fox');
81
+ expect(result.info).toEqual({
82
+ confidence: 1,
83
+ ratio: 1,
84
+ changes: 0,
85
+ lengthDiff: 0,
86
+ });
87
+ });
88
+ });
@@ -0,0 +1,38 @@
1
+ import { Metric } from '@mastra/core/eval';
2
+ import type { MetricResult } from '@mastra/core/eval';
3
+ import { SequenceMatcher } from 'difflib';
4
+
5
+ interface TextualDifferenceResult extends MetricResult {
6
+ info: {
7
+ ratio: number;
8
+ changes: number;
9
+ lengthDiff: number;
10
+ confidence: number;
11
+ };
12
+ }
13
+
14
+ export class TextualDifferenceMetric extends Metric {
15
+ async measure(input: string, output: string): Promise<TextualDifferenceResult> {
16
+ const matcher = new SequenceMatcher(null, input, output);
17
+ const ratio = matcher.ratio();
18
+
19
+ // Get detailed operations
20
+ const ops = matcher.getOpcodes();
21
+ const changes = ops.filter(([op]) => op !== 'equal').length;
22
+
23
+ // Calculate confidence based on text length difference
24
+ const maxLength = Math.max(input.length, output.length);
25
+ const lengthDiff = maxLength > 0 ? Math.abs(input.length - output.length) / maxLength : 0;
26
+ const confidence = 1 - lengthDiff;
27
+
28
+ return {
29
+ score: ratio,
30
+ info: {
31
+ confidence,
32
+ ratio,
33
+ changes,
34
+ lengthDiff,
35
+ },
36
+ };
37
+ }
38
+ }
@@ -0,0 +1,100 @@
1
+ import { describe, it, expect } from 'vitest';
2
+
3
+ import { ToneConsistencyMetric } from './index';
4
+
5
+ describe('ToneConsistencyMetric', () => {
6
+ const metric = new ToneConsistencyMetric();
7
+
8
+ describe('tone consistency (with reference)', () => {
9
+ it('should return perfect score for identical sentiment', async () => {
10
+ const result = await metric.measure('I love this amazing product!', 'This product is wonderful and fantastic!');
11
+ const metrics = result.info as { responseSentiment: number; referenceSentiment: number; difference: number };
12
+ expect(result.score).toBeGreaterThan(0.9);
13
+ expect(metrics.responseSentiment).toBeGreaterThan(0);
14
+ expect(metrics.referenceSentiment).toBeGreaterThan(0);
15
+ expect(metrics.difference).toBeLessThan(0.1);
16
+ });
17
+
18
+ it('should handle opposite sentiments', async () => {
19
+ const result = await metric.measure('This is terrible and disappointing.', 'This is excellent and amazing!');
20
+ const metrics = result.info as { responseSentiment: number; referenceSentiment: number; difference: number };
21
+ expect(result.score).toBeLessThan(0.5);
22
+ expect(metrics.responseSentiment).toBeLessThan(0);
23
+ expect(metrics.referenceSentiment).toBeGreaterThan(0);
24
+ expect(metrics.difference).toBeGreaterThan(0.5);
25
+ });
26
+
27
+ it('should handle neutral text', async () => {
28
+ const result = await metric.measure('The sky is blue. The grass is green.', 'Trees are tall. Water is wet.');
29
+ const metrics = result.info as { responseSentiment: number; referenceSentiment: number; difference: number };
30
+ expect(result.score).toBeGreaterThan(0.9);
31
+ expect(Math.abs(metrics.responseSentiment)).toBeLessThan(0.2);
32
+ expect(Math.abs(metrics.referenceSentiment)).toBeLessThan(0.2);
33
+ expect(metrics.difference!).toBeLessThan(0.1);
34
+ });
35
+
36
+ it('should handle mixed sentiment comparison', async () => {
37
+ const result = await metric.measure(
38
+ 'The product has great features but some annoying bugs.',
39
+ 'While the interface is beautiful, performance is poor.',
40
+ );
41
+ const metrics = result.info as { responseSentiment: number; referenceSentiment: number; difference: number };
42
+ expect(result.score).toBeGreaterThan(0.7);
43
+ expect(Math.abs(metrics.difference)).toBeLessThan(0.3);
44
+ });
45
+ });
46
+
47
+ describe('tone stability (single input)', () => {
48
+ it('should handle consistent positive tone', async () => {
49
+ const result = await metric.measure(
50
+ 'I love this product! It works amazingly well. The features are fantastic.',
51
+ '',
52
+ );
53
+ const metrics = result.info as { avgSentiment: number; sentimentVariance: number };
54
+ expect(result.score).toBeGreaterThan(0.8);
55
+ expect(metrics.avgSentiment).toBeGreaterThan(0);
56
+ expect(metrics.sentimentVariance).toBeLessThan(0.2);
57
+ });
58
+
59
+ it('should handle consistent negative tone', async () => {
60
+ const result = await metric.measure('This is terrible. It never works properly. The support is awful.', '');
61
+ const metrics = result.info as { avgSentiment: number; sentimentVariance: number };
62
+ expect(result.score).toBeGreaterThan(0.8);
63
+ expect(metrics.avgSentiment).toBeLessThan(0);
64
+ expect(metrics.sentimentVariance).toBeLessThan(0.2);
65
+ });
66
+
67
+ it('should detect inconsistent tone', async () => {
68
+ const result = await metric.measure(
69
+ 'This is amazing! But it has terrible flaws. Yet somehow I love it. Though it frustrates me.',
70
+ '',
71
+ );
72
+ const metrics = result.info as { avgSentiment: number; sentimentVariance: number };
73
+ expect(result.score).toBeLessThan(0.7);
74
+ expect(metrics.sentimentVariance).toBeGreaterThan(0.2);
75
+ });
76
+
77
+ it('should handle single sentence', async () => {
78
+ const result = await metric.measure('This is a great product.', '');
79
+ const metrics = result.info as { avgSentiment: number; sentimentVariance: number };
80
+ expect(result.score).toBe(1);
81
+ expect(metrics.sentimentVariance).toBe(0);
82
+ });
83
+
84
+ it('should handle empty input', async () => {
85
+ const result = await metric.measure('', '');
86
+ const metrics = result.info as { avgSentiment: number; sentimentVariance: number };
87
+ expect(result.score).toBe(1);
88
+ expect(metrics.avgSentiment).toBe(0);
89
+ expect(metrics.sentimentVariance).toBe(0);
90
+ });
91
+
92
+ it('should handle neutral consistent tone', async () => {
93
+ const result = await metric.measure('The sky is blue. The grass is green. The tree is tall.', '');
94
+ const metrics = result.info as { avgSentiment: number; sentimentVariance: number };
95
+ expect(result.score).toBeGreaterThan(0.9);
96
+ expect(Math.abs(metrics.avgSentiment)).toBeLessThan(0.2);
97
+ expect(metrics.sentimentVariance).toBeLessThan(0.1);
98
+ });
99
+ });
100
+ });
@@ -0,0 +1,55 @@
1
+ import { Metric } from '@mastra/core/eval';
2
+ import type { MetricResult } from '@mastra/core/eval';
3
+ import Sentiment from 'sentiment';
4
+
5
+ interface ToneConsitencyResult extends MetricResult {
6
+ info:
7
+ | {
8
+ responseSentiment: number;
9
+ referenceSentiment: number;
10
+ difference: number;
11
+ }
12
+ | {
13
+ avgSentiment: number;
14
+ sentimentVariance: number;
15
+ };
16
+ }
17
+
18
+ export class ToneConsistencyMetric extends Metric {
19
+ private sentiment = new Sentiment();
20
+
21
+ async measure(input: string, output: string): Promise<ToneConsitencyResult> {
22
+ const responseSentiment = this.sentiment.analyze(input);
23
+
24
+ if (output) {
25
+ // Compare sentiment with reference
26
+ const referenceSentiment = this.sentiment.analyze(output);
27
+ const sentimentDiff = Math.abs(responseSentiment.comparative - referenceSentiment.comparative);
28
+ const normalizedScore = Math.max(0, 1 - sentimentDiff);
29
+
30
+ return {
31
+ score: normalizedScore,
32
+ info: {
33
+ responseSentiment: responseSentiment.comparative,
34
+ referenceSentiment: referenceSentiment.comparative,
35
+ difference: sentimentDiff,
36
+ },
37
+ };
38
+ }
39
+
40
+ // Evaluate sentiment stability across response
41
+ const sentences = input.match(/[^.!?]+[.!?]+/g) || [input];
42
+ const sentiments = sentences.map(s => this.sentiment.analyze(s).comparative);
43
+ const avgSentiment = sentiments.reduce((a, b) => a + b, 0) / sentiments.length;
44
+ const variance = sentiments.reduce((sum, s) => sum + Math.pow(s - avgSentiment, 2), 0) / sentiments.length;
45
+ const stability = Math.max(0, 1 - variance);
46
+
47
+ return {
48
+ score: stability,
49
+ info: {
50
+ avgSentiment,
51
+ sentimentVariance: variance,
52
+ },
53
+ };
54
+ }
55
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": "../../tsconfig.node.json",
3
+ "include": ["src/**/*"],
4
+ "exclude": ["node_modules", "**/*.test.ts"]
5
+ }