@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.
- package/.turbo/turbo-build.log +37 -0
- package/CHANGELOG.md +777 -0
- package/LICENSE +44 -0
- package/README.md +185 -0
- package/dist/_tsup-dts-rollup.d.cts +764 -0
- package/dist/_tsup-dts-rollup.d.ts +764 -0
- package/dist/chunk-4VNS5WPM.js +37 -0
- package/dist/chunk-TXXJUIES.js +15 -0
- package/dist/dist-MSGH6PAG.js +17947 -0
- package/dist/index.cjs +19675 -0
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +86 -0
- package/dist/magic-string.es-5UDOWOAZ.js +1296 -0
- package/dist/metrics/judge/index.cjs +17 -0
- package/dist/metrics/judge/index.d.cts +1 -0
- package/dist/metrics/judge/index.d.ts +1 -0
- package/dist/metrics/judge/index.js +2 -0
- package/dist/metrics/llm/index.cjs +2482 -0
- package/dist/metrics/llm/index.d.cts +11 -0
- package/dist/metrics/llm/index.d.ts +11 -0
- package/dist/metrics/llm/index.js +2459 -0
- package/dist/metrics/nlp/index.cjs +202 -0
- package/dist/metrics/nlp/index.d.cts +5 -0
- package/dist/metrics/nlp/index.d.ts +5 -0
- package/dist/metrics/nlp/index.js +189 -0
- package/eslint.config.js +6 -0
- package/package.json +89 -0
- package/src/attachListeners.ts +40 -0
- package/src/constants.ts +1 -0
- package/src/evaluation.test.ts +29 -0
- package/src/evaluation.ts +58 -0
- package/src/index.ts +2 -0
- package/src/metrics/index.ts +3 -0
- package/src/metrics/judge/index.ts +14 -0
- package/src/metrics/llm/answer-relevancy/index.test.ts +156 -0
- package/src/metrics/llm/answer-relevancy/index.ts +58 -0
- package/src/metrics/llm/answer-relevancy/metricJudge.ts +56 -0
- package/src/metrics/llm/answer-relevancy/prompts.ts +214 -0
- package/src/metrics/llm/bias/index.test.ts +152 -0
- package/src/metrics/llm/bias/index.ts +52 -0
- package/src/metrics/llm/bias/metricJudge.ts +53 -0
- package/src/metrics/llm/bias/prompts.ts +109 -0
- package/src/metrics/llm/context-position/index.test.ts +275 -0
- package/src/metrics/llm/context-position/index.ts +69 -0
- package/src/metrics/llm/context-position/metricJudge.ts +55 -0
- package/src/metrics/llm/context-position/prompts.ts +135 -0
- package/src/metrics/llm/context-precision/index.test.ts +213 -0
- package/src/metrics/llm/context-precision/index.ts +68 -0
- package/src/metrics/llm/context-precision/metricJudge.ts +55 -0
- package/src/metrics/llm/context-precision/prompts.ts +139 -0
- package/src/metrics/llm/context-relevancy/index.test.ts +162 -0
- package/src/metrics/llm/context-relevancy/index.ts +59 -0
- package/src/metrics/llm/context-relevancy/metricJudge.ts +51 -0
- package/src/metrics/llm/context-relevancy/prompts.ts +111 -0
- package/src/metrics/llm/contextual-recall/index.test.ts +90 -0
- package/src/metrics/llm/contextual-recall/index.ts +56 -0
- package/src/metrics/llm/contextual-recall/metricJudge.ts +52 -0
- package/src/metrics/llm/contextual-recall/prompts.ts +82 -0
- package/src/metrics/llm/faithfulness/index.test.ts +254 -0
- package/src/metrics/llm/faithfulness/index.ts +59 -0
- package/src/metrics/llm/faithfulness/metricJudge.ts +62 -0
- package/src/metrics/llm/faithfulness/prompts.ts +166 -0
- package/src/metrics/llm/hallucination/index.test.ts +214 -0
- package/src/metrics/llm/hallucination/index.ts +59 -0
- package/src/metrics/llm/hallucination/metricJudge.ts +44 -0
- package/src/metrics/llm/hallucination/prompts.ts +143 -0
- package/src/metrics/llm/index.ts +11 -0
- package/src/metrics/llm/prompt-alignment/index.test.ts +335 -0
- package/src/metrics/llm/prompt-alignment/index.ts +116 -0
- package/src/metrics/llm/prompt-alignment/metricJudge.ts +43 -0
- package/src/metrics/llm/prompt-alignment/prompts.ts +224 -0
- package/src/metrics/llm/summarization/index.test.ts +274 -0
- package/src/metrics/llm/summarization/index.ts +72 -0
- package/src/metrics/llm/summarization/metricJudge.ts +101 -0
- package/src/metrics/llm/summarization/prompts.ts +252 -0
- package/src/metrics/llm/toxicity/index.test.ts +84 -0
- package/src/metrics/llm/toxicity/index.ts +54 -0
- package/src/metrics/llm/toxicity/metricJudge.ts +39 -0
- package/src/metrics/llm/toxicity/prompts.ts +87 -0
- package/src/metrics/llm/types.ts +7 -0
- package/src/metrics/llm/utils.ts +20 -0
- package/src/metrics/nlp/completeness/index.test.ts +98 -0
- package/src/metrics/nlp/completeness/index.ts +121 -0
- package/src/metrics/nlp/content-similarity/index.test.ts +76 -0
- package/src/metrics/nlp/content-similarity/index.ts +49 -0
- package/src/metrics/nlp/index.ts +5 -0
- package/src/metrics/nlp/keyword-coverage/index.test.ts +85 -0
- package/src/metrics/nlp/keyword-coverage/index.ts +49 -0
- package/src/metrics/nlp/textual-difference/index.test.ts +88 -0
- package/src/metrics/nlp/textual-difference/index.ts +38 -0
- package/src/metrics/nlp/tone/index.test.ts +100 -0
- package/src/metrics/nlp/tone/index.ts +55 -0
- package/tsconfig.json +5 -0
- package/vitest.config.ts +12 -0
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
export const PROMPT_ALIGNMENT_AGENT_INSTRUCTIONS = `You are a strict and thorough prompt alignment evaluator. Your job is to determine if LLM outputs follow their given prompt instructions exactly.
|
|
2
|
+
|
|
3
|
+
Key Principles:
|
|
4
|
+
1. First determine if an instruction is APPLICABLE to the given input/output context
|
|
5
|
+
2. For applicable instructions, be EXTRA STRICT in evaluation
|
|
6
|
+
3. Only give a "yes" verdict if an instruction is COMPLETELY followed
|
|
7
|
+
4. Mark instructions as "n/a" (not applicable) ONLY when they are about a completely different domain
|
|
8
|
+
5. Provide clear, specific reasons for ALL verdicts
|
|
9
|
+
6. Focus solely on instruction compliance, not output quality
|
|
10
|
+
7. Judge each instruction independently
|
|
11
|
+
|
|
12
|
+
Remember:
|
|
13
|
+
- Each instruction must be evaluated independently
|
|
14
|
+
- Verdicts must be "yes", "no", or "n/a" (not applicable)
|
|
15
|
+
- Reasons are REQUIRED for ALL verdicts to explain the evaluation
|
|
16
|
+
- The number of verdicts must match the number of instructions exactly`;
|
|
17
|
+
|
|
18
|
+
export function generateEvaluatePrompt({
|
|
19
|
+
instructions,
|
|
20
|
+
input,
|
|
21
|
+
output,
|
|
22
|
+
}: {
|
|
23
|
+
instructions: string[];
|
|
24
|
+
input: string;
|
|
25
|
+
output: string;
|
|
26
|
+
}) {
|
|
27
|
+
return `For the provided list of prompt instructions, determine whether each instruction has been followed in the LLM output.
|
|
28
|
+
First determine if each instruction is applicable to the given context, then evaluate compliance for applicable instructions.
|
|
29
|
+
Important Guidelines:
|
|
30
|
+
1. For empty outputs:
|
|
31
|
+
- ALL formatting instructions (capitalization, punctuation, etc.) are applicable
|
|
32
|
+
- Mark them as "no" since empty output cannot satisfy formatting requirements
|
|
33
|
+
2. For domain-specific instructions:
|
|
34
|
+
- Instructions about the queried domain are ALWAYS applicable
|
|
35
|
+
- Mark as "no" if not followed, not "n/a"
|
|
36
|
+
3. Only mark as "n/a" when instruction is about a completely different domain
|
|
37
|
+
|
|
38
|
+
Generate a list of verdicts in JSON format, where each verdict must have:
|
|
39
|
+
- "verdict": Must be one of:
|
|
40
|
+
- "yes": Instruction is applicable and COMPLETELY followed
|
|
41
|
+
- "no": Instruction is applicable but not followed or only partially followed
|
|
42
|
+
- "n/a": Instruction is not applicable to this context
|
|
43
|
+
- "reason": REQUIRED for ALL verdicts to explain the evaluation
|
|
44
|
+
|
|
45
|
+
Example 1: Empty Output
|
|
46
|
+
Input: "What's the weather?"
|
|
47
|
+
Output: ""
|
|
48
|
+
Instructions: [
|
|
49
|
+
"Reply in all uppercase",
|
|
50
|
+
"Show account balance"
|
|
51
|
+
]
|
|
52
|
+
{
|
|
53
|
+
"verdicts": [
|
|
54
|
+
{
|
|
55
|
+
"verdict": "no",
|
|
56
|
+
"reason": "Empty output cannot satisfy the uppercase formatting requirement"
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
"verdict": "n/a",
|
|
60
|
+
"reason": "This is a weather query, account balance is not applicable"
|
|
61
|
+
}
|
|
62
|
+
]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
Example 2: Weather Query with Mixed Instructions
|
|
66
|
+
Input: "What's the weather in Paris?"
|
|
67
|
+
Output: "It's clear in Paris."
|
|
68
|
+
Instructions: [
|
|
69
|
+
"Include temperature in weather reports",
|
|
70
|
+
"Analyze transaction patterns",
|
|
71
|
+
"Use proper English"
|
|
72
|
+
]
|
|
73
|
+
{
|
|
74
|
+
"verdicts": [
|
|
75
|
+
{
|
|
76
|
+
"verdict": "no",
|
|
77
|
+
"reason": "Temperature is not included in the weather report"
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
"verdict": "n/a",
|
|
81
|
+
"reason": "This is a weather query, transaction analysis is not applicable"
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
"verdict": "yes",
|
|
85
|
+
"reason": "The response uses proper English with correct grammar and punctuation"
|
|
86
|
+
}
|
|
87
|
+
]
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
Example 3: Weather Query with Multiple Requirements
|
|
91
|
+
Input: "What's the weather in Paris?"
|
|
92
|
+
Output: "The temperature is 22°C in Paris"
|
|
93
|
+
Instructions: [
|
|
94
|
+
"Include temperature in weather reports",
|
|
95
|
+
"Mention wind conditions",
|
|
96
|
+
"End with a period"
|
|
97
|
+
]
|
|
98
|
+
{
|
|
99
|
+
"verdicts": [
|
|
100
|
+
{
|
|
101
|
+
"verdict": "yes",
|
|
102
|
+
"reason": "Temperature (22°C) is included in the report"
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
"verdict": "no",
|
|
106
|
+
"reason": "Wind conditions are not mentioned in the weather report"
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
"verdict": "no",
|
|
110
|
+
"reason": "The response does not end with a period"
|
|
111
|
+
}
|
|
112
|
+
]
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
Now evaluate the following:
|
|
116
|
+
Input: ${JSON.stringify(input)}
|
|
117
|
+
Output: ${JSON.stringify(output)}
|
|
118
|
+
Instructions: ${JSON.stringify(instructions, null, 2)}
|
|
119
|
+
|
|
120
|
+
{
|
|
121
|
+
"verdicts": [
|
|
122
|
+
{
|
|
123
|
+
"verdict": "no",
|
|
124
|
+
"reason": "Temperature is not included in the weather report"
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
"verdict": "n/a",
|
|
128
|
+
"reason": "This is a weather query, transaction analysis is not applicable"
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
"verdict": "yes",
|
|
132
|
+
"reason": "Response uses proper English with correct grammar and punctuation"
|
|
133
|
+
}
|
|
134
|
+
]
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
Example 2: Transaction Query with Incomplete Analysis
|
|
138
|
+
Input: "Review my recent spending"
|
|
139
|
+
Output: "You spent money this month."
|
|
140
|
+
Instructions: [
|
|
141
|
+
"Include temperature in weather reports",
|
|
142
|
+
"Analyze transaction patterns",
|
|
143
|
+
"Use proper English",
|
|
144
|
+
"Provide specific insights"
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
{
|
|
148
|
+
"verdicts": [
|
|
149
|
+
{
|
|
150
|
+
"verdict": "n/a",
|
|
151
|
+
"reason": "This is a transaction query, weather information is not applicable"
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
"verdict": "no",
|
|
155
|
+
"reason": "No analysis of patterns or trends is provided, just a basic statement"
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
"verdict": "yes",
|
|
159
|
+
"reason": "Response uses correct English grammar and structure"
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
"verdict": "no",
|
|
163
|
+
"reason": "Response lacks specific details or actionable insights about spending"
|
|
164
|
+
}
|
|
165
|
+
]
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
Number of instructions: ${instructions.length}
|
|
169
|
+
|
|
170
|
+
Prompt Instructions:
|
|
171
|
+
${instructions}
|
|
172
|
+
|
|
173
|
+
Input:
|
|
174
|
+
${input}
|
|
175
|
+
|
|
176
|
+
LLM Actual Output:
|
|
177
|
+
${output}
|
|
178
|
+
|
|
179
|
+
JSON:`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function generateReasonPrompt({
|
|
183
|
+
input,
|
|
184
|
+
output,
|
|
185
|
+
score,
|
|
186
|
+
verdicts,
|
|
187
|
+
scale,
|
|
188
|
+
}: {
|
|
189
|
+
input: string;
|
|
190
|
+
output: string;
|
|
191
|
+
score: number;
|
|
192
|
+
verdicts: { verdict: string; reason: string }[];
|
|
193
|
+
scale: number;
|
|
194
|
+
}) {
|
|
195
|
+
return `Explain the instruction following score where 0 is the lowest and ${scale} is the highest for the LLM's response using this context:
|
|
196
|
+
Context:
|
|
197
|
+
Input: ${input}
|
|
198
|
+
Output: ${output}
|
|
199
|
+
Score: ${score}
|
|
200
|
+
Verdicts: ${JSON.stringify(verdicts)}
|
|
201
|
+
|
|
202
|
+
Rules (follow these rules exactly. do not deviate):
|
|
203
|
+
- Keep your response concise and to the point
|
|
204
|
+
- Do not change score from what is given
|
|
205
|
+
- Do not make judgements on inputs or outputs (factual correctness, quality, etc)
|
|
206
|
+
- Focus on how well the output aligns with the given instructions
|
|
207
|
+
- Explain what aspects of instruction alignment affected the score
|
|
208
|
+
- Do not reference the verdicts themselves in your explanation
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
Output format:
|
|
212
|
+
{
|
|
213
|
+
"reason": "The score is {score} because {explanation of instruction following}"
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
Example Responses:
|
|
217
|
+
{
|
|
218
|
+
"reason": "The score is ${scale} because the output fully aligns with all applicable instructions, providing clear and actionable information while maintaining a professional tone"
|
|
219
|
+
}
|
|
220
|
+
{
|
|
221
|
+
"reason": "The score is 0 because the output does not follow the instructions"
|
|
222
|
+
}
|
|
223
|
+
`;
|
|
224
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import { createOpenAI } from '@ai-sdk/openai';
|
|
2
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import type { TestCase } from '../utils';
|
|
5
|
+
import { isCloserTo } from '../utils';
|
|
6
|
+
|
|
7
|
+
import { SummarizationMetric } from './index';
|
|
8
|
+
|
|
9
|
+
const openai = createOpenAI({
|
|
10
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const model = openai('gpt-4o');
|
|
14
|
+
|
|
15
|
+
const testCases: TestCase[] = [
|
|
16
|
+
{
|
|
17
|
+
// Perfect summarization
|
|
18
|
+
input:
|
|
19
|
+
'The company XYZ was founded in 2010 in San Francisco. They specialize in artificial intelligence and have developed several groundbreaking products. Their flagship product, launched in 2015, has over 1 million users worldwide.',
|
|
20
|
+
output:
|
|
21
|
+
'XYZ, founded in 2010 in San Francisco, is an AI company known for their groundbreaking products. Their main product, released in 2015, serves over 1 million users globally.',
|
|
22
|
+
expectedResult: {
|
|
23
|
+
score: 1.0,
|
|
24
|
+
reason:
|
|
25
|
+
'The summary accurately captures all key information and contains no contradictions or unsupported claims',
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
// Mixed accuracy with contradictions
|
|
30
|
+
input:
|
|
31
|
+
'The company XYZ was founded in 2010 in San Francisco. They specialize in artificial intelligence and have developed several groundbreaking products. Their flagship product, launched in 2015, has over 1 million users worldwide.',
|
|
32
|
+
output: 'XYZ, founded in 2012 in San Francisco, is an AI company. Their main product has 2 million users globally.',
|
|
33
|
+
expectedResult: {
|
|
34
|
+
score: 0.33,
|
|
35
|
+
reason:
|
|
36
|
+
'Contains both accurate information (location, AI focus) and contradictions (founding year, user count). Misses key information about product launch date and multiple products. Incorrect numbers are treated as contradictions, not approximations.',
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
// Missing key information
|
|
41
|
+
input:
|
|
42
|
+
'The company XYZ was founded in 2010 in San Francisco. They specialize in artificial intelligence and have developed several groundbreaking products. Their flagship product, launched in 2015, has over 1 million users worldwide.',
|
|
43
|
+
output: 'XYZ is a technology company based in San Francisco.',
|
|
44
|
+
expectedResult: {
|
|
45
|
+
score: 0.2,
|
|
46
|
+
reason:
|
|
47
|
+
'While factually accurate about location, the summary omits founding year, AI focus, products, and user base. Tech company claim is unverifiable.',
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
// Empty output
|
|
52
|
+
input: 'The company XYZ was founded in 2010 in San Francisco.',
|
|
53
|
+
output: '',
|
|
54
|
+
expectedResult: {
|
|
55
|
+
score: 0,
|
|
56
|
+
reason: 'No summary provided for evaluation',
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
// Speculative additions
|
|
61
|
+
input: 'The company XYZ was founded in 2010 in San Francisco.',
|
|
62
|
+
output: 'XYZ, founded in 2010 in San Francisco, might expand to Europe next year and could become a market leader.',
|
|
63
|
+
expectedResult: {
|
|
64
|
+
score: 0.5,
|
|
65
|
+
reason:
|
|
66
|
+
'The factual claims about founding year and location are correct, but includes unsupported speculative claims about expansion and market position',
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
// Incorrect emphasis
|
|
71
|
+
input:
|
|
72
|
+
'The company XYZ was founded in 2010 in San Francisco. Their groundbreaking AI product has transformed the industry.',
|
|
73
|
+
output: 'XYZ, a San Francisco company since 2010, has offices worldwide.',
|
|
74
|
+
expectedResult: {
|
|
75
|
+
score: 0.5,
|
|
76
|
+
reason:
|
|
77
|
+
'While location and founding date are correct, misses key AI impact and adds unsupported claims about offices',
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
// Technical accuracy with missing context
|
|
82
|
+
input: `XYZ's AI platform processes 1 million transactions per second using distributed computing. The system was developed over 5 years with a team of 100 engineers.`,
|
|
83
|
+
output: `XYZ's platform handles 1 million transactions per second.`,
|
|
84
|
+
expectedResult: {
|
|
85
|
+
score: 0.25,
|
|
86
|
+
reason:
|
|
87
|
+
'While the transaction speed is accurately reported (perfect alignment), the summary omits crucial technical context about AI, distributed computing, development time, and team size (poor coverage: 1/4 key points).',
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
// Numerical approximation
|
|
92
|
+
input: 'XYZ has 1,023 employees across 12 offices.',
|
|
93
|
+
output: 'XYZ employs approximately 1,000 people in multiple offices.',
|
|
94
|
+
expectedResult: {
|
|
95
|
+
score: 0,
|
|
96
|
+
reason: 'While using acceptable approximations, fails to precisely convey the specific numbers from the source',
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
// Mixed tenses
|
|
101
|
+
input: 'XYZ launched in 2010 and has grown steadily. They plan to expand next year.',
|
|
102
|
+
output: 'XYZ, which started in 2010, continues to grow and has future expansion plans.',
|
|
103
|
+
expectedResult: {
|
|
104
|
+
score: 0.33,
|
|
105
|
+
reason:
|
|
106
|
+
'While factually accurate, the summary unnecessarily loses precision by making specific details vague (steady growth → continues to grow, next year → future plans) without gaining brevity or clarity.',
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
// Subjective interpretation
|
|
111
|
+
input: `XYZ's revenue grew by 50% last year, reaching $100 million.`,
|
|
112
|
+
output: 'XYZ had an impressive year with substantial revenue growth to $100 million.',
|
|
113
|
+
expectedResult: {
|
|
114
|
+
score: 0.5,
|
|
115
|
+
reason:
|
|
116
|
+
'While revenue numbers are accurate, adds subjective interpretation ("impressive") and omits specific growth percentage',
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
// High alignment, low coverage
|
|
121
|
+
input: `The company ABC was founded in 2020 in New York. They have developed revolutionary quantum computing technology.
|
|
122
|
+
Their first product achieved quantum supremacy in 2022. The team consists of 50 PhD researchers and has secured $100M in funding.
|
|
123
|
+
They have partnerships with major tech companies and are expanding into Europe.`,
|
|
124
|
+
output: 'ABC is a New York-based company founded in 2020.',
|
|
125
|
+
expectedResult: {
|
|
126
|
+
score: 0.2,
|
|
127
|
+
reason:
|
|
128
|
+
'While all stated facts are accurate (high alignment), the summary misses crucial information about quantum computing, achievements, team, funding, and expansion plans (low coverage).',
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
// Low alignment, high coverage
|
|
133
|
+
input: `The company ABC was founded in 2020 in New York. They have developed revolutionary quantum computing technology.
|
|
134
|
+
Their first product achieved quantum supremacy in 2022.`,
|
|
135
|
+
output: `ABC, founded in 2021 in Boston, has made breakthroughs in quantum computing with their first product achieving quantum supremacy in 2022.
|
|
136
|
+
They are leaders in the quantum computing field.`,
|
|
137
|
+
expectedResult: {
|
|
138
|
+
score: 0.5,
|
|
139
|
+
reason:
|
|
140
|
+
'While the summary covers most key points (high coverage), it contains factual errors about founding year and location (low alignment).',
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
// Single word summary
|
|
145
|
+
input:
|
|
146
|
+
'The company XYZ specializes in artificial intelligence and machine learning, with offices in multiple countries.',
|
|
147
|
+
output: 'AI.',
|
|
148
|
+
expectedResult: {
|
|
149
|
+
score: 0,
|
|
150
|
+
reason: 'While technically accurate, the summary is extremely minimal and misses almost all key information',
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
// Repetitive summary
|
|
155
|
+
input: 'XYZ develops AI solutions for healthcare.',
|
|
156
|
+
output: 'XYZ is an AI company that develops AI solutions. Their AI technology is used in AI applications.',
|
|
157
|
+
expectedResult: {
|
|
158
|
+
score: 0.33,
|
|
159
|
+
reason:
|
|
160
|
+
'While factually correct about AI, the summary is unnecessarily repetitive and fails to mention the healthcare focus',
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
// Summary longer than input
|
|
165
|
+
input: 'XYZ is a tech startup.',
|
|
166
|
+
output:
|
|
167
|
+
'XYZ is a technology company that develops software solutions and might be working on various projects across different sectors with potential future expansion plans.',
|
|
168
|
+
expectedResult: {
|
|
169
|
+
score: 0,
|
|
170
|
+
reason: 'The summary adds many unsupported claims and is inappropriately verbose for the given input',
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
];
|
|
174
|
+
|
|
175
|
+
const SECONDS = 1000;
|
|
176
|
+
|
|
177
|
+
vi.setConfig({
|
|
178
|
+
testTimeout: 30 * SECONDS,
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
describe('SummarizationMetric', () => {
|
|
182
|
+
const metric = new SummarizationMetric(model);
|
|
183
|
+
|
|
184
|
+
it('should handle perfect summarization', async () => {
|
|
185
|
+
const testCase = testCases[0]!;
|
|
186
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
187
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it('should handle mixed accuracy with contradictions', async () => {
|
|
191
|
+
const testCase = testCases[1]!;
|
|
192
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
193
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it('should handle missing key information', async () => {
|
|
197
|
+
const testCase = testCases[2]!;
|
|
198
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
199
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it('should handle empty output', async () => {
|
|
203
|
+
const testCase = testCases[3]!;
|
|
204
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
205
|
+
expect(result.score).toBe(testCase.expectedResult.score);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('should handle speculative additions', async () => {
|
|
209
|
+
const testCase = testCases[4]!;
|
|
210
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
211
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it('should handle incorrect emphasis', async () => {
|
|
215
|
+
const testCase = testCases[5]!;
|
|
216
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
217
|
+
expect(isCloserTo(result.score, testCase.expectedResult.score, 0)).toBe(true);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it('should handle technical accuracy with missing context', async () => {
|
|
221
|
+
const testCase = testCases[6]!;
|
|
222
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
223
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('should handle numerical approximation', async () => {
|
|
227
|
+
const testCase = testCases[7]!;
|
|
228
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
229
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
it('should handle mixed tenses', async () => {
|
|
233
|
+
const testCase = testCases[8]!;
|
|
234
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
235
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it('should handle subjective interpretation', async () => {
|
|
239
|
+
const testCase = testCases[9]!;
|
|
240
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
241
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
it('should handle high alignment with low coverage', async () => {
|
|
245
|
+
const testCase = testCases[10]!;
|
|
246
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
247
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
it('should handle low alignment with high coverage', async () => {
|
|
251
|
+
const testCase = testCases[11]!;
|
|
252
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
253
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
it('should handle single word summary', async () => {
|
|
257
|
+
const testCase = testCases[12]!;
|
|
258
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
259
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it('should handle repetitive summary', async () => {
|
|
263
|
+
const testCase = testCases[13]!;
|
|
264
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
265
|
+
console.log(result.score, testCase.expectedResult.score);
|
|
266
|
+
expect(isCloserTo(result.score, testCase.expectedResult.score, 1)).toBe(true);
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
it('should handle overly verbose summary', async () => {
|
|
270
|
+
const testCase = testCases[14]!;
|
|
271
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
272
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
273
|
+
});
|
|
274
|
+
});
|
|
@@ -0,0 +1,72 @@
|
|
|
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 { SummarizationJudge } from './metricJudge';
|
|
8
|
+
|
|
9
|
+
export interface SummarizationMetricOptions {
|
|
10
|
+
scale?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class SummarizationMetric extends Metric {
|
|
14
|
+
private judge: SummarizationJudge;
|
|
15
|
+
private scale: number;
|
|
16
|
+
|
|
17
|
+
constructor(model: LanguageModel, { scale = 1 }: SummarizationMetricOptions = {}) {
|
|
18
|
+
super();
|
|
19
|
+
|
|
20
|
+
this.judge = new SummarizationJudge(model);
|
|
21
|
+
this.scale = scale;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async measure(
|
|
25
|
+
input: string,
|
|
26
|
+
output: string,
|
|
27
|
+
): Promise<MetricResultWithReason & { info: { alignmentScore: number; coverageScore: number } }> {
|
|
28
|
+
const alignmentVerdicts = await this.judge.evaluateAlignment(input, output);
|
|
29
|
+
const coverageVerdicts = await this.judge.evaluateCoverage(input, output);
|
|
30
|
+
|
|
31
|
+
const alignmentScore = this.calculateScore(alignmentVerdicts);
|
|
32
|
+
const coverageScore = this.calculateScore(coverageVerdicts);
|
|
33
|
+
const finalScore = Math.min(alignmentScore, coverageScore);
|
|
34
|
+
|
|
35
|
+
const reason = await this.judge.getReason({
|
|
36
|
+
originalText: input,
|
|
37
|
+
summary: output,
|
|
38
|
+
alignmentScore,
|
|
39
|
+
coverageScore,
|
|
40
|
+
finalScore,
|
|
41
|
+
alignmentVerdicts,
|
|
42
|
+
coverageVerdicts,
|
|
43
|
+
scale: this.scale,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
score: finalScore,
|
|
48
|
+
info: {
|
|
49
|
+
reason,
|
|
50
|
+
alignmentScore,
|
|
51
|
+
coverageScore,
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private calculateScore(evaluation: { verdict: string; reason: string }[]): number {
|
|
57
|
+
const numberOfVerdicts = evaluation?.length || 0;
|
|
58
|
+
if (numberOfVerdicts === 0) {
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
let positiveCount = 0;
|
|
63
|
+
for (const { verdict } of evaluation!) {
|
|
64
|
+
if (verdict.trim().toLowerCase() === 'yes') {
|
|
65
|
+
positiveCount++;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const score = positiveCount / numberOfVerdicts;
|
|
70
|
+
return roundToTwoDecimals(score * this.scale);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { LanguageModel } from '@mastra/core/llm';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
import { MastraAgentJudge } from '../../judge';
|
|
5
|
+
import { generateClaimExtractionPrompt } from '../faithfulness/prompts';
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
generateAlignmentPrompt,
|
|
9
|
+
generateAnswersPrompt,
|
|
10
|
+
generateQuestionsPrompt,
|
|
11
|
+
generateReasonPrompt,
|
|
12
|
+
SUMMARIZATION_AGENT_INSTRUCTIONS,
|
|
13
|
+
} from './prompts';
|
|
14
|
+
|
|
15
|
+
export class SummarizationJudge extends MastraAgentJudge {
|
|
16
|
+
constructor(model: LanguageModel) {
|
|
17
|
+
super('Summarization', SUMMARIZATION_AGENT_INSTRUCTIONS, model);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async evaluateAlignment(originalText: string, summary: string): Promise<{ verdict: string; reason: string }[]> {
|
|
21
|
+
const claimsPrompt = generateClaimExtractionPrompt({ output: summary });
|
|
22
|
+
const summaryClaims = await this.agent.generate(claimsPrompt, {
|
|
23
|
+
output: z.object({
|
|
24
|
+
claims: z.array(z.string()),
|
|
25
|
+
}),
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const prompt = generateAlignmentPrompt({ originalText, summaryClaims: summaryClaims.object.claims });
|
|
29
|
+
const result = await this.agent.generate(prompt, {
|
|
30
|
+
output: z.object({
|
|
31
|
+
verdicts: z.array(
|
|
32
|
+
z.object({
|
|
33
|
+
claim: z.string(),
|
|
34
|
+
verdict: z.string(),
|
|
35
|
+
reason: z.string(),
|
|
36
|
+
}),
|
|
37
|
+
),
|
|
38
|
+
}),
|
|
39
|
+
});
|
|
40
|
+
return result.object.verdicts;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async evaluateQuestionBasedCoverage(
|
|
44
|
+
originalText: string,
|
|
45
|
+
summary: string,
|
|
46
|
+
): Promise<{
|
|
47
|
+
questions: string[];
|
|
48
|
+
answers: string[];
|
|
49
|
+
}> {
|
|
50
|
+
// Generate questions from original text
|
|
51
|
+
const questionsPrompt = generateQuestionsPrompt({ originalText });
|
|
52
|
+
const questionsResult = await this.agent.generate(questionsPrompt, {
|
|
53
|
+
output: z.object({
|
|
54
|
+
questions: z.array(z.string()),
|
|
55
|
+
}),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// Check if summary can answer these questions
|
|
59
|
+
const answersPrompt = generateAnswersPrompt({
|
|
60
|
+
originalText,
|
|
61
|
+
summary,
|
|
62
|
+
questions: questionsResult.object.questions,
|
|
63
|
+
});
|
|
64
|
+
const answersResult = await this.agent.generate(answersPrompt, {
|
|
65
|
+
output: z.object({
|
|
66
|
+
answers: z.array(z.string()),
|
|
67
|
+
}),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
questions: questionsResult.object.questions,
|
|
72
|
+
answers: answersResult.object.answers,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async evaluateCoverage(originalText: string, summary: string): Promise<{ verdict: string; reason: string }[]> {
|
|
77
|
+
const { questions, answers } = await this.evaluateQuestionBasedCoverage(originalText, summary);
|
|
78
|
+
|
|
79
|
+
const coverageVerdicts = questions.map((question, index) => ({
|
|
80
|
+
verdict: answers[index] as string,
|
|
81
|
+
reason: question,
|
|
82
|
+
}));
|
|
83
|
+
|
|
84
|
+
return coverageVerdicts;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async getReason(args: {
|
|
88
|
+
originalText: string;
|
|
89
|
+
summary: string;
|
|
90
|
+
alignmentScore: number;
|
|
91
|
+
coverageScore: number;
|
|
92
|
+
finalScore: number;
|
|
93
|
+
alignmentVerdicts: { verdict: string; reason: string }[];
|
|
94
|
+
coverageVerdicts: { verdict: string; reason: string }[];
|
|
95
|
+
scale: number;
|
|
96
|
+
}): Promise<string> {
|
|
97
|
+
const prompt = generateReasonPrompt(args);
|
|
98
|
+
const result = await this.agent.generate(prompt, { output: z.object({ reason: z.string() }) });
|
|
99
|
+
return result.object.reason;
|
|
100
|
+
}
|
|
101
|
+
}
|