@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,162 @@
1
+ import { createOpenAI } from '@ai-sdk/openai';
2
+ import { describe, it, expect } from 'vitest';
3
+
4
+ import type { TestCaseWithContext } from '../utils';
5
+ import { isCloserTo } from '../utils';
6
+
7
+ import { ContextRelevancyMetric } from './index';
8
+
9
+ const testCases: TestCaseWithContext[] = [
10
+ {
11
+ // Perfect relevancy - all context pieces directly address the question
12
+ input: 'What are the symptoms and treatment options for type 2 diabetes?',
13
+ output:
14
+ 'Type 2 diabetes symptoms include increased thirst, frequent urination, fatigue, and blurred vision. Treatment options include lifestyle changes, blood sugar monitoring, and medications like metformin or insulin therapy.',
15
+ context: [
16
+ 'Common symptoms of type 2 diabetes include increased thirst, frequent urination, unexplained weight loss, fatigue, and blurred vision. Early detection of these symptoms is crucial for proper management.',
17
+ 'Treatment options for type 2 diabetes typically include lifestyle modifications such as diet changes and regular exercise. Regular monitoring of blood sugar levels is essential for managing the condition.',
18
+ 'Medications for type 2 diabetes may include metformin, sulfonylureas, or insulin therapy, depending on the severity of the condition and individual patient factors.',
19
+ ],
20
+ expectedResult: {
21
+ score: 1.0,
22
+ reason:
23
+ 'All context pieces are highly relevant to the question, providing specific information about both symptoms and treatments for type 2 diabetes. Each piece of context directly contributes to answering the question comprehensively.',
24
+ },
25
+ },
26
+ {
27
+ // Mixed relevancy - some context pieces are relevant, others tangential
28
+ input: 'What caused the 2008 financial crisis?',
29
+ output:
30
+ 'The 2008 financial crisis was caused by the collapse of the subprime mortgage market, though there were other contributing factors in the banking sector.',
31
+ context: [
32
+ 'The 2008 financial crisis was primarily triggered by the collapse of the subprime mortgage market in the United States.',
33
+ 'The history of banking regulation in the United States dates back to the Great Depression of the 1930s.',
34
+ 'Modern investment banking practices involve various financial instruments and risk management strategies.',
35
+ ],
36
+ expectedResult: {
37
+ score: 0.5,
38
+ reason:
39
+ "Only one context piece directly addresses the cause of the 2008 financial crisis. The other two pieces provide general banking information that isn't specifically relevant to the question about the crisis's causes.",
40
+ },
41
+ },
42
+ {
43
+ // Zero relevancy - completely unrelated context
44
+ input: 'How does a solar eclipse occur?',
45
+ output:
46
+ "A solar eclipse occurs when the Moon passes between the Earth and the Sun, temporarily blocking part or all of the Sun's light.",
47
+ context: [
48
+ 'Volcanic eruptions can have significant impacts on local weather patterns and air quality.',
49
+ 'The Amazon rainforest is home to countless species of plants and animals.',
50
+ 'Wind turbines convert kinetic energy from wind into electrical power.',
51
+ ],
52
+ expectedResult: {
53
+ score: 0.0,
54
+ reason:
55
+ 'None of the provided context pieces contain any information about solar eclipses or related astronomical phenomena. The contexts discuss entirely unrelated topics such as volcanoes, rainforests, and wind power.',
56
+ },
57
+ },
58
+ {
59
+ // Only recent developments are relevant when asking for 'latest'
60
+ input: 'What are the latest developments in quantum computing?',
61
+ output: 'Recent advances include improved error correction and the development of more stable qubits.',
62
+ context: [
63
+ 'In 2023, researchers achieved a breakthrough in quantum error correction, significantly improving qubit stability.',
64
+ 'The basic principles of quantum computing were first proposed in the 1980s.',
65
+ 'Classical computers use bits that are either 0 or 1.',
66
+ ],
67
+ expectedResult: {
68
+ score: 0.33,
69
+ reason:
70
+ 'Only the first context piece about 2023 breakthroughs is relevant to "latest developments". Historical information about 1980s principles and basic classical computing concepts are not relevant when specifically asking about recent developments.',
71
+ },
72
+ },
73
+ {
74
+ // Full relevancy with complementary details
75
+ input: 'How do electric cars work?',
76
+ output:
77
+ 'Electric cars use batteries to power an electric motor, converting electrical energy to mechanical energy for propulsion.',
78
+ context: [
79
+ 'Electric vehicles (EVs) use large battery packs to store electrical energy, which powers one or more electric motors.',
80
+ 'The motors in EVs convert electrical energy into mechanical energy through electromagnetic principles.',
81
+ 'Modern EVs typically use lithium-ion batteries, though some early models used lead-acid or nickel-metal hydride batteries.',
82
+ ],
83
+ expectedResult: {
84
+ score: 1.0,
85
+ reason:
86
+ 'All three context pieces are fully relevant to explaining how electric cars work: the first describes the core power flow from batteries to motors, the second explains the energy conversion process, and the third details the types of batteries used for power storage. Each piece contributes a different but essential aspect of EV operation.',
87
+ },
88
+ },
89
+ {
90
+ // Zero relevancy with misleading keyword matches
91
+ input: 'What is the capital of France?',
92
+ output: 'Paris is the capital of France.',
93
+ context: [
94
+ 'Paris Hilton is a well-known American media personality.',
95
+ 'The Paris Agreement is a global climate change treaty.',
96
+ 'Paris, Texas is a city in Lamar County.',
97
+ ],
98
+ expectedResult: {
99
+ score: 0.0,
100
+ reason:
101
+ 'All context pieces contain the word "Paris" but are completely irrelevant to the capital of France. Each discusses a different entity (a person, a treaty, and a US city) that just happens to share the name. Matching keywords alone do not constitute relevance when the underlying topics are unrelated.',
102
+ },
103
+ },
104
+ ];
105
+
106
+ const SECONDS = 10000;
107
+
108
+ const openai = createOpenAI({
109
+ apiKey: process.env.OPENAI_API_KEY,
110
+ });
111
+
112
+ const model = openai('gpt-4o');
113
+
114
+ describe(
115
+ 'ContextRelevancyMetric',
116
+ () => {
117
+ it('should detect perfect relevancy when all context pieces directly address the question', async () => {
118
+ const testCase = testCases[0]!;
119
+ const metric = new ContextRelevancyMetric(model, { context: testCase.context });
120
+ const result = await metric.measure(testCase.input, testCase.output);
121
+ expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
122
+ });
123
+
124
+ it('should handle mixed relevancy with some relevant and some tangential context', async () => {
125
+ const testCase = testCases[1]!;
126
+ const metric = new ContextRelevancyMetric(model, { context: testCase.context });
127
+ const result = await metric.measure(testCase.input, testCase.output);
128
+ expect(isCloserTo(result.score, testCase.expectedResult.score, 0)).toBe(true);
129
+ });
130
+
131
+ it('should identify zero relevancy with completely unrelated context', async () => {
132
+ const testCase = testCases[2]!;
133
+ const metric = new ContextRelevancyMetric(model, { context: testCase.context });
134
+ const result = await metric.measure(testCase.input, testCase.output);
135
+ expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
136
+ });
137
+
138
+ it('should evaluate temporal relevancy with mix of current and historical context', async () => {
139
+ const testCase = testCases[3]!;
140
+ const metric = new ContextRelevancyMetric(model, { context: testCase.context });
141
+ const result = await metric.measure(testCase.input, testCase.output);
142
+ expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
143
+ });
144
+
145
+ it('should handle high relevancy with varying levels of detail', async () => {
146
+ const testCase = testCases[4]!;
147
+ const metric = new ContextRelevancyMetric(model, { context: testCase.context });
148
+ const result = await metric.measure(testCase.input, testCase.output);
149
+ expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
150
+ });
151
+
152
+ it('should detect low relevancy with misleading keyword matches', async () => {
153
+ const testCase = testCases[5]!;
154
+ const metric = new ContextRelevancyMetric(model, { context: testCase.context });
155
+ const result = await metric.measure(testCase.input, testCase.output);
156
+ expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
157
+ });
158
+ },
159
+ {
160
+ timeout: 15 * SECONDS,
161
+ },
162
+ );
@@ -0,0 +1,59 @@
1
+ import { Metric } from '@mastra/core/eval';
2
+ import type { LanguageModel } from '@mastra/core/llm';
3
+
4
+ import type { MetricResultWithReason } from '../types';
5
+ import { roundToTwoDecimals } from '../utils';
6
+
7
+ import { ContextRelevancyJudge } from './metricJudge';
8
+
9
+ export interface ContextRelevancyOptions {
10
+ scale?: number;
11
+ context: string[];
12
+ }
13
+
14
+ export class ContextRelevancyMetric extends Metric {
15
+ private judge: ContextRelevancyJudge;
16
+ private scale: number;
17
+ private context: string[];
18
+
19
+ constructor(model: LanguageModel, { scale = 1, context }: ContextRelevancyOptions) {
20
+ super();
21
+
22
+ this.context = context;
23
+ this.judge = new ContextRelevancyJudge(model);
24
+ this.scale = scale;
25
+ }
26
+
27
+ async measure(input: string, output: string): Promise<MetricResultWithReason> {
28
+ const verdicts = await this.judge.evaluate(input, output, this.context);
29
+ const score = this.calculateScore(verdicts);
30
+
31
+ const irrelevancies = verdicts.filter(v => v.verdict.toLowerCase() === 'no').map(v => v.reason);
32
+ const relevantStatements = verdicts.filter(v => v.verdict.toLowerCase() === 'no').map(v => v.reason);
33
+ const reason = await this.judge.getReason({
34
+ input,
35
+ irrelevancies,
36
+ relevantStatements,
37
+ score,
38
+ });
39
+
40
+ return {
41
+ score,
42
+ info: {
43
+ reason,
44
+ },
45
+ };
46
+ }
47
+
48
+ private calculateScore(verdicts: { verdict: string; reason: string }[]): number {
49
+ const totalVerdicts = verdicts?.length || 0;
50
+ if (totalVerdicts === 0) {
51
+ return 0;
52
+ }
53
+
54
+ const relevantVerdicts = verdicts.filter(v => v.verdict.toLowerCase() === 'yes');
55
+
56
+ const score = relevantVerdicts.length / totalVerdicts;
57
+ return roundToTwoDecimals(score * this.scale);
58
+ }
59
+ }
@@ -0,0 +1,51 @@
1
+ import type { LanguageModel } from '@mastra/core/llm';
2
+ import { z } from 'zod';
3
+
4
+ import { MastraAgentJudge } from '../../judge';
5
+
6
+ import { CONTEXT_RELEVANCY_AGENT_INSTRUCTIONS, generateEvaluatePrompt, generateReasonPrompt } from './prompts';
7
+
8
+ export class ContextRelevancyJudge extends MastraAgentJudge {
9
+ constructor(model: LanguageModel) {
10
+ super('Context Relevancy', CONTEXT_RELEVANCY_AGENT_INSTRUCTIONS, model);
11
+ }
12
+
13
+ async evaluate(
14
+ input: string,
15
+ actualOutput: string,
16
+ retrievalContext: string[],
17
+ ): Promise<{ verdict: string; reason: string }[]> {
18
+ const prompt = generateEvaluatePrompt({
19
+ input,
20
+ output: actualOutput,
21
+ context: retrievalContext,
22
+ });
23
+ const result = await this.agent.generate(prompt, {
24
+ output: z.object({
25
+ verdicts: z.array(
26
+ z.object({
27
+ verdict: z.string(),
28
+ reason: z.string(),
29
+ }),
30
+ ),
31
+ }),
32
+ });
33
+
34
+ return result.object.verdicts;
35
+ }
36
+
37
+ async getReason(args: {
38
+ score: number;
39
+ input: string;
40
+ irrelevancies: string[];
41
+ relevantStatements: string[];
42
+ }): Promise<string> {
43
+ const prompt = generateReasonPrompt(args);
44
+ const result = await this.agent.generate(prompt, {
45
+ output: z.object({
46
+ reason: z.string(),
47
+ }),
48
+ });
49
+ return result.object.reason;
50
+ }
51
+ }
@@ -0,0 +1,111 @@
1
+ export const CONTEXT_RELEVANCY_AGENT_INSTRUCTIONS = `You are a balanced and nuanced context relevancy evaluator. Your job is to determine if retrieved context nodes are overall relevant to given input.
2
+
3
+ Key Principles:
4
+ 1. Evaluate whether each context node was useful in generating the given input
5
+ 2. Consider all forms of relevance:
6
+ - Direct definitions or explanations
7
+ - Supporting evidence or examples
8
+ - Related characteristics or behaviors
9
+ - Real-world applications or effects
10
+ 3. Prioritize usefulness over completeness
11
+ 4. Recognize that some nodes may be partially relevant
12
+ 5. Empty or error nodes should be marked as not relevant`;
13
+
14
+ export function generateEvaluatePrompt({
15
+ input,
16
+ output,
17
+ context,
18
+ }: {
19
+ input: string;
20
+ output: string;
21
+ context: string[];
22
+ }) {
23
+ return `Based on the input and context, please generate a JSON object to indicate whether each statement found in the context is relevant to the provided input. First extract high-level statements from the context, then evaluate each for relevance.
24
+ You should first extract statements found in the context, which are high level information found in the context, before deciding on a verdict and a reason for each statement.
25
+
26
+ Each verdict in the JSON must have:
27
+ 1. 'statement': The high-level information extracted from context
28
+ 2. 'verdict': STRICTLY either 'yes' or 'no'
29
+ 3. 'reason': REQUIRED for ALL verdicts to explain the evaluation
30
+
31
+ For 'yes' verdicts:
32
+ - Explain how the statement helps answer or address the input
33
+ - Highlight specific relevant details or connections
34
+
35
+ For 'no' verdicts:
36
+ - Quote the irrelevant parts of the statement
37
+ - Explain why they don't help address the input
38
+
39
+ **
40
+ IMPORTANT: Please make sure to only return in JSON format.
41
+ Example Context: "Einstein won the Nobel Prize for his discovery of the photoelectric effect in 1921. He published his theory of relativity in 1905. There was a cat in his office."
42
+ Example Input: "What were some of Einstein's achievements?"
43
+
44
+ Example:
45
+ {{
46
+ "verdicts": [
47
+ {{
48
+ "verdict": "yes",
49
+ "statement": "Einstein won the Nobel Prize for his discovery of the photoelectric effect",
50
+ "reason": "This directly addresses Einstein's achievements by highlighting a major scientific contribution that was recognized with a Nobel Prize"
51
+ }},
52
+ {{
53
+ "verdict": "yes",
54
+ "statement": "Einstein published his theory of relativity in 1905",
55
+ "reason": "This is highly relevant as it describes one of Einstein's most significant scientific achievements and when it occurred"
56
+ }},
57
+ {{
58
+ "verdict": "no",
59
+ "statement": "There was a cat in his office",
60
+ "reason": "The statement 'There was a cat in his office' is unrelated to Einstein's achievements. While it's a detail about his workspace, it doesn't describe any scientific or professional accomplishments"
61
+ }}
62
+ ]
63
+ }}
64
+ **
65
+
66
+ Input:
67
+ ${input}
68
+
69
+ Output:
70
+ ${output}
71
+ Context:
72
+ ${context.join('\n')}
73
+ `;
74
+ }
75
+
76
+ export function generateReasonPrompt({
77
+ score,
78
+ input,
79
+ irrelevancies,
80
+ relevantStatements,
81
+ }: {
82
+ score: number;
83
+ input: string;
84
+ irrelevancies: string[];
85
+ relevantStatements: string[];
86
+ }) {
87
+ return `Based on the given input, reasons for why the retrieval context is irrelevant to the input, the statements in the retrieval context that is actually relevant to the retrieval context, and the contextual relevancy score (the closer to 1 the better), please generate a CONCISE reason for the score.
88
+ In your reason, you should quote data provided in the reasons for irrelevancy and relevant statements to support your point.
89
+
90
+ **
91
+ IMPORTANT: Please make sure to only return in JSON format, with the 'reason' key providing the reason.
92
+ Example JSON:
93
+ {{
94
+ "reason": "The score is <contextual_relevancy_score> because <your_reason>."
95
+ }}
96
+
97
+ If the score is 1, keep it short and say something positive with an upbeat encouraging tone (but don't overdo it otherwise it gets annoying).
98
+ **
99
+
100
+ Contextual Relevancy Score:
101
+ ${score}
102
+
103
+ Input:
104
+ ${input}
105
+
106
+ Reasons for why the retrieval context is irrelevant to the input:
107
+ ${irrelevancies}
108
+
109
+ Statement in the retrieval context that is relevant to the input:
110
+ ${relevantStatements}`;
111
+ }
@@ -0,0 +1,90 @@
1
+ import { createOpenAI } from '@ai-sdk/openai';
2
+ import { describe, it, expect } from 'vitest';
3
+
4
+ import type { TestCaseWithContext } from '../utils';
5
+ import { isCloserTo } from '../utils';
6
+
7
+ import { ContextualRecallMetric } from './index';
8
+
9
+ const testCases: TestCaseWithContext[] = [
10
+ {
11
+ input: `What are the health benefits of drinking green tea?`,
12
+ output:
13
+ 'Green tea contains powerful antioxidants called catechins that help fight free radicals. It has been shown to boost metabolism and aid in weight loss. Regular consumption may reduce the risk of heart disease by lowering bad cholesterol levels. Studies have also linked green tea to improved brain function and potential cancer-fighting properties.',
14
+ context: [
15
+ 'Green tea is rich in catechins, which are powerful antioxidants that neutralize harmful free radicals in the body.',
16
+ 'Research shows that the compounds in green tea can increase metabolic rate and promote fat burning.',
17
+ 'Regular green tea consumption has been linked to reduced levels of LDL (bad) cholesterol, potentially lowering heart disease risk.',
18
+ 'Studies indicate that green tea may enhance cognitive function and contains compounds that could help prevent certain types of cancer.',
19
+ ],
20
+ expectedResult: {
21
+ score: 1.0,
22
+ },
23
+ },
24
+ {
25
+ input: `What were the major causes of World War I?`,
26
+ output:
27
+ '"World War I was triggered by the assassination of Archduke Franz Ferdinand. The underlying causes included militarism among European powers, a complex system of alliances, imperialism and competition for colonies, and rising nationalism. The alliance system drew various nations into the conflict, turning it into a global war. Economic competition between major powers also played a significant role.',
28
+ context: [
29
+ 'The immediate trigger for World War I was the assassination of Archduke Franz Ferdinand in Sarajevo.',
30
+ 'The system of alliances in Europe meant that countries were obligated to support their allies in case of war.',
31
+ 'Military buildup among European nations created an atmosphere of tension and distrust.',
32
+ ],
33
+ expectedResult: {
34
+ score: 0.5,
35
+ },
36
+ },
37
+ {
38
+ input: `What is the process of photosynthesis?`,
39
+ output:
40
+ 'Photosynthesis is the process by which plants convert light energy into chemical energy. It takes place in the chloroplasts, specifically using chlorophyll in the thylakoids. During photosynthesis, plants take in carbon dioxide and water, using sunlight to convert them into glucose and oxygen. This process occurs in two stages: the light-dependent reactions and the Calvin cycle. The glucose produced serves as food for the plant, while the oxygen is released into the atmosphere.',
41
+ context: [
42
+ "Plants are essential for maintaining Earth's ecosystem balance.",
43
+ 'Different species of plants have evolved various adaptations to survive in their environments.',
44
+ 'The agricultural revolution led to humans cultivating plants for food production.',
45
+ 'Deforestation poses a significant threat to plant biodiversity worldwide.',
46
+ ],
47
+ expectedResult: {
48
+ score: 0,
49
+ },
50
+ },
51
+ ];
52
+
53
+ const SECONDS = 10000;
54
+
55
+ const openai = createOpenAI({
56
+ apiKey: process.env.OPENAI_API_KEY,
57
+ });
58
+
59
+ const model = openai('gpt-4o');
60
+
61
+ describe(
62
+ 'ContextualRecallMetric',
63
+ () => {
64
+ it('should succeed when context is relevant', async () => {
65
+ const testCase = testCases[0]!;
66
+ const metric = new ContextualRecallMetric(model, { context: testCase.context });
67
+ const result = await metric.measure(testCase.input, testCase.output);
68
+ expect(result.score).toBeCloseTo(testCase.expectedResult.score, 2);
69
+ });
70
+
71
+ it('should be mixed', async () => {
72
+ const testCase = testCases[1]!;
73
+ const metric = new ContextualRecallMetric(model, { context: testCase.context });
74
+ const result = await metric.measure(testCase.input, testCase.output);
75
+ console.log(result.score, testCase.expectedResult.score);
76
+
77
+ expect(isCloserTo(result.score, testCase.expectedResult.score, 1)).toBe(true);
78
+ });
79
+
80
+ it('should be none', async () => {
81
+ const testCase = testCases[2]!;
82
+ const metric = new ContextualRecallMetric(model, { context: testCase.context });
83
+ const result = await metric.measure(testCase.input, testCase.output);
84
+ expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
85
+ });
86
+ },
87
+ {
88
+ timeout: 15 * SECONDS,
89
+ },
90
+ );
@@ -0,0 +1,56 @@
1
+ import { Metric } from '@mastra/core/eval';
2
+ import type { LanguageModel } from '@mastra/core/llm';
3
+
4
+ import type { MetricResultWithReason } from '../types';
5
+ import { roundToTwoDecimals } from '../utils';
6
+
7
+ import { ContextualRecallJudge } from './metricJudge';
8
+
9
+ export interface ContextualRecallMetricOptions {
10
+ scale?: number;
11
+ context: string[];
12
+ }
13
+
14
+ export class ContextualRecallMetric extends Metric {
15
+ private judge: ContextualRecallJudge;
16
+ private scale: number;
17
+ private context: string[];
18
+
19
+ constructor(model: LanguageModel, { scale = 1, context }: ContextualRecallMetricOptions) {
20
+ super();
21
+
22
+ this.context = context;
23
+ this.judge = new ContextualRecallJudge(model);
24
+ this.scale = scale;
25
+ }
26
+
27
+ async measure(input: string, output: string): Promise<MetricResultWithReason> {
28
+ const verdicts = await this.judge.evaluate(input, output, this.context);
29
+ const score = this.calculateScore(verdicts);
30
+ const reason = await this.judge.getReason({
31
+ score,
32
+ expectedOutput: output,
33
+ supportiveReasons: verdicts.filter(v => v.verdict === 'yes').map(v => v.reason),
34
+ unsupportiveReasons: verdicts.filter(v => v.verdict === 'no').map(v => v.reason),
35
+ });
36
+
37
+ return {
38
+ score,
39
+ info: {
40
+ reason,
41
+ },
42
+ };
43
+ }
44
+
45
+ private calculateScore(verdicts: { verdict: string; reason: string }[]): number {
46
+ const totalVerdicts = verdicts?.length || 0;
47
+ if (totalVerdicts === 0) {
48
+ return 0;
49
+ }
50
+
51
+ const justifiedVerdicts = verdicts.filter(v => v.verdict === 'yes');
52
+
53
+ const score = justifiedVerdicts.length / totalVerdicts;
54
+ return roundToTwoDecimals(score * this.scale);
55
+ }
56
+ }
@@ -0,0 +1,52 @@
1
+ import type { LanguageModel } from '@mastra/core/llm';
2
+ import { z } from 'zod';
3
+
4
+ import { MastraAgentJudge } from '../../judge';
5
+
6
+ import { CONTEXT_RECALL_AGENT_INSTRUCTIONS, generateEvaluatePrompt, generateReasonPrompt } from './prompts';
7
+
8
+ export class ContextualRecallJudge extends MastraAgentJudge {
9
+ constructor(model: LanguageModel) {
10
+ super('Contextual Recall', CONTEXT_RECALL_AGENT_INSTRUCTIONS, model);
11
+ }
12
+
13
+ async evaluate(
14
+ input: string,
15
+ actualOutput: string,
16
+ retrievalContext: string[],
17
+ ): Promise<{ verdict: string; reason: string }[]> {
18
+ const prompt = generateEvaluatePrompt({
19
+ input,
20
+ output: actualOutput,
21
+ context: retrievalContext,
22
+ });
23
+
24
+ const result = await this.agent.generate(prompt, {
25
+ output: z.object({
26
+ verdicts: z.array(
27
+ z.object({
28
+ verdict: z.string(),
29
+ reason: z.string(),
30
+ }),
31
+ ),
32
+ }),
33
+ });
34
+
35
+ return result.object.verdicts;
36
+ }
37
+
38
+ async getReason(args: {
39
+ score: number;
40
+ unsupportiveReasons: string[];
41
+ expectedOutput: string;
42
+ supportiveReasons: string[];
43
+ }): Promise<string> {
44
+ const prompt = generateReasonPrompt(args);
45
+ const result = await this.agent.generate(prompt, {
46
+ output: z.object({
47
+ reason: z.string(),
48
+ }),
49
+ });
50
+ return result.object.reason;
51
+ }
52
+ }
@@ -0,0 +1,82 @@
1
+ export const CONTEXT_RECALL_AGENT_INSTRUCTIONS = `You are a balanced and nuanced contextual recall evaluator. Your job is to determine if retrieved context nodes are aligning to the expected output.`;
2
+
3
+ export function generateEvaluatePrompt({
4
+ input,
5
+ output,
6
+ context,
7
+ }: {
8
+ input: string;
9
+ output: string;
10
+ context: string[];
11
+ }) {
12
+ return `For EACH sentence in the given expected output below, determine whether the sentence can be attributed to the nodes of retrieval contexts. Please generate a list of JSON with two keys: \`verdict\` and \`reason\`.
13
+ The "verdict" key should STRICTLY be either a 'yes' or 'no'. Answer 'yes' if the sentence can be attributed to any parts of the retrieval context, else answer 'no'.
14
+ The "reason" key should provide a reason why to the verdict. In the reason, you should aim to include the node(s) count in the retrieval context (eg., 1st node, and 2nd node in the retrieval context) that is attributed to said sentence. You should also aim to quote the specific part of the retrieval context to justify your verdict, but keep it extremely concise and cut short the quote with an ellipsis if possible.
15
+
16
+ **
17
+ IMPORTANT: Please make sure to only return in JSON format, with the 'verdicts' key as a list of JSON objects, each with two keys: \`verdict\` and \`reason\`.
18
+
19
+ {{
20
+ "verdicts": [
21
+ {{
22
+ "verdict": "yes",
23
+ "reason": "..."
24
+ }},
25
+ ...
26
+ ]
27
+ }}
28
+
29
+ Since you are going to generate a verdict for each sentence, the number of 'verdicts' SHOULD BE STRICTLY EQUAL to the number of sentences in of \`expected output\`.
30
+ **
31
+
32
+ input:
33
+ ${input}
34
+
35
+ Expected Output:
36
+ ${output}
37
+
38
+ Retrieval Context:
39
+ ${context}
40
+ `;
41
+ }
42
+
43
+ export function generateReasonPrompt({
44
+ score,
45
+ unsupportiveReasons,
46
+ expectedOutput,
47
+ supportiveReasons,
48
+ }: {
49
+ score: number;
50
+ unsupportiveReasons: string[];
51
+ expectedOutput: string;
52
+ supportiveReasons: string[];
53
+ }) {
54
+ return `Given the original expected output, a list of supportive reasons, and a list of unsupportive reasons (which is deduced directly from the 'expected output'), and a contextual recall score (closer to 1 the better), summarize a CONCISE reason for the score.
55
+ A supportive reason is the reason why a certain sentence in the original expected output can be attributed to the node in the retrieval context.
56
+ An unsupportive reason is the reason why a certain sentence in the original expected output cannot be attributed to anything in the retrieval context.
57
+ In your reason, you should related supportive/unsupportive reasons to the sentence number in expected output, and info regarding the node number in retrieval context to support your final reason. The first mention of "node(s)" should specify "node(s) in retrieval context)".
58
+
59
+ **
60
+ IMPORTANT: Please make sure to only return in JSON format, with the 'reason' key providing the reason.
61
+ Example JSON:
62
+ {{
63
+ "reason": "The score is <contextual_recall_score> because <your_reason>."
64
+ }}
65
+
66
+ DO NOT mention 'supportive reasons' and 'unsupportive reasons' in your reason, these terms are just here for you to understand the broader scope of things.
67
+ If the score is 1, keep it short and say something positive with an upbeat encouraging tone (but don't overdo it otherwise it gets annoying).
68
+ **
69
+
70
+ Contextual Recall Score:
71
+ ${score}
72
+
73
+ Expected Output:
74
+ ${expectedOutput}
75
+
76
+ Supportive Reasons:
77
+ ${supportiveReasons.join('\n')}
78
+
79
+ Unsupportive Reasons:
80
+ ${unsupportiveReasons.join('\n')}
81
+ `;
82
+ }