@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,135 @@
|
|
|
1
|
+
export const CONTEXT_POSITION_AGENT_INSTRUCTIONS = `You are a balanced and nuanced context position evaluator. Your job is to determine if retrieved context nodes are relevant to generating the expected output, with special attention to their ordering.
|
|
2
|
+
|
|
3
|
+
Key Principles:
|
|
4
|
+
1. Evaluate whether each context node contributes to understanding the expected output - both directly AND indirectly
|
|
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. Pay attention to the position of relevant information
|
|
11
|
+
4. Recognize that earlier positions should contain more relevant information
|
|
12
|
+
5. Be inclusive rather than exclusive in determining relevance - if the information supports or reinforces the output in any way, consider it relevant
|
|
13
|
+
6. Empty or error nodes should be marked as not relevant`;
|
|
14
|
+
|
|
15
|
+
export function generateEvaluatePrompt({
|
|
16
|
+
input,
|
|
17
|
+
output,
|
|
18
|
+
context,
|
|
19
|
+
}: {
|
|
20
|
+
input: string;
|
|
21
|
+
output: string;
|
|
22
|
+
context: string[];
|
|
23
|
+
}) {
|
|
24
|
+
return `Given the input, output, and context, evaluate each context piece's relevance by generating a list of JSON objects.
|
|
25
|
+
|
|
26
|
+
**
|
|
27
|
+
IMPORTANT: Your response must be in JSON format with a 'verdicts' key containing a list. Each verdict must have only two fields: \`verdict\` with either 'yes' or 'no', and \`reason\` explaining the verdict. Your reason should include relevant quotes from the context.
|
|
28
|
+
|
|
29
|
+
CRITICAL: Context should be marked as relevant if it:
|
|
30
|
+
1. Directly helps define or explain the subject
|
|
31
|
+
2. Demonstrates properties or behaviors mentioned in the output
|
|
32
|
+
|
|
33
|
+
Example Context: ["The Sun is a star", "Stars produce their own light", "The Moon reflects sunlight", "The Sun gives light to planets"]
|
|
34
|
+
Example Query: "What is the Sun?"
|
|
35
|
+
Example Expected Response: "The Sun is a star that produces light."
|
|
36
|
+
|
|
37
|
+
Consider context relevant if it:
|
|
38
|
+
- Directly addresses the input question
|
|
39
|
+
- Demonstrates properties mentioned in the output
|
|
40
|
+
- Provides examples that validate the output
|
|
41
|
+
- Contains information that helps define the subject
|
|
42
|
+
|
|
43
|
+
Mark as not relevant if the information:
|
|
44
|
+
- Only describes other objects' behaviors
|
|
45
|
+
- Has no connection to properties mentioned in output
|
|
46
|
+
- Is completely unrelated to the subject
|
|
47
|
+
- Contradicts the output
|
|
48
|
+
|
|
49
|
+
Example:
|
|
50
|
+
{
|
|
51
|
+
"verdicts": [
|
|
52
|
+
{
|
|
53
|
+
"verdict": "yes",
|
|
54
|
+
"reason": "The context 'The Sun is a star' directly defines what the Sun is."
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
"verdict": "yes",
|
|
58
|
+
"reason": "The context 'Stars produce their own light' is relevant as it describes a key characteristic of stars, which includes the Sun."
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
"verdict": "no",
|
|
62
|
+
"reason": "The context 'The Moon reflects sunlight' is not relevant to defining what the Sun is or how it produces light, as it only describes how another object interacts with sunlight."
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
"verdict": "yes",
|
|
66
|
+
"reason": "The context 'The Sun gives light to planets' demonstrates the light-producing property mentioned in the output."
|
|
67
|
+
}
|
|
68
|
+
]
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
Consider context relevant if it:
|
|
72
|
+
- Directly addresses the query
|
|
73
|
+
- Provides examples or instances that help explain the concept
|
|
74
|
+
- Offers related information that helps build understanding
|
|
75
|
+
- Contains partial information that contributes to the response
|
|
76
|
+
|
|
77
|
+
The number of verdicts MUST MATCH the number of context pieces exactly.
|
|
78
|
+
**
|
|
79
|
+
|
|
80
|
+
Input:
|
|
81
|
+
${input}
|
|
82
|
+
|
|
83
|
+
Output:
|
|
84
|
+
${output}
|
|
85
|
+
|
|
86
|
+
Number of context pieces: ${context.length === 0 ? '1' : context.length}
|
|
87
|
+
|
|
88
|
+
Context:
|
|
89
|
+
${context}
|
|
90
|
+
|
|
91
|
+
JSON:
|
|
92
|
+
`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function generateReasonPrompt({
|
|
96
|
+
score,
|
|
97
|
+
verdicts,
|
|
98
|
+
input,
|
|
99
|
+
output,
|
|
100
|
+
scale,
|
|
101
|
+
}: {
|
|
102
|
+
score: number;
|
|
103
|
+
verdicts: { verdict: string; reason: string }[];
|
|
104
|
+
input: string;
|
|
105
|
+
output: string;
|
|
106
|
+
scale: number;
|
|
107
|
+
}) {
|
|
108
|
+
return `Explain the irrelevancy score where 0 is the lowest and ${scale} is the highest for the LLM's response using this context:
|
|
109
|
+
Context:
|
|
110
|
+
Input: ${input}
|
|
111
|
+
Output: ${output}
|
|
112
|
+
Score: ${score}
|
|
113
|
+
Verdicts: ${JSON.stringify(verdicts)}
|
|
114
|
+
|
|
115
|
+
Rules:
|
|
116
|
+
- Explain score based on mix of direct answers and related context
|
|
117
|
+
- Consider both full and partial relevance
|
|
118
|
+
- Keep explanation concise and focused
|
|
119
|
+
- Use given score, don't recalculate
|
|
120
|
+
- Don't judge factual correctness
|
|
121
|
+
- Explain both relevant and irrelevant aspects
|
|
122
|
+
- For mixed responses, explain the balance
|
|
123
|
+
Format:
|
|
124
|
+
{
|
|
125
|
+
"reason": "The score is {score} because {explanation of overall relevance}"
|
|
126
|
+
}
|
|
127
|
+
Example Responses:
|
|
128
|
+
{
|
|
129
|
+
"reason": "The score is 7 because while the first statement directly answers the question, the additional context is only partially relevant"
|
|
130
|
+
}
|
|
131
|
+
{
|
|
132
|
+
"reason": "The score is 3 because while the answer discusses the right topic, it doesn't directly address the question"
|
|
133
|
+
}
|
|
134
|
+
`;
|
|
135
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { createOpenAI } from '@ai-sdk/openai';
|
|
2
|
+
import { describe, it, expect } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import type { TestCaseWithContext } from '../utils';
|
|
5
|
+
|
|
6
|
+
import { ContextPrecisionMetric } from './index';
|
|
7
|
+
|
|
8
|
+
const testCases: TestCaseWithContext[] = [
|
|
9
|
+
{
|
|
10
|
+
input: 'Who invented the light bulb?',
|
|
11
|
+
output: 'Thomas Edison invented the light bulb.',
|
|
12
|
+
context: [
|
|
13
|
+
'Thomas Edison invented the light bulb in 1879 after many experiments.',
|
|
14
|
+
'Edison spent years perfecting the light bulb design.',
|
|
15
|
+
'Edison tested thousands of materials before finding the right filament.',
|
|
16
|
+
],
|
|
17
|
+
expectedResult: {
|
|
18
|
+
score: 1.0,
|
|
19
|
+
reason: 'All context pieces are highly relevant',
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
input: 'Tell me about Tokyo, Japan',
|
|
24
|
+
output: 'Tokyo is the capital of Japan and a major city.',
|
|
25
|
+
context: [
|
|
26
|
+
'Tokyo is the capital city of Japan.',
|
|
27
|
+
'Tokyo is a major economic and cultural center.',
|
|
28
|
+
'Japan has many beautiful mountains.',
|
|
29
|
+
],
|
|
30
|
+
expectedResult: {
|
|
31
|
+
score: 1.0,
|
|
32
|
+
reason: 'First two contexts are relevant, last one irrelevant',
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
input: 'What is quantum computing?',
|
|
37
|
+
output: 'Quantum computing uses quantum mechanics for computation.',
|
|
38
|
+
context: [
|
|
39
|
+
'Classical computers use bits.',
|
|
40
|
+
'Quantum computing uses quantum mechanics principles.',
|
|
41
|
+
'Quantum computers process information using quantum states.',
|
|
42
|
+
],
|
|
43
|
+
expectedResult: {
|
|
44
|
+
score: 0.583,
|
|
45
|
+
reason: 'Two relevant pieces, but after irrelevant first item',
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
input: 'What are programming languages?',
|
|
50
|
+
output: 'Programming languages are used to write computer code.',
|
|
51
|
+
context: [
|
|
52
|
+
'Python is a popular programming language.',
|
|
53
|
+
'Computers run on binary.',
|
|
54
|
+
'JavaScript is used for web development.',
|
|
55
|
+
],
|
|
56
|
+
expectedResult: {
|
|
57
|
+
score: 0.833,
|
|
58
|
+
reason: 'Two relevant pieces with alternating relevance',
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
input: 'What is machine learning?',
|
|
63
|
+
output: 'Machine learning is a type of artificial intelligence.',
|
|
64
|
+
context: [
|
|
65
|
+
'Machine learning uses data to make predictions.',
|
|
66
|
+
'Data science is a broad field.',
|
|
67
|
+
'Statistics help analyze results.',
|
|
68
|
+
],
|
|
69
|
+
expectedResult: {
|
|
70
|
+
score: 1.0,
|
|
71
|
+
reason: 'Single relevant piece at the start',
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
input: 'What started World War 1?',
|
|
76
|
+
output: 'The assassination of Archduke Franz Ferdinand sparked WWI.',
|
|
77
|
+
context: [
|
|
78
|
+
'The weather was mild that summer.',
|
|
79
|
+
'Many people enjoyed picnics in the park.',
|
|
80
|
+
'Local farmers had a good harvest.',
|
|
81
|
+
],
|
|
82
|
+
expectedResult: {
|
|
83
|
+
score: 0,
|
|
84
|
+
reason: 'No context pieces are relevant to WWI',
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
input: 'Tell me about Romeo and Juliet',
|
|
89
|
+
output: 'Romeo and Juliet was written by Shakespeare.',
|
|
90
|
+
context: ['William Shakespeare wrote the famous play Romeo and Juliet in the late 16th century.'],
|
|
91
|
+
expectedResult: {
|
|
92
|
+
score: 1.0,
|
|
93
|
+
reason: 'Single context is perfectly relevant',
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
input: 'How do I install Node.js?',
|
|
98
|
+
output: 'You need to download Node.js from the official website.',
|
|
99
|
+
context: [
|
|
100
|
+
'ERROR: Installation failed due to permissions.',
|
|
101
|
+
'Node.js is a JavaScript runtime.',
|
|
102
|
+
'To install Node.js, first download it from nodejs.org.',
|
|
103
|
+
],
|
|
104
|
+
expectedResult: {
|
|
105
|
+
score: 0.333,
|
|
106
|
+
reason: 'Single relevant piece at the end',
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
input: 'Empty context test',
|
|
111
|
+
output: 'Test output',
|
|
112
|
+
context: [],
|
|
113
|
+
expectedResult: {
|
|
114
|
+
score: 0,
|
|
115
|
+
reason: 'Empty context should score 0',
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
input: 'Single irrelevant test',
|
|
120
|
+
output: 'Test output',
|
|
121
|
+
context: ['Completely unrelated information'],
|
|
122
|
+
expectedResult: {
|
|
123
|
+
score: 0,
|
|
124
|
+
reason: 'Single irrelevant context should score 0',
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
];
|
|
128
|
+
|
|
129
|
+
const SECONDS = 10000;
|
|
130
|
+
|
|
131
|
+
const openai = createOpenAI({
|
|
132
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
const model = openai('gpt-4o');
|
|
136
|
+
|
|
137
|
+
describe(
|
|
138
|
+
'ContextPrecisionMetric',
|
|
139
|
+
() => {
|
|
140
|
+
it('should measure perfect context precision with all relevant items', async () => {
|
|
141
|
+
const testCase = testCases[0]!;
|
|
142
|
+
const metric = new ContextPrecisionMetric(model, { context: testCase.context });
|
|
143
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
144
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('should measure high precision with irrelevant item at end', async () => {
|
|
148
|
+
const testCase = testCases[1]!;
|
|
149
|
+
const metric = new ContextPrecisionMetric(model, { context: testCase.context });
|
|
150
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
151
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('should measure precision with two relevant items after irrelevant start', async () => {
|
|
155
|
+
const testCase = testCases[2]!;
|
|
156
|
+
const metric = new ContextPrecisionMetric(model, { context: testCase.context });
|
|
157
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
158
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('should measure precision with alternating relevant items', async () => {
|
|
162
|
+
const testCase = testCases[3]!;
|
|
163
|
+
const metric = new ContextPrecisionMetric(model, { context: testCase.context });
|
|
164
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
165
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it('should measure precision with single relevant item at start', async () => {
|
|
169
|
+
const testCase = testCases[4]!;
|
|
170
|
+
const metric = new ContextPrecisionMetric(model, { context: testCase.context });
|
|
171
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
172
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('should handle completely irrelevant context', async () => {
|
|
176
|
+
const testCase = testCases[5]!;
|
|
177
|
+
const metric = new ContextPrecisionMetric(model, { context: testCase.context });
|
|
178
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
179
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it('should handle single relevant context perfectly', async () => {
|
|
183
|
+
const testCase = testCases[6]!;
|
|
184
|
+
const metric = new ContextPrecisionMetric(model, { context: testCase.context });
|
|
185
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
186
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it('should measure precision with single relevant item at end', async () => {
|
|
190
|
+
const testCase = testCases[7]!;
|
|
191
|
+
const metric = new ContextPrecisionMetric(model, { context: testCase.context });
|
|
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 empty context', async () => {
|
|
197
|
+
const testCase = testCases[8]!;
|
|
198
|
+
const metric = new ContextPrecisionMetric(model, { context: testCase.context });
|
|
199
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
200
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it('should handle single irrelevant context', async () => {
|
|
204
|
+
const testCase = testCases[9]!;
|
|
205
|
+
const metric = new ContextPrecisionMetric(model, { context: testCase.context });
|
|
206
|
+
const result = await metric.measure(testCase.input, testCase.output);
|
|
207
|
+
expect(result.score).toBeCloseTo(testCase.expectedResult.score, 1);
|
|
208
|
+
});
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
timeout: 15 * SECONDS,
|
|
212
|
+
},
|
|
213
|
+
);
|
|
@@ -0,0 +1,68 @@
|
|
|
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 { ContextPrecisionJudge } from './metricJudge';
|
|
8
|
+
|
|
9
|
+
export interface ContextPrecisionMetricOptions {
|
|
10
|
+
scale?: number;
|
|
11
|
+
context: string[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class ContextPrecisionMetric extends Metric {
|
|
15
|
+
private judge: ContextPrecisionJudge;
|
|
16
|
+
private scale: number;
|
|
17
|
+
private context: string[];
|
|
18
|
+
|
|
19
|
+
constructor(model: LanguageModel, { scale = 1, context }: ContextPrecisionMetricOptions) {
|
|
20
|
+
super();
|
|
21
|
+
|
|
22
|
+
this.context = context;
|
|
23
|
+
this.judge = new ContextPrecisionJudge(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({ input, output, score, scale: this.scale, verdicts });
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
score,
|
|
34
|
+
info: {
|
|
35
|
+
reason,
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
private calculateScore(verdicts: { verdict: string; reason: string }[]): number {
|
|
41
|
+
const totalVerdicts = verdicts?.length || 0;
|
|
42
|
+
if (totalVerdicts === 0) {
|
|
43
|
+
return 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Convert to binary scores (1 for yes, 0 for no)
|
|
47
|
+
const binaryScores = verdicts.map(v => (v.verdict.trim().toLowerCase() === 'yes' ? 1 : 0));
|
|
48
|
+
|
|
49
|
+
let weightedPrecisionSum = 0;
|
|
50
|
+
let relevantCount = 0;
|
|
51
|
+
|
|
52
|
+
// Calculate weighted precision at each position
|
|
53
|
+
binaryScores.forEach((isRelevant, index) => {
|
|
54
|
+
if (isRelevant) {
|
|
55
|
+
relevantCount++;
|
|
56
|
+
const currentPrecision = relevantCount / (index + 1);
|
|
57
|
+
weightedPrecisionSum += currentPrecision * isRelevant;
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
if (relevantCount === 0) {
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const finalScore = weightedPrecisionSum / relevantCount;
|
|
66
|
+
return roundToTwoDecimals(finalScore * this.scale);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { LanguageModel } from '@mastra/core/llm';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
import { MastraAgentJudge } from '../../judge';
|
|
5
|
+
|
|
6
|
+
import { CONTEXT_PRECISION_AGENT_INSTRUCTIONS, generateEvaluatePrompt, generateReasonPrompt } from './prompts';
|
|
7
|
+
|
|
8
|
+
export class ContextPrecisionJudge extends MastraAgentJudge {
|
|
9
|
+
constructor(model: LanguageModel) {
|
|
10
|
+
super('Context Precision', CONTEXT_PRECISION_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
|
+
input: string;
|
|
39
|
+
output: string;
|
|
40
|
+
score: number;
|
|
41
|
+
scale: number;
|
|
42
|
+
verdicts: {
|
|
43
|
+
verdict: string;
|
|
44
|
+
reason: string;
|
|
45
|
+
}[];
|
|
46
|
+
}): Promise<string> {
|
|
47
|
+
const prompt = generateReasonPrompt(args);
|
|
48
|
+
const result = await this.agent.generate(prompt, {
|
|
49
|
+
output: z.object({
|
|
50
|
+
reason: z.string(),
|
|
51
|
+
}),
|
|
52
|
+
});
|
|
53
|
+
return result.object.reason;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
export const CONTEXT_PRECISION_AGENT_INSTRUCTIONS = `You are a balanced and nuanced context precision evaluator. Your job is to determine if retrieved context nodes are relevant to generating the expected output.
|
|
2
|
+
|
|
3
|
+
Key Principles:
|
|
4
|
+
1. Evaluate whether each context node was useful in generating the expected output
|
|
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 `Given the input, output, and context, evaluate each context piece's relevance by generating a list of JSON objects.
|
|
24
|
+
|
|
25
|
+
**
|
|
26
|
+
IMPORTANT: Your response must be in JSON format with a 'verdicts' key containing a list. Each verdict must have only two fields: \`verdict\` with either 'yes' or 'no', and \`reason\` explaining the verdict. Your reason should include relevant quotes from the context.
|
|
27
|
+
|
|
28
|
+
CRITICAL: Context should be marked as relevant if it:
|
|
29
|
+
1. Directly helps define or explain the subject
|
|
30
|
+
2. Demonstrates properties or behaviors mentioned in the output
|
|
31
|
+
|
|
32
|
+
Example Context: ["The Sun is a star", "Stars produce their own light", "The Moon reflects sunlight", "The Sun gives light to planets"]
|
|
33
|
+
Example Query: "What is the Sun?"
|
|
34
|
+
Example Expected Response: "The Sun is a star that produces light."
|
|
35
|
+
|
|
36
|
+
Consider context relevant if it:
|
|
37
|
+
- Directly addresses the input question
|
|
38
|
+
- Demonstrates properties mentioned in the output
|
|
39
|
+
- Provides examples that validate the output
|
|
40
|
+
- Contains information that helps define the subject
|
|
41
|
+
|
|
42
|
+
Mark as not relevant if the information:
|
|
43
|
+
- Only describes other objects' behaviors
|
|
44
|
+
- Has no connection to properties mentioned in output
|
|
45
|
+
- Is completely unrelated to the subject
|
|
46
|
+
- Contradicts the output
|
|
47
|
+
|
|
48
|
+
Example:
|
|
49
|
+
{
|
|
50
|
+
"verdicts": [
|
|
51
|
+
{
|
|
52
|
+
"verdict": "yes",
|
|
53
|
+
"reason": "The context 'The Sun is a star' directly defines what the Sun is."
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
"verdict": "yes",
|
|
57
|
+
"reason": "The context 'Stars produce their own light' is relevant as it describes a key characteristic of stars, which includes the Sun."
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"verdict": "no",
|
|
61
|
+
"reason": "The context 'The Moon reflects sunlight' is not relevant to defining what the Sun is or how it produces light, as it only describes how another object interacts with sunlight."
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
"verdict": "yes",
|
|
65
|
+
"reason": "The context 'The Sun gives light to planets' demonstrates the light-producing property mentioned in the output."
|
|
66
|
+
}
|
|
67
|
+
]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
Consider context relevant if it:
|
|
71
|
+
- Directly addresses the query
|
|
72
|
+
- Provides examples or instances that help explain the concept
|
|
73
|
+
- Offers related information that helps build understanding
|
|
74
|
+
- Contains partial information that contributes to the response
|
|
75
|
+
|
|
76
|
+
The number of verdicts MUST MATCH the number of context pieces exactly.
|
|
77
|
+
**
|
|
78
|
+
|
|
79
|
+
Input:
|
|
80
|
+
${input}
|
|
81
|
+
|
|
82
|
+
Output:
|
|
83
|
+
${output}
|
|
84
|
+
|
|
85
|
+
Number of context pieces: ${context.length === 0 ? '1' : context.length}
|
|
86
|
+
|
|
87
|
+
Context:
|
|
88
|
+
${context}
|
|
89
|
+
|
|
90
|
+
JSON:
|
|
91
|
+
`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function generateReasonPrompt({
|
|
95
|
+
input,
|
|
96
|
+
output,
|
|
97
|
+
verdicts,
|
|
98
|
+
score,
|
|
99
|
+
scale,
|
|
100
|
+
}: {
|
|
101
|
+
input: string;
|
|
102
|
+
output: string;
|
|
103
|
+
verdicts: Array<{ verdict: string; reason: string }>;
|
|
104
|
+
score: number;
|
|
105
|
+
scale: number;
|
|
106
|
+
}) {
|
|
107
|
+
return `Given the input, output, verdicts, and precision score, and the highest possible score is ${scale}, provide a BRIEF explanation for the score. Explain both its strengths and limitations.
|
|
108
|
+
The verdicts are a list containing \`verdict\` ('yes' or 'no' for relevance), \`reason\` (explaining the verdict) and \`node\` (the context text). Contexts are listed in their ranking order.
|
|
109
|
+
|
|
110
|
+
**
|
|
111
|
+
IMPORTANT: Return only JSON format with a single 'reason' key explaining the score.
|
|
112
|
+
Example JSON:
|
|
113
|
+
{
|
|
114
|
+
"reason": "The score is <score> because <explanation>."
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
Guidelines:
|
|
118
|
+
- Don't mention 'verdict' - refer to relevant/irrelevant nodes instead
|
|
119
|
+
- Use information from the \`reason\` field, not the field itself
|
|
120
|
+
- Reference node positions (first, second, etc.) when explaining relevance
|
|
121
|
+
- For perfect scores (${scale}.0), emphasize both relevance and optimal ordering
|
|
122
|
+
- Always reference the ranking order when discussing relevance
|
|
123
|
+
**
|
|
124
|
+
|
|
125
|
+
Precision Score:
|
|
126
|
+
${score}
|
|
127
|
+
|
|
128
|
+
Input:
|
|
129
|
+
${input}
|
|
130
|
+
|
|
131
|
+
Output:
|
|
132
|
+
${output}
|
|
133
|
+
|
|
134
|
+
Verdicts:
|
|
135
|
+
${JSON.stringify(verdicts)}
|
|
136
|
+
|
|
137
|
+
JSON:
|
|
138
|
+
`;
|
|
139
|
+
}
|