@mastra/evals 0.0.0-error-handler-fix-20251020202607 → 0.0.0-execa-dynamic-import-20260304221256
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/CHANGELOG.md +364 -3
- package/LICENSE.md +15 -0
- package/README.md +19 -159
- package/dist/chunk-OEOE7ZHN.js +195 -0
- package/dist/chunk-OEOE7ZHN.js.map +1 -0
- package/dist/{chunk-QKR2PMLZ.cjs → chunk-W3U7MMDX.cjs} +85 -21
- package/dist/chunk-W3U7MMDX.cjs.map +1 -0
- package/dist/docs/SKILL.md +43 -0
- package/dist/docs/assets/SOURCE_MAP.json +6 -0
- package/dist/docs/references/docs-evals-built-in-scorers.md +47 -0
- package/dist/docs/references/docs-evals-overview.md +141 -0
- package/dist/docs/references/reference-evals-answer-relevancy.md +105 -0
- package/dist/docs/references/reference-evals-answer-similarity.md +99 -0
- package/dist/docs/references/reference-evals-bias.md +120 -0
- package/dist/docs/references/reference-evals-completeness.md +136 -0
- package/dist/docs/references/reference-evals-content-similarity.md +101 -0
- package/dist/docs/references/reference-evals-context-precision.md +196 -0
- package/dist/docs/references/reference-evals-context-relevance.md +531 -0
- package/dist/docs/references/reference-evals-faithfulness.md +114 -0
- package/dist/docs/references/reference-evals-hallucination.md +213 -0
- package/dist/docs/references/reference-evals-keyword-coverage.md +128 -0
- package/dist/docs/references/reference-evals-noise-sensitivity.md +675 -0
- package/dist/docs/references/reference-evals-prompt-alignment.md +614 -0
- package/dist/docs/references/reference-evals-scorer-utils.md +326 -0
- package/dist/docs/references/reference-evals-textual-difference.md +113 -0
- package/dist/docs/references/reference-evals-tone-consistency.md +119 -0
- package/dist/docs/references/reference-evals-tool-call-accuracy.md +533 -0
- package/dist/docs/references/reference-evals-toxicity.md +123 -0
- package/dist/index.cjs +0 -89
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +11 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -86
- package/dist/index.js.map +1 -1
- package/dist/scorers/code/completeness/index.d.ts +1 -1
- package/dist/scorers/code/completeness/index.d.ts.map +1 -1
- package/dist/scorers/code/content-similarity/index.d.ts +1 -1
- package/dist/scorers/code/content-similarity/index.d.ts.map +1 -1
- package/dist/scorers/code/keyword-coverage/index.d.ts +1 -1
- package/dist/scorers/code/keyword-coverage/index.d.ts.map +1 -1
- package/dist/scorers/code/textual-difference/index.d.ts +1 -1
- package/dist/scorers/code/textual-difference/index.d.ts.map +1 -1
- package/dist/scorers/code/tone/index.d.ts +1 -1
- package/dist/scorers/code/tone/index.d.ts.map +1 -1
- package/dist/scorers/code/tool-call-accuracy/index.d.ts +2 -2
- package/dist/scorers/code/tool-call-accuracy/index.d.ts.map +1 -1
- package/dist/scorers/index.d.ts +1 -0
- package/dist/scorers/index.d.ts.map +1 -1
- package/dist/scorers/llm/answer-relevancy/index.d.ts +1 -1
- package/dist/scorers/llm/answer-relevancy/index.d.ts.map +1 -1
- package/dist/scorers/llm/answer-similarity/index.d.ts +2 -2
- package/dist/scorers/llm/answer-similarity/index.d.ts.map +1 -1
- package/dist/scorers/llm/bias/index.d.ts +2 -2
- package/dist/scorers/llm/bias/index.d.ts.map +1 -1
- package/dist/scorers/llm/context-precision/index.d.ts +3 -3
- package/dist/scorers/llm/context-precision/index.d.ts.map +1 -1
- package/dist/scorers/llm/context-relevance/index.d.ts +3 -3
- package/dist/scorers/llm/context-relevance/index.d.ts.map +1 -1
- package/dist/scorers/llm/faithfulness/index.d.ts +4 -2
- package/dist/scorers/llm/faithfulness/index.d.ts.map +1 -1
- package/dist/scorers/llm/hallucination/index.d.ts +20 -3
- package/dist/scorers/llm/hallucination/index.d.ts.map +1 -1
- package/dist/scorers/llm/noise-sensitivity/index.d.ts +1 -1
- package/dist/scorers/llm/noise-sensitivity/index.d.ts.map +1 -1
- package/dist/scorers/llm/prompt-alignment/index.d.ts +2 -2
- package/dist/scorers/llm/prompt-alignment/index.d.ts.map +1 -1
- package/dist/scorers/llm/tool-call-accuracy/index.d.ts +3 -3
- package/dist/scorers/llm/tool-call-accuracy/index.d.ts.map +1 -1
- package/dist/scorers/llm/toxicity/index.d.ts +2 -2
- package/dist/scorers/llm/toxicity/index.d.ts.map +1 -1
- package/dist/scorers/{llm → prebuilt}/index.cjs +506 -73
- package/dist/scorers/prebuilt/index.cjs.map +1 -0
- package/dist/scorers/prebuilt/index.d.ts +3 -0
- package/dist/scorers/prebuilt/index.d.ts.map +1 -0
- package/dist/scorers/{llm → prebuilt}/index.js +446 -26
- package/dist/scorers/prebuilt/index.js.map +1 -0
- package/dist/scorers/utils.cjs +29 -17
- package/dist/scorers/utils.d.ts +375 -12
- package/dist/scorers/utils.d.ts.map +1 -1
- package/dist/scorers/utils.js +1 -1
- package/package.json +22 -64
- package/dist/attachListeners.d.ts +0 -4
- package/dist/attachListeners.d.ts.map +0 -1
- package/dist/chunk-7QAUEU4L.cjs +0 -10
- package/dist/chunk-7QAUEU4L.cjs.map +0 -1
- package/dist/chunk-EMMSS5I5.cjs +0 -37
- package/dist/chunk-EMMSS5I5.cjs.map +0 -1
- package/dist/chunk-G3PMV62Z.js +0 -33
- package/dist/chunk-G3PMV62Z.js.map +0 -1
- package/dist/chunk-IUSAD2BW.cjs +0 -19
- package/dist/chunk-IUSAD2BW.cjs.map +0 -1
- package/dist/chunk-KHEXN75Q.js +0 -134
- package/dist/chunk-KHEXN75Q.js.map +0 -1
- package/dist/chunk-QKR2PMLZ.cjs.map +0 -1
- package/dist/chunk-QTWX6TKR.js +0 -8
- package/dist/chunk-QTWX6TKR.js.map +0 -1
- package/dist/chunk-YGTIO3J5.js +0 -17
- package/dist/chunk-YGTIO3J5.js.map +0 -1
- package/dist/dist-E463LOAZ.js +0 -16729
- package/dist/dist-E463LOAZ.js.map +0 -1
- package/dist/dist-KKO3PIUK.cjs +0 -16751
- package/dist/dist-KKO3PIUK.cjs.map +0 -1
- package/dist/evaluation.d.ts +0 -8
- package/dist/evaluation.d.ts.map +0 -1
- package/dist/magic-string.es-7ORA5OGR.js +0 -1305
- package/dist/magic-string.es-7ORA5OGR.js.map +0 -1
- package/dist/magic-string.es-NZ2XWFKN.cjs +0 -1311
- package/dist/magic-string.es-NZ2XWFKN.cjs.map +0 -1
- package/dist/metrics/index.d.ts +0 -4
- package/dist/metrics/index.d.ts.map +0 -1
- package/dist/metrics/judge/index.cjs +0 -12
- package/dist/metrics/judge/index.cjs.map +0 -1
- package/dist/metrics/judge/index.d.ts +0 -7
- package/dist/metrics/judge/index.d.ts.map +0 -1
- package/dist/metrics/judge/index.js +0 -3
- package/dist/metrics/judge/index.js.map +0 -1
- package/dist/metrics/llm/answer-relevancy/index.d.ts +0 -16
- package/dist/metrics/llm/answer-relevancy/index.d.ts.map +0 -1
- package/dist/metrics/llm/answer-relevancy/metricJudge.d.ts +0 -20
- package/dist/metrics/llm/answer-relevancy/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/answer-relevancy/prompts.d.ts +0 -19
- package/dist/metrics/llm/answer-relevancy/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/bias/index.d.ts +0 -14
- package/dist/metrics/llm/bias/index.d.ts.map +0 -1
- package/dist/metrics/llm/bias/metricJudge.d.ts +0 -14
- package/dist/metrics/llm/bias/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/bias/prompts.d.ts +0 -14
- package/dist/metrics/llm/bias/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/context-position/index.d.ts +0 -16
- package/dist/metrics/llm/context-position/index.d.ts.map +0 -1
- package/dist/metrics/llm/context-position/metricJudge.d.ts +0 -20
- package/dist/metrics/llm/context-position/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/context-position/prompts.d.ts +0 -17
- package/dist/metrics/llm/context-position/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/context-precision/index.d.ts +0 -16
- package/dist/metrics/llm/context-precision/index.d.ts.map +0 -1
- package/dist/metrics/llm/context-precision/metricJudge.d.ts +0 -20
- package/dist/metrics/llm/context-precision/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/context-precision/prompts.d.ts +0 -17
- package/dist/metrics/llm/context-precision/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/context-relevancy/index.d.ts +0 -16
- package/dist/metrics/llm/context-relevancy/index.d.ts.map +0 -1
- package/dist/metrics/llm/context-relevancy/metricJudge.d.ts +0 -16
- package/dist/metrics/llm/context-relevancy/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/context-relevancy/prompts.d.ts +0 -13
- package/dist/metrics/llm/context-relevancy/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/contextual-recall/index.d.ts +0 -16
- package/dist/metrics/llm/contextual-recall/index.d.ts.map +0 -1
- package/dist/metrics/llm/contextual-recall/metricJudge.d.ts +0 -16
- package/dist/metrics/llm/contextual-recall/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/contextual-recall/prompts.d.ts +0 -13
- package/dist/metrics/llm/contextual-recall/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/faithfulness/index.d.ts +0 -16
- package/dist/metrics/llm/faithfulness/index.d.ts.map +0 -1
- package/dist/metrics/llm/faithfulness/metricJudge.d.ts +0 -22
- package/dist/metrics/llm/faithfulness/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/faithfulness/prompts.d.ts +0 -20
- package/dist/metrics/llm/faithfulness/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/hallucination/index.d.ts +0 -16
- package/dist/metrics/llm/hallucination/index.d.ts.map +0 -1
- package/dist/metrics/llm/hallucination/metricJudge.d.ts +0 -22
- package/dist/metrics/llm/hallucination/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/hallucination/prompts.d.ts +0 -17
- package/dist/metrics/llm/hallucination/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/index.cjs +0 -2481
- package/dist/metrics/llm/index.cjs.map +0 -1
- package/dist/metrics/llm/index.d.ts +0 -12
- package/dist/metrics/llm/index.d.ts.map +0 -1
- package/dist/metrics/llm/index.js +0 -2469
- package/dist/metrics/llm/index.js.map +0 -1
- package/dist/metrics/llm/prompt-alignment/index.d.ts +0 -33
- package/dist/metrics/llm/prompt-alignment/index.d.ts.map +0 -1
- package/dist/metrics/llm/prompt-alignment/metricJudge.d.ts +0 -20
- package/dist/metrics/llm/prompt-alignment/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/prompt-alignment/prompts.d.ts +0 -17
- package/dist/metrics/llm/prompt-alignment/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/summarization/index.d.ts +0 -19
- package/dist/metrics/llm/summarization/index.d.ts.map +0 -1
- package/dist/metrics/llm/summarization/metricJudge.d.ts +0 -34
- package/dist/metrics/llm/summarization/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/summarization/prompts.d.ts +0 -30
- package/dist/metrics/llm/summarization/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/toxicity/index.d.ts +0 -14
- package/dist/metrics/llm/toxicity/index.d.ts.map +0 -1
- package/dist/metrics/llm/toxicity/metricJudge.d.ts +0 -14
- package/dist/metrics/llm/toxicity/metricJudge.d.ts.map +0 -1
- package/dist/metrics/llm/toxicity/prompts.d.ts +0 -10
- package/dist/metrics/llm/toxicity/prompts.d.ts.map +0 -1
- package/dist/metrics/llm/types.d.ts +0 -7
- package/dist/metrics/llm/types.d.ts.map +0 -1
- package/dist/metrics/llm/utils.d.ts +0 -14
- package/dist/metrics/llm/utils.d.ts.map +0 -1
- package/dist/metrics/nlp/completeness/index.d.ts +0 -21
- package/dist/metrics/nlp/completeness/index.d.ts.map +0 -1
- package/dist/metrics/nlp/content-similarity/index.d.ts +0 -18
- package/dist/metrics/nlp/content-similarity/index.d.ts.map +0 -1
- package/dist/metrics/nlp/index.cjs +0 -203
- package/dist/metrics/nlp/index.cjs.map +0 -1
- package/dist/metrics/nlp/index.d.ts +0 -6
- package/dist/metrics/nlp/index.d.ts.map +0 -1
- package/dist/metrics/nlp/index.js +0 -190
- package/dist/metrics/nlp/index.js.map +0 -1
- package/dist/metrics/nlp/keyword-coverage/index.d.ts +0 -13
- package/dist/metrics/nlp/keyword-coverage/index.d.ts.map +0 -1
- package/dist/metrics/nlp/textual-difference/index.d.ts +0 -15
- package/dist/metrics/nlp/textual-difference/index.d.ts.map +0 -1
- package/dist/metrics/nlp/tone/index.d.ts +0 -18
- package/dist/metrics/nlp/tone/index.d.ts.map +0 -1
- package/dist/scorers/code/index.cjs +0 -329
- package/dist/scorers/code/index.cjs.map +0 -1
- package/dist/scorers/code/index.js +0 -315
- package/dist/scorers/code/index.js.map +0 -1
- package/dist/scorers/llm/index.cjs.map +0 -1
- package/dist/scorers/llm/index.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
# @mastra/evals
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@mastra/evals` ships a collection of scoring utilities you can run locally or inside your own evaluation pipelines. These scorers come in two flavors:
|
|
4
|
+
|
|
5
|
+
- **LLM scorers** – leverage a judge model (e.g. OpenAI, Anthropic) to rate responses for qualities such as faithfulness or toxicity.
|
|
6
|
+
- **Code/NLP scorers** – deterministic heuristics (keyword coverage, similarity, etc.) that do not require an external model.
|
|
7
|
+
|
|
8
|
+
The scorers do not persist results or integrate with Mastra Storage; you decide where and how to record outcomes.
|
|
4
9
|
|
|
5
10
|
## Installation
|
|
6
11
|
|
|
@@ -8,171 +13,26 @@ A comprehensive evaluation framework for assessing AI model outputs across multi
|
|
|
8
13
|
npm install @mastra/evals
|
|
9
14
|
```
|
|
10
15
|
|
|
11
|
-
##
|
|
12
|
-
|
|
13
|
-
`@mastra/evals` provides a suite of evaluation metrics for assessing AI model outputs. The package includes both LLM-based and NLP-based metrics, enabling both automated and model-assisted evaluation of AI responses.
|
|
14
|
-
|
|
15
|
-
## Features
|
|
16
|
-
|
|
17
|
-
### LLM-Based Metrics
|
|
18
|
-
|
|
19
|
-
1. **Answer Relevancy**
|
|
20
|
-
- Evaluates how well an answer addresses the input question
|
|
21
|
-
- Considers uncertainty weighting for more nuanced scoring
|
|
22
|
-
- Returns detailed reasoning for scores
|
|
23
|
-
|
|
24
|
-
2. **Bias Detection**
|
|
25
|
-
- Identifies potential biases in model outputs
|
|
26
|
-
- Analyzes opinions and statements for bias indicators
|
|
27
|
-
- Provides explanations for detected biases
|
|
28
|
-
- Configurable scoring scale
|
|
29
|
-
|
|
30
|
-
3. **Context Precision & Relevancy**
|
|
31
|
-
- Assesses how well responses use provided context
|
|
32
|
-
- Evaluates accuracy of context usage
|
|
33
|
-
- Measures relevance of context to the response
|
|
34
|
-
- Analyzes context positioning in responses
|
|
35
|
-
|
|
36
|
-
4. **Faithfulness**
|
|
37
|
-
- Verifies that responses are faithful to provided context
|
|
38
|
-
- Detects hallucinations or fabricated information
|
|
39
|
-
- Evaluates claims against provided context
|
|
40
|
-
- Provides detailed analysis of faithfulness breaches
|
|
41
|
-
|
|
42
|
-
5. **Prompt Alignment**
|
|
43
|
-
- Measures how well responses follow given instructions
|
|
44
|
-
- Evaluates adherence to multiple instruction criteria
|
|
45
|
-
- Provides per-instruction scoring
|
|
46
|
-
- Supports custom instruction sets
|
|
47
|
-
|
|
48
|
-
6. **Toxicity**
|
|
49
|
-
- Detects toxic or harmful content in responses
|
|
50
|
-
- Provides detailed reasoning for toxicity verdicts
|
|
51
|
-
- Configurable scoring thresholds
|
|
52
|
-
- Considers both input and output context
|
|
16
|
+
## Quick Start
|
|
53
17
|
|
|
54
|
-
|
|
18
|
+
```ts
|
|
19
|
+
import { createFaithfulnessScorer, createContentSimilarityScorer } from '@mastra/evals/scorers/prebuilt';
|
|
55
20
|
|
|
56
|
-
|
|
57
|
-
-
|
|
58
|
-
- Identifies missing elements from input requirements
|
|
59
|
-
- Provides detailed element coverage analysis
|
|
60
|
-
- Tracks input-output element ratios
|
|
61
|
-
|
|
62
|
-
2. **Content Similarity**
|
|
63
|
-
- Measures text similarity between inputs and outputs
|
|
64
|
-
- Configurable for case and whitespace sensitivity
|
|
65
|
-
- Returns normalized similarity scores
|
|
66
|
-
- Uses string comparison algorithms for accuracy
|
|
67
|
-
|
|
68
|
-
3. **Keyword Coverage**
|
|
69
|
-
- Tracks presence of key terms from input in output
|
|
70
|
-
- Provides detailed keyword matching statistics
|
|
71
|
-
- Calculates coverage ratios
|
|
72
|
-
- Useful for ensuring comprehensive responses
|
|
73
|
-
|
|
74
|
-
## Usage
|
|
75
|
-
|
|
76
|
-
### Basic Example
|
|
77
|
-
|
|
78
|
-
```typescript
|
|
79
|
-
import { ContentSimilarityMetric, ToxicityMetric } from '@mastra/evals';
|
|
80
|
-
|
|
81
|
-
// Initialize metrics
|
|
82
|
-
const similarityMetric = new ContentSimilarityMetric({
|
|
83
|
-
ignoreCase: true,
|
|
84
|
-
ignoreWhitespace: true,
|
|
21
|
+
const faithfulness = createFaithfulnessScorer({
|
|
22
|
+
model: 'openai/gpt-4o-mini')
|
|
85
23
|
});
|
|
86
24
|
|
|
87
|
-
const
|
|
88
|
-
model: openai('gpt-4'),
|
|
89
|
-
scale: 1, // Optional: adjust scoring scale
|
|
90
|
-
});
|
|
91
|
-
|
|
92
|
-
// Evaluate outputs
|
|
93
|
-
const input = 'What is the capital of France?';
|
|
94
|
-
const output = 'Paris is the capital of France.';
|
|
95
|
-
|
|
96
|
-
const similarityResult = await similarityMetric.measure(input, output);
|
|
97
|
-
const toxicityResult = await toxicityMetric.measure(input, output);
|
|
98
|
-
|
|
99
|
-
console.log('Similarity Score:', similarityResult.score);
|
|
100
|
-
console.log('Toxicity Score:', toxicityResult.score);
|
|
101
|
-
```
|
|
25
|
+
const similarity = createContentSimilarityScorer({ ignoreCase: true });
|
|
102
26
|
|
|
103
|
-
|
|
27
|
+
const answer = 'Paris is the capital of France.';
|
|
28
|
+
const context = ['Paris is the capital of France', 'France is in Europe'];
|
|
104
29
|
|
|
105
|
-
|
|
106
|
-
import { FaithfulnessMetric } from '@mastra/evals';
|
|
30
|
+
const faithfulnessScore = await faithfulness.score({ answer, context });
|
|
107
31
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
context: ['Paris is the capital of France', 'Paris has a population of 2.2 million'],
|
|
112
|
-
scale: 1,
|
|
32
|
+
const similarityScore = similarity.score({
|
|
33
|
+
input: context[0],
|
|
34
|
+
output: answer
|
|
113
35
|
});
|
|
114
36
|
|
|
115
|
-
|
|
116
|
-
const result = await faithfulnessMetric.measure(
|
|
117
|
-
'Tell me about Paris',
|
|
118
|
-
'Paris is the capital of France with 2.2 million residents',
|
|
119
|
-
);
|
|
120
|
-
|
|
121
|
-
console.log('Faithfulness Score:', result.score);
|
|
122
|
-
console.log('Reasoning:', result.reason);
|
|
37
|
+
console.log({ faithfulnessScore, similarityScore });
|
|
123
38
|
```
|
|
124
|
-
|
|
125
|
-
## Metric Results
|
|
126
|
-
|
|
127
|
-
Each metric returns a standardized result object containing:
|
|
128
|
-
|
|
129
|
-
- `score`: Normalized score (typically 0-1)
|
|
130
|
-
- `info`: Detailed information about the evaluation
|
|
131
|
-
- Additional metric-specific data (e.g., matched keywords, missing elements)
|
|
132
|
-
|
|
133
|
-
Some metrics also provide:
|
|
134
|
-
|
|
135
|
-
- `reason`: Detailed explanation of the score
|
|
136
|
-
- `verdicts`: Individual judgments that contributed to the final score
|
|
137
|
-
|
|
138
|
-
## Telemetry and Logging
|
|
139
|
-
|
|
140
|
-
The package includes built-in telemetry and logging capabilities:
|
|
141
|
-
|
|
142
|
-
- Automatic evaluation tracking through Mastra Storage
|
|
143
|
-
- Integration with OpenTelemetry for performance monitoring
|
|
144
|
-
- Detailed evaluation traces for debugging
|
|
145
|
-
|
|
146
|
-
```typescript
|
|
147
|
-
import { attachListeners } from '@mastra/evals';
|
|
148
|
-
|
|
149
|
-
// Enable basic evaluation tracking
|
|
150
|
-
await attachListeners();
|
|
151
|
-
|
|
152
|
-
// Store evals in Mastra Storage (if storage is enabled)
|
|
153
|
-
await attachListeners(mastra);
|
|
154
|
-
// Note: When using in-memory storage, evaluations are isolated to the test process.
|
|
155
|
-
// When using file storage, evaluations are persisted and can be queried later.
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
## Environment Variables
|
|
159
|
-
|
|
160
|
-
Required for LLM-based metrics:
|
|
161
|
-
|
|
162
|
-
- `OPENAI_API_KEY`: For OpenAI model access
|
|
163
|
-
- Additional provider keys as needed (Cohere, Anthropic, etc.)
|
|
164
|
-
|
|
165
|
-
## Package Exports
|
|
166
|
-
|
|
167
|
-
```typescript
|
|
168
|
-
// Main package exports
|
|
169
|
-
import { evaluate } from '@mastra/evals';
|
|
170
|
-
// NLP-specific metrics
|
|
171
|
-
import { ContentSimilarityMetric } from '@mastra/evals/nlp';
|
|
172
|
-
```
|
|
173
|
-
|
|
174
|
-
## Related Packages
|
|
175
|
-
|
|
176
|
-
- `@mastra/core`: Core framework functionality
|
|
177
|
-
- `@mastra/engine`: LLM execution engine
|
|
178
|
-
- `@mastra/mcp`: Model Context Protocol integration
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { RequestContext } from '@mastra/core/request-context';
|
|
2
|
+
|
|
3
|
+
// src/scorers/utils.ts
|
|
4
|
+
function getTextContentFromMastraDBMessage(message) {
|
|
5
|
+
if (typeof message.content.content === "string" && message.content.content !== "") {
|
|
6
|
+
return message.content.content;
|
|
7
|
+
}
|
|
8
|
+
if (message.content.parts && Array.isArray(message.content.parts)) {
|
|
9
|
+
const textParts = message.content.parts.filter((p) => p.type === "text");
|
|
10
|
+
return textParts.length > 0 ? textParts[textParts.length - 1]?.text || "" : "";
|
|
11
|
+
}
|
|
12
|
+
return "";
|
|
13
|
+
}
|
|
14
|
+
var roundToTwoDecimals = (num) => {
|
|
15
|
+
return Math.round((num + Number.EPSILON) * 100) / 100;
|
|
16
|
+
};
|
|
17
|
+
function isCloserTo(value, target1, target2) {
|
|
18
|
+
return Math.abs(value - target1) < Math.abs(value - target2);
|
|
19
|
+
}
|
|
20
|
+
var createTestRun = (input, output, additionalContext, requestContext) => {
|
|
21
|
+
return {
|
|
22
|
+
input: [{ role: "user", content: input }],
|
|
23
|
+
output: { role: "assistant", text: output },
|
|
24
|
+
additionalContext: additionalContext ?? {},
|
|
25
|
+
requestContext: requestContext ?? {}
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
var getUserMessageFromRunInput = (input) => {
|
|
29
|
+
const message = input?.inputMessages.find(({ role }) => role === "user");
|
|
30
|
+
return message ? getTextContentFromMastraDBMessage(message) : void 0;
|
|
31
|
+
};
|
|
32
|
+
var getSystemMessagesFromRunInput = (input) => {
|
|
33
|
+
const systemMessages = [];
|
|
34
|
+
if (input?.systemMessages) {
|
|
35
|
+
systemMessages.push(
|
|
36
|
+
...input.systemMessages.map((msg) => {
|
|
37
|
+
if (typeof msg.content === "string") {
|
|
38
|
+
return msg.content;
|
|
39
|
+
} else if (Array.isArray(msg.content)) {
|
|
40
|
+
return msg.content.filter((part) => part.type === "text").map((part) => part.text || "").join(" ");
|
|
41
|
+
}
|
|
42
|
+
return "";
|
|
43
|
+
}).filter((content) => content)
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
if (input?.taggedSystemMessages) {
|
|
47
|
+
Object.values(input.taggedSystemMessages).forEach((messages) => {
|
|
48
|
+
messages.forEach((msg) => {
|
|
49
|
+
if (typeof msg.content === "string") {
|
|
50
|
+
systemMessages.push(msg.content);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return systemMessages;
|
|
56
|
+
};
|
|
57
|
+
var getCombinedSystemPrompt = (input) => {
|
|
58
|
+
const systemMessages = getSystemMessagesFromRunInput(input);
|
|
59
|
+
return systemMessages.join("\n\n");
|
|
60
|
+
};
|
|
61
|
+
var getAssistantMessageFromRunOutput = (output) => {
|
|
62
|
+
const message = output?.find(({ role }) => role === "assistant");
|
|
63
|
+
return message ? getTextContentFromMastraDBMessage(message) : void 0;
|
|
64
|
+
};
|
|
65
|
+
var getReasoningFromRunOutput = (output) => {
|
|
66
|
+
if (!output) return void 0;
|
|
67
|
+
const message = output.find(({ role }) => role === "assistant");
|
|
68
|
+
if (!message) return void 0;
|
|
69
|
+
if (message.content.reasoning) {
|
|
70
|
+
return message.content.reasoning;
|
|
71
|
+
}
|
|
72
|
+
const reasoningParts = message.content.parts?.filter((p) => p.type === "reasoning");
|
|
73
|
+
if (reasoningParts && reasoningParts.length > 0) {
|
|
74
|
+
const reasoningTexts = reasoningParts.map((p) => {
|
|
75
|
+
if (p.details && Array.isArray(p.details)) {
|
|
76
|
+
return p.details.filter((d) => d.type === "text").map((d) => d.text).join("");
|
|
77
|
+
}
|
|
78
|
+
return p.reasoning || "";
|
|
79
|
+
}).filter(Boolean);
|
|
80
|
+
return reasoningTexts.length > 0 ? reasoningTexts.join("\n") : void 0;
|
|
81
|
+
}
|
|
82
|
+
return void 0;
|
|
83
|
+
};
|
|
84
|
+
var createToolInvocation = ({
|
|
85
|
+
toolCallId,
|
|
86
|
+
toolName,
|
|
87
|
+
args,
|
|
88
|
+
result,
|
|
89
|
+
state = "result"
|
|
90
|
+
}) => {
|
|
91
|
+
return {
|
|
92
|
+
toolCallId,
|
|
93
|
+
toolName,
|
|
94
|
+
args,
|
|
95
|
+
result,
|
|
96
|
+
state
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
function createTestMessage({
|
|
100
|
+
content,
|
|
101
|
+
role,
|
|
102
|
+
id = "test-message",
|
|
103
|
+
toolInvocations = []
|
|
104
|
+
}) {
|
|
105
|
+
return {
|
|
106
|
+
id,
|
|
107
|
+
role,
|
|
108
|
+
content: {
|
|
109
|
+
format: 2,
|
|
110
|
+
parts: [{ type: "text", text: content }],
|
|
111
|
+
content,
|
|
112
|
+
...toolInvocations.length > 0 && {
|
|
113
|
+
toolInvocations: toolInvocations.map((ti) => ({
|
|
114
|
+
toolCallId: ti.toolCallId,
|
|
115
|
+
toolName: ti.toolName,
|
|
116
|
+
args: ti.args,
|
|
117
|
+
result: ti.result,
|
|
118
|
+
state: ti.state
|
|
119
|
+
}))
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
var createAgentTestRun = ({
|
|
126
|
+
inputMessages = [],
|
|
127
|
+
output,
|
|
128
|
+
rememberedMessages = [],
|
|
129
|
+
systemMessages = [],
|
|
130
|
+
taggedSystemMessages = {},
|
|
131
|
+
requestContext = new RequestContext(),
|
|
132
|
+
runId = crypto.randomUUID()
|
|
133
|
+
}) => {
|
|
134
|
+
return {
|
|
135
|
+
input: {
|
|
136
|
+
inputMessages,
|
|
137
|
+
rememberedMessages,
|
|
138
|
+
systemMessages,
|
|
139
|
+
taggedSystemMessages
|
|
140
|
+
},
|
|
141
|
+
output,
|
|
142
|
+
requestContext,
|
|
143
|
+
runId
|
|
144
|
+
};
|
|
145
|
+
};
|
|
146
|
+
function extractToolCalls(output) {
|
|
147
|
+
const toolCalls = [];
|
|
148
|
+
const toolCallInfos = [];
|
|
149
|
+
for (let messageIndex = 0; messageIndex < output.length; messageIndex++) {
|
|
150
|
+
const message = output[messageIndex];
|
|
151
|
+
if (message?.content?.toolInvocations) {
|
|
152
|
+
for (let invocationIndex = 0; invocationIndex < message.content.toolInvocations.length; invocationIndex++) {
|
|
153
|
+
const invocation = message.content.toolInvocations[invocationIndex];
|
|
154
|
+
if (invocation && invocation.toolName && (invocation.state === "result" || invocation.state === "call")) {
|
|
155
|
+
toolCalls.push(invocation.toolName);
|
|
156
|
+
toolCallInfos.push({
|
|
157
|
+
toolName: invocation.toolName,
|
|
158
|
+
toolCallId: invocation.toolCallId || `${messageIndex}-${invocationIndex}`,
|
|
159
|
+
messageIndex,
|
|
160
|
+
invocationIndex
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return { tools: toolCalls, toolCallInfos };
|
|
167
|
+
}
|
|
168
|
+
var extractInputMessages = (runInput) => {
|
|
169
|
+
return runInput?.inputMessages?.map((msg) => getTextContentFromMastraDBMessage(msg)) || [];
|
|
170
|
+
};
|
|
171
|
+
var extractAgentResponseMessages = (runOutput) => {
|
|
172
|
+
return runOutput.filter((msg) => msg.role === "assistant").map((msg) => getTextContentFromMastraDBMessage(msg));
|
|
173
|
+
};
|
|
174
|
+
function extractToolResults(output) {
|
|
175
|
+
const results = [];
|
|
176
|
+
for (const message of output) {
|
|
177
|
+
const toolInvocations = message?.content?.toolInvocations;
|
|
178
|
+
if (!toolInvocations) continue;
|
|
179
|
+
for (const invocation of toolInvocations) {
|
|
180
|
+
if (invocation.state === "result" && invocation.result !== void 0) {
|
|
181
|
+
results.push({
|
|
182
|
+
toolName: invocation.toolName,
|
|
183
|
+
toolCallId: invocation.toolCallId || "",
|
|
184
|
+
args: invocation.args || {},
|
|
185
|
+
result: invocation.result
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return results;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export { createAgentTestRun, createTestMessage, createTestRun, createToolInvocation, extractAgentResponseMessages, extractInputMessages, extractToolCalls, extractToolResults, getAssistantMessageFromRunOutput, getCombinedSystemPrompt, getReasoningFromRunOutput, getSystemMessagesFromRunInput, getTextContentFromMastraDBMessage, getUserMessageFromRunInput, isCloserTo, roundToTwoDecimals };
|
|
194
|
+
//# sourceMappingURL=chunk-OEOE7ZHN.js.map
|
|
195
|
+
//# sourceMappingURL=chunk-OEOE7ZHN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/scorers/utils.ts"],"names":[],"mappings":";;;AAyBO,SAAS,kCAAkC,OAAA,EAAkC;AAClF,EAAA,IAAI,OAAO,QAAQ,OAAA,CAAQ,OAAA,KAAY,YAAY,OAAA,CAAQ,OAAA,CAAQ,YAAY,EAAA,EAAI;AACjF,IAAA,OAAO,QAAQ,OAAA,CAAQ,OAAA;AAAA,EACzB;AACA,EAAA,IAAI,OAA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;AAEA,EAAA,OAAO,EAAE,KAAA,EAAO,SAAA,EAAW,aAAA,EAAc;AAC3C;AAiBO,IAAM,oBAAA,GAAuB,CAAC,QAAA,KAA2D;AAC9F,EAAA,OAAO,QAAA,EAAU,eAAe,GAAA,CAAI,CAAA,GAAA,KAAO,kCAAkC,GAAG,CAAC,KAAK,EAAC;AACzF;AAmBO,IAAM,4BAAA,GAA+B,CAAC,SAAA,KAAiD;AAC5F,EAAA,OAAO,SAAA,CAAU,MAAA,CAAO,CAAA,GAAA,KAAO,GAAA,CAAI,IAAA,KAAS,WAAW,CAAA,CAAE,GAAA,CAAI,CAAA,GAAA,KAAO,iCAAA,CAAkC,GAAG,CAAC,CAAA;AAC5G;AAyCO,SAAS,mBAAmB,MAAA,EAAmD;AACpF,EAAA,MAAM,UAA4B,EAAC;AAEnC,EAAA,KAAA,MAAW,WAAW,MAAA,EAAQ;AAC5B,IAAA,MAAM,eAAA,GAAkB,SAAS,OAAA,EAAS,eAAA;AAC1C,IAAA,IAAI,CAAC,eAAA,EAAiB;AAEtB,IAAA,KAAA,MAAW,cAAc,eAAA,EAAiB;AACxC,MAAA,IAAI,UAAA,CAAW,KAAA,KAAU,QAAA,IAAY,UAAA,CAAW,WAAW,MAAA,EAAW;AACpE,QAAA,OAAA,CAAQ,IAAA,CAAK;AAAA,UACX,UAAU,UAAA,CAAW,QAAA;AAAA,UACrB,UAAA,EAAY,WAAW,UAAA,IAAc,EAAA;AAAA,UACrC,IAAA,EAAM,UAAA,CAAW,IAAA,IAAQ,EAAC;AAAA,UAC1B,QAAQ,UAAA,CAAW;AAAA,SACpB,CAAA;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO,OAAA;AACT","file":"chunk-OEOE7ZHN.js","sourcesContent":["import type { MastraDBMessage } from '@mastra/core/agent';\nimport type { ScorerRunInputForAgent, ScorerRunOutputForAgent, ScoringInput } from '@mastra/core/evals';\nimport { RequestContext } from '@mastra/core/request-context';\n\n/**\n * Extracts text content from a MastraDBMessage.\n *\n * This function matches the logic used in `MessageList.mastraDBMessageToAIV4UIMessage`.\n * It first checks for a string `content.content` field, then falls back to extracting\n * text from the `parts` array (returning only the last text part, like AI SDK does).\n *\n * @param message - The MastraDBMessage to extract text from\n * @returns The extracted text content, or an empty string if no text is found\n *\n * @example\n * ```ts\n * const message: MastraDBMessage = {\n * id: 'msg-1',\n * role: 'assistant',\n * content: { format: 2, parts: [{ type: 'text', text: 'Hello!' }] },\n * createdAt: new Date(),\n * };\n * const text = getTextContentFromMastraDBMessage(message); // 'Hello!'\n * ```\n */\nexport function getTextContentFromMastraDBMessage(message: MastraDBMessage): string {\n if (typeof message.content.content === 'string' && message.content.content !== '') {\n return message.content.content;\n }\n if (message.content.parts && Array.isArray(message.content.parts)) {\n // Return only the last text part like AI SDK does\n const textParts = message.content.parts.filter(p => p.type === 'text');\n return textParts.length > 0 ? textParts[textParts.length - 1]?.text || '' : '';\n }\n return '';\n}\n\n/**\n * Rounds a number to two decimal places.\n *\n * Uses `Number.EPSILON` to handle floating-point precision issues.\n *\n * @param num - The number to round\n * @returns The number rounded to two decimal places\n *\n * @example\n * ```ts\n * roundToTwoDecimals(0.1 + 0.2); // 0.3\n * roundToTwoDecimals(1.005); // 1.01\n * ```\n */\nexport const roundToTwoDecimals = (num: number) => {\n return Math.round((num + Number.EPSILON) * 100) / 100;\n};\n\n/**\n * Determines if a value is closer to the first target than the second.\n *\n * @param value - The value to compare\n * @param target1 - The first target value\n * @param target2 - The second target value\n * @returns `true` if `value` is closer to `target1` than `target2`\n *\n * @example\n * ```ts\n * isCloserTo(0.6, 1, 0); // true (0.6 is closer to 1)\n * isCloserTo(0.3, 1, 0); // false (0.3 is closer to 0)\n * ```\n */\nexport function isCloserTo(value: number, target1: number, target2: number): boolean {\n return Math.abs(value - target1) < Math.abs(value - target2);\n}\n\n/**\n * Represents a test case for scorer evaluation.\n */\nexport type TestCase = {\n /** The input text to evaluate */\n input: string;\n /** The output text to evaluate */\n output: string;\n /** The expected result of the evaluation */\n expectedResult: {\n /** The expected score */\n score: number;\n /** The optional expected reason */\n reason?: string;\n };\n};\n\n/**\n * Represents a test case with additional context for scorer evaluation.\n */\nexport type TestCaseWithContext = TestCase & {\n /** Additional context strings for the evaluation */\n context: string[];\n};\n\n/**\n * Creates a scoring input object for testing purposes.\n *\n * @param input - The user input text\n * @param output - The assistant output text\n * @param additionalContext - Optional additional context data\n * @param requestContext - Optional request context data\n * @returns A ScoringInput object ready for use in scorer tests\n *\n * @example\n * ```ts\n * const run = createTestRun(\n * 'What is 2+2?',\n * 'The answer is 4.',\n * { topic: 'math' }\n * );\n * ```\n */\nexport const createTestRun = (\n input: string,\n output: string,\n additionalContext?: Record<string, any>,\n requestContext?: Record<string, any>,\n): ScoringInput => {\n return {\n input: [{ role: 'user', content: input }],\n output: { role: 'assistant', text: output },\n additionalContext: additionalContext ?? {},\n requestContext: requestContext ?? {},\n };\n};\n\n/**\n * Extracts the user message text from a scorer run input.\n *\n * Finds the first message with role 'user' and extracts its text content.\n *\n * @param input - The scorer run input containing input messages\n * @returns The user message text, or `undefined` if no user message is found\n *\n * @example\n * ```ts\n * const scorer = createScorer({ ... })\n * .preprocess(({ run }) => {\n * const userText = getUserMessageFromRunInput(run.input);\n * return { userText };\n * });\n * ```\n */\nexport const getUserMessageFromRunInput = (input?: ScorerRunInputForAgent): string | undefined => {\n const message = input?.inputMessages.find(({ role }) => role === 'user');\n return message ? getTextContentFromMastraDBMessage(message) : undefined;\n};\n\n/**\n * Extracts all system messages from a scorer run input.\n *\n * Collects text from both standard system messages and tagged system messages\n * (specialized system prompts like memory instructions).\n *\n * @param input - The scorer run input containing system messages\n * @returns An array of system message strings\n *\n * @example\n * ```ts\n * const scorer = createScorer({ ... })\n * .preprocess(({ run }) => {\n * const systemMessages = getSystemMessagesFromRunInput(run.input);\n * return { systemPrompt: systemMessages.join('\\n') };\n * });\n * ```\n */\nexport const getSystemMessagesFromRunInput = (input?: ScorerRunInputForAgent): string[] => {\n const systemMessages: string[] = [];\n\n // Add standard system messages\n if (input?.systemMessages) {\n systemMessages.push(\n ...input.systemMessages\n .map(msg => {\n // Handle different content types - extract text if it's an array of parts\n if (typeof msg.content === 'string') {\n return msg.content;\n } else if (Array.isArray(msg.content)) {\n // Extract text from parts array\n return msg.content\n .filter((part: any) => part.type === 'text')\n .map((part: any) => part.text || '')\n .join(' ');\n }\n return '';\n })\n .filter(content => content),\n );\n }\n\n // Add tagged system messages (these are specialized system prompts)\n if (input?.taggedSystemMessages) {\n Object.values(input.taggedSystemMessages).forEach(messages => {\n messages.forEach(msg => {\n if (typeof msg.content === 'string') {\n systemMessages.push(msg.content);\n }\n });\n });\n }\n\n return systemMessages;\n};\n\n/**\n * Combines all system messages into a single prompt string.\n *\n * Joins all system messages (standard and tagged) with double newlines.\n *\n * @param input - The scorer run input containing system messages\n * @returns A combined system prompt string\n *\n * @example\n * ```ts\n * const scorer = createScorer({ ... })\n * .preprocess(({ run }) => {\n * const systemPrompt = getCombinedSystemPrompt(run.input);\n * return { systemPrompt };\n * });\n * ```\n */\nexport const getCombinedSystemPrompt = (input?: ScorerRunInputForAgent): string => {\n const systemMessages = getSystemMessagesFromRunInput(input);\n return systemMessages.join('\\n\\n');\n};\n\n/**\n * Extracts the assistant message text from a scorer run output.\n *\n * Finds the first message with role 'assistant' and extracts its text content.\n *\n * @param output - The scorer run output (array of MastraDBMessage)\n * @returns The assistant message text, or `undefined` if no assistant message is found\n *\n * @example\n * ```ts\n * const scorer = createScorer({ ... })\n * .preprocess(({ run }) => {\n * const response = getAssistantMessageFromRunOutput(run.output);\n * return { response };\n * });\n * ```\n */\nexport const getAssistantMessageFromRunOutput = (output?: ScorerRunOutputForAgent) => {\n const message = output?.find(({ role }) => role === 'assistant');\n return message ? getTextContentFromMastraDBMessage(message) : undefined;\n};\n\n/**\n * Extracts reasoning text from a scorer run output.\n *\n * This function extracts reasoning content from assistant messages, which is\n * produced by reasoning models like `deepseek-reasoner`. The reasoning can be\n * stored in two places:\n * 1. `content.reasoning` - a string field on the message content\n * 2. `content.parts` - as parts with `type: 'reasoning'` containing `details`\n *\n * @param output - The scorer run output (array of MastraDBMessage)\n * @returns The reasoning text, or `undefined` if no reasoning is present\n *\n * @example\n * ```ts\n * const reasoningScorer = createScorer({\n * id: 'reasoning-scorer',\n * name: 'Reasoning Quality',\n * description: 'Evaluates the quality of model reasoning',\n * type: 'agent',\n * })\n * .preprocess(({ run }) => {\n * const reasoning = getReasoningFromRunOutput(run.output);\n * const response = getAssistantMessageFromRunOutput(run.output);\n * return { reasoning, response };\n * })\n * .generateScore(({ results }) => {\n * // Score based on reasoning quality\n * return results.preprocessStepResult?.reasoning ? 1 : 0;\n * });\n * ```\n */\nexport const getReasoningFromRunOutput = (output?: ScorerRunOutputForAgent): string | undefined => {\n if (!output) return undefined;\n\n const message = output.find(({ role }) => role === 'assistant');\n if (!message) return undefined;\n\n // Check for reasoning in content.reasoning (string format)\n if (message.content.reasoning) {\n return message.content.reasoning;\n }\n\n // Check for reasoning in parts with type 'reasoning'\n // Reasoning models store reasoning in parts as { type: 'reasoning', details: [{ type: 'text', text: '...' }] }\n const reasoningParts = message.content.parts?.filter((p: any) => p.type === 'reasoning');\n if (reasoningParts && reasoningParts.length > 0) {\n const reasoningTexts = reasoningParts\n .map((p: any) => {\n // The reasoning text can be in p.reasoning or in p.details[].text\n if (p.details && Array.isArray(p.details)) {\n return p.details\n .filter((d: any) => d.type === 'text')\n .map((d: any) => d.text)\n .join('');\n }\n return p.reasoning || '';\n })\n .filter(Boolean);\n\n return reasoningTexts.length > 0 ? reasoningTexts.join('\\n') : undefined;\n }\n\n return undefined;\n};\n\n/**\n * Creates a tool invocation object for testing purposes.\n *\n * @param options - The tool invocation configuration\n * @param options.toolCallId - Unique identifier for the tool call\n * @param options.toolName - Name of the tool being called\n * @param options.args - Arguments passed to the tool\n * @param options.result - Result returned by the tool\n * @param options.state - State of the invocation (default: 'result')\n * @returns A tool invocation object\n *\n * @example\n * ```ts\n * const invocation = createToolInvocation({\n * toolCallId: 'call-123',\n * toolName: 'weatherTool',\n * args: { location: 'London' },\n * result: { temperature: 20, condition: 'sunny' },\n * });\n * ```\n */\nexport const createToolInvocation = ({\n toolCallId,\n toolName,\n args,\n result,\n state = 'result',\n}: {\n toolCallId: string;\n toolName: string;\n args: Record<string, any>;\n result: Record<string, any>;\n state?: 'call' | 'partial-call' | 'result';\n}): { toolCallId: string; toolName: string; args: Record<string, any>; result: Record<string, any>; state: string } => {\n return {\n toolCallId,\n toolName,\n args,\n result,\n state,\n };\n};\n\n/**\n * Creates a MastraDBMessage object for testing purposes.\n *\n * Supports optional tool invocations for testing tool call scenarios.\n *\n * @param options - The message configuration\n * @param options.content - The text content of the message\n * @param options.role - The role of the message sender ('user', 'assistant', or 'system')\n * @param options.id - Optional message ID (default: 'test-message')\n * @param options.toolInvocations - Optional array of tool invocations\n * @returns A MastraDBMessage object\n *\n * @example\n * ```ts\n * const message = createTestMessage({\n * content: 'Hello, how can I help?',\n * role: 'assistant',\n * });\n *\n * // With tool invocations\n * const messageWithTools = createTestMessage({\n * content: 'Let me check the weather.',\n * role: 'assistant',\n * toolInvocations: [{\n * toolCallId: 'call-1',\n * toolName: 'weatherTool',\n * args: { location: 'Paris' },\n * result: { temp: 22 },\n * state: 'result',\n * }],\n * });\n * ```\n */\nexport function createTestMessage({\n content,\n role,\n id = 'test-message',\n toolInvocations = [],\n}: {\n content: string;\n role: 'user' | 'assistant' | 'system';\n id?: string;\n toolInvocations?: Array<{\n toolCallId: string;\n toolName: string;\n args: Record<string, any>;\n result: Record<string, any>;\n state: any;\n }>;\n}): MastraDBMessage {\n return {\n id,\n role,\n content: {\n format: 2,\n parts: [{ type: 'text', text: content }],\n content,\n ...(toolInvocations.length > 0 && {\n toolInvocations: toolInvocations.map(ti => ({\n toolCallId: ti.toolCallId,\n toolName: ti.toolName,\n args: ti.args,\n result: ti.result,\n state: ti.state,\n })),\n }),\n },\n createdAt: new Date(),\n };\n}\n\n/**\n * Creates a complete agent test run object for testing scorers.\n *\n * Provides a convenient way to construct the full run object that scorers receive,\n * including input messages, output, system messages, and request context.\n *\n * @param options - The test run configuration\n * @param options.inputMessages - Array of input messages (default: [])\n * @param options.output - The output messages (required)\n * @param options.rememberedMessages - Array of remembered messages from memory (default: [])\n * @param options.systemMessages - Array of system messages (default: [])\n * @param options.taggedSystemMessages - Tagged system messages map (default: {})\n * @param options.requestContext - Request context (default: new RequestContext())\n * @param options.runId - Unique run ID (default: random UUID)\n * @returns A complete test run object\n *\n * @example\n * ```ts\n * const testRun = createAgentTestRun({\n * inputMessages: [createTestMessage({ content: 'Hello', role: 'user' })],\n * output: [createTestMessage({ content: 'Hi there!', role: 'assistant' })],\n * });\n *\n * const result = await scorer.run({\n * input: testRun.input,\n * output: testRun.output,\n * });\n * ```\n */\nexport const createAgentTestRun = ({\n inputMessages = [],\n output,\n rememberedMessages = [],\n systemMessages = [],\n taggedSystemMessages = {},\n requestContext = new RequestContext(),\n runId = crypto.randomUUID(),\n}: {\n inputMessages?: ScorerRunInputForAgent['inputMessages'];\n output: ScorerRunOutputForAgent;\n rememberedMessages?: ScorerRunInputForAgent['rememberedMessages'];\n systemMessages?: ScorerRunInputForAgent['systemMessages'];\n taggedSystemMessages?: ScorerRunInputForAgent['taggedSystemMessages'];\n requestContext?: RequestContext;\n runId?: string;\n}): {\n input: ScorerRunInputForAgent;\n output: ScorerRunOutputForAgent;\n requestContext: RequestContext;\n runId: string;\n} => {\n return {\n input: {\n inputMessages,\n rememberedMessages,\n systemMessages,\n taggedSystemMessages,\n },\n output,\n requestContext,\n runId,\n };\n};\n\n/**\n * Information about a tool call extracted from scorer output.\n */\nexport type ToolCallInfo = {\n /** Name of the tool that was called */\n toolName: string;\n /** Unique identifier for the tool call */\n toolCallId: string;\n /** Index of the message containing this tool call */\n messageIndex: number;\n /** Index of the invocation within the message's tool invocations */\n invocationIndex: number;\n};\n\n/**\n * Extracts all tool calls from a scorer run output.\n *\n * Iterates through all messages and their tool invocations to collect\n * information about tools that were called (with state 'result' or 'call').\n *\n * @param output - The scorer run output (array of MastraDBMessage)\n * @returns An object containing tool names and detailed tool call info\n *\n * @example\n * ```ts\n * const scorer = createScorer({ ... })\n * .preprocess(({ run }) => {\n * const { tools, toolCallInfos } = extractToolCalls(run.output);\n * return {\n * toolsUsed: tools,\n * toolCount: tools.length,\n * };\n * });\n * ```\n */\nexport function extractToolCalls(output: ScorerRunOutputForAgent): { tools: string[]; toolCallInfos: ToolCallInfo[] } {\n const toolCalls: string[] = [];\n const toolCallInfos: ToolCallInfo[] = [];\n\n for (let messageIndex = 0; messageIndex < output.length; messageIndex++) {\n const message = output[messageIndex];\n // Tool invocations are now nested under content\n if (message?.content?.toolInvocations) {\n for (let invocationIndex = 0; invocationIndex < message.content.toolInvocations.length; invocationIndex++) {\n const invocation = message.content.toolInvocations[invocationIndex];\n if (invocation && invocation.toolName && (invocation.state === 'result' || invocation.state === 'call')) {\n toolCalls.push(invocation.toolName);\n toolCallInfos.push({\n toolName: invocation.toolName,\n toolCallId: invocation.toolCallId || `${messageIndex}-${invocationIndex}`,\n messageIndex,\n invocationIndex,\n });\n }\n }\n }\n }\n\n return { tools: toolCalls, toolCallInfos };\n}\n\n/**\n * Extracts text content from all input messages.\n *\n * @param runInput - The scorer run input\n * @returns An array of text strings from each input message\n *\n * @example\n * ```ts\n * const scorer = createScorer({ ... })\n * .preprocess(({ run }) => {\n * const messages = extractInputMessages(run.input);\n * return { allUserMessages: messages.join('\\n') };\n * });\n * ```\n */\nexport const extractInputMessages = (runInput: ScorerRunInputForAgent | undefined): string[] => {\n return runInput?.inputMessages?.map(msg => getTextContentFromMastraDBMessage(msg)) || [];\n};\n\n/**\n * Extracts text content from all assistant response messages.\n *\n * Filters for messages with role 'assistant' and extracts their text content.\n *\n * @param runOutput - The scorer run output (array of MastraDBMessage)\n * @returns An array of text strings from each assistant message\n *\n * @example\n * ```ts\n * const scorer = createScorer({ ... })\n * .preprocess(({ run }) => {\n * const responses = extractAgentResponseMessages(run.output);\n * return { allResponses: responses.join('\\n') };\n * });\n * ```\n */\nexport const extractAgentResponseMessages = (runOutput: ScorerRunOutputForAgent): string[] => {\n return runOutput.filter(msg => msg.role === 'assistant').map(msg => getTextContentFromMastraDBMessage(msg));\n};\n\n/**\n * Information about a tool result extracted from scorer output.\n */\nexport type ToolResultInfo = {\n /** Name of the tool that was called */\n toolName: string;\n /** Unique identifier for the tool call */\n toolCallId: string;\n /** Arguments passed to the tool */\n args: Record<string, any>;\n /** Result returned by the tool */\n result: any;\n};\n\n/**\n * Extracts tool results from a scorer run output.\n *\n * Returns structured objects that can be used with the hallucination scorer's\n * `getContext` hook or for other scorer logic.\n *\n * @param output - The scorer run output (array of MastraDBMessage)\n * @returns An array of ToolResultInfo objects\n *\n * @example\n * ```ts\n * import { extractToolResults } from '@mastra/evals/scorers';\n * import { createHallucinationScorer } from '@mastra/evals/scorers/prebuilt';\n *\n * const scorer = createHallucinationScorer({\n * model: openai('gpt-4o'),\n * options: {\n * getContext: (run) => {\n * const toolResults = extractToolResults(run.output);\n * return toolResults.map(t => JSON.stringify({ tool: t.toolName, result: t.result }));\n * },\n * },\n * });\n * ```\n */\nexport function extractToolResults(output: ScorerRunOutputForAgent): ToolResultInfo[] {\n const results: ToolResultInfo[] = [];\n\n for (const message of output) {\n const toolInvocations = message?.content?.toolInvocations;\n if (!toolInvocations) continue;\n\n for (const invocation of toolInvocations) {\n if (invocation.state === 'result' && invocation.result !== undefined) {\n results.push({\n toolName: invocation.toolName,\n toolCallId: invocation.toolCallId || '',\n args: invocation.args || {},\n result: invocation.result,\n });\n }\n }\n }\n\n return results;\n}\n"]}
|
|
@@ -1,24 +1,35 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var requestContext = require('@mastra/core/request-context');
|
|
4
4
|
|
|
5
5
|
// src/scorers/utils.ts
|
|
6
|
+
function getTextContentFromMastraDBMessage(message) {
|
|
7
|
+
if (typeof message.content.content === "string" && message.content.content !== "") {
|
|
8
|
+
return message.content.content;
|
|
9
|
+
}
|
|
10
|
+
if (message.content.parts && Array.isArray(message.content.parts)) {
|
|
11
|
+
const textParts = message.content.parts.filter((p) => p.type === "text");
|
|
12
|
+
return textParts.length > 0 ? textParts[textParts.length - 1]?.text || "" : "";
|
|
13
|
+
}
|
|
14
|
+
return "";
|
|
15
|
+
}
|
|
6
16
|
var roundToTwoDecimals = (num) => {
|
|
7
17
|
return Math.round((num + Number.EPSILON) * 100) / 100;
|
|
8
18
|
};
|
|
9
19
|
function isCloserTo(value, target1, target2) {
|
|
10
20
|
return Math.abs(value - target1) < Math.abs(value - target2);
|
|
11
21
|
}
|
|
12
|
-
var createTestRun = (input, output, additionalContext,
|
|
22
|
+
var createTestRun = (input, output, additionalContext, requestContext) => {
|
|
13
23
|
return {
|
|
14
24
|
input: [{ role: "user", content: input }],
|
|
15
25
|
output: { role: "assistant", text: output },
|
|
16
26
|
additionalContext: additionalContext ?? {},
|
|
17
|
-
|
|
27
|
+
requestContext: requestContext ?? {}
|
|
18
28
|
};
|
|
19
29
|
};
|
|
20
30
|
var getUserMessageFromRunInput = (input) => {
|
|
21
|
-
|
|
31
|
+
const message = input?.inputMessages.find(({ role }) => role === "user");
|
|
32
|
+
return message ? getTextContentFromMastraDBMessage(message) : void 0;
|
|
22
33
|
};
|
|
23
34
|
var getSystemMessagesFromRunInput = (input) => {
|
|
24
35
|
const systemMessages = [];
|
|
@@ -50,7 +61,27 @@ var getCombinedSystemPrompt = (input) => {
|
|
|
50
61
|
return systemMessages.join("\n\n");
|
|
51
62
|
};
|
|
52
63
|
var getAssistantMessageFromRunOutput = (output) => {
|
|
53
|
-
|
|
64
|
+
const message = output?.find(({ role }) => role === "assistant");
|
|
65
|
+
return message ? getTextContentFromMastraDBMessage(message) : void 0;
|
|
66
|
+
};
|
|
67
|
+
var getReasoningFromRunOutput = (output) => {
|
|
68
|
+
if (!output) return void 0;
|
|
69
|
+
const message = output.find(({ role }) => role === "assistant");
|
|
70
|
+
if (!message) return void 0;
|
|
71
|
+
if (message.content.reasoning) {
|
|
72
|
+
return message.content.reasoning;
|
|
73
|
+
}
|
|
74
|
+
const reasoningParts = message.content.parts?.filter((p) => p.type === "reasoning");
|
|
75
|
+
if (reasoningParts && reasoningParts.length > 0) {
|
|
76
|
+
const reasoningTexts = reasoningParts.map((p) => {
|
|
77
|
+
if (p.details && Array.isArray(p.details)) {
|
|
78
|
+
return p.details.filter((d) => d.type === "text").map((d) => d.text).join("");
|
|
79
|
+
}
|
|
80
|
+
return p.reasoning || "";
|
|
81
|
+
}).filter(Boolean);
|
|
82
|
+
return reasoningTexts.length > 0 ? reasoningTexts.join("\n") : void 0;
|
|
83
|
+
}
|
|
84
|
+
return void 0;
|
|
54
85
|
};
|
|
55
86
|
var createToolInvocation = ({
|
|
56
87
|
toolCallId,
|
|
@@ -67,27 +98,39 @@ var createToolInvocation = ({
|
|
|
67
98
|
state
|
|
68
99
|
};
|
|
69
100
|
};
|
|
70
|
-
|
|
101
|
+
function createTestMessage({
|
|
71
102
|
content,
|
|
72
103
|
role,
|
|
73
104
|
id = "test-message",
|
|
74
105
|
toolInvocations = []
|
|
75
|
-
})
|
|
106
|
+
}) {
|
|
76
107
|
return {
|
|
77
108
|
id,
|
|
78
109
|
role,
|
|
79
|
-
content
|
|
80
|
-
|
|
81
|
-
|
|
110
|
+
content: {
|
|
111
|
+
format: 2,
|
|
112
|
+
parts: [{ type: "text", text: content }],
|
|
113
|
+
content,
|
|
114
|
+
...toolInvocations.length > 0 && {
|
|
115
|
+
toolInvocations: toolInvocations.map((ti) => ({
|
|
116
|
+
toolCallId: ti.toolCallId,
|
|
117
|
+
toolName: ti.toolName,
|
|
118
|
+
args: ti.args,
|
|
119
|
+
result: ti.result,
|
|
120
|
+
state: ti.state
|
|
121
|
+
}))
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
82
125
|
};
|
|
83
|
-
}
|
|
126
|
+
}
|
|
84
127
|
var createAgentTestRun = ({
|
|
85
128
|
inputMessages = [],
|
|
86
129
|
output,
|
|
87
130
|
rememberedMessages = [],
|
|
88
131
|
systemMessages = [],
|
|
89
132
|
taggedSystemMessages = {},
|
|
90
|
-
|
|
133
|
+
requestContext: requestContext$1 = new requestContext.RequestContext(),
|
|
91
134
|
runId = crypto.randomUUID()
|
|
92
135
|
}) => {
|
|
93
136
|
return {
|
|
@@ -98,7 +141,7 @@ var createAgentTestRun = ({
|
|
|
98
141
|
taggedSystemMessages
|
|
99
142
|
},
|
|
100
143
|
output,
|
|
101
|
-
|
|
144
|
+
requestContext: requestContext$1,
|
|
102
145
|
runId
|
|
103
146
|
};
|
|
104
147
|
};
|
|
@@ -107,9 +150,9 @@ function extractToolCalls(output) {
|
|
|
107
150
|
const toolCallInfos = [];
|
|
108
151
|
for (let messageIndex = 0; messageIndex < output.length; messageIndex++) {
|
|
109
152
|
const message = output[messageIndex];
|
|
110
|
-
if (message?.toolInvocations) {
|
|
111
|
-
for (let invocationIndex = 0; invocationIndex < message.toolInvocations.length; invocationIndex++) {
|
|
112
|
-
const invocation = message.toolInvocations[invocationIndex];
|
|
153
|
+
if (message?.content?.toolInvocations) {
|
|
154
|
+
for (let invocationIndex = 0; invocationIndex < message.content.toolInvocations.length; invocationIndex++) {
|
|
155
|
+
const invocation = message.content.toolInvocations[invocationIndex];
|
|
113
156
|
if (invocation && invocation.toolName && (invocation.state === "result" || invocation.state === "call")) {
|
|
114
157
|
toolCalls.push(invocation.toolName);
|
|
115
158
|
toolCallInfos.push({
|
|
@@ -125,24 +168,45 @@ function extractToolCalls(output) {
|
|
|
125
168
|
return { tools: toolCalls, toolCallInfos };
|
|
126
169
|
}
|
|
127
170
|
var extractInputMessages = (runInput) => {
|
|
128
|
-
return runInput?.inputMessages?.map((msg) => msg
|
|
171
|
+
return runInput?.inputMessages?.map((msg) => getTextContentFromMastraDBMessage(msg)) || [];
|
|
129
172
|
};
|
|
130
173
|
var extractAgentResponseMessages = (runOutput) => {
|
|
131
|
-
return runOutput.filter((msg) => msg.role === "assistant").map((msg) => msg
|
|
174
|
+
return runOutput.filter((msg) => msg.role === "assistant").map((msg) => getTextContentFromMastraDBMessage(msg));
|
|
132
175
|
};
|
|
176
|
+
function extractToolResults(output) {
|
|
177
|
+
const results = [];
|
|
178
|
+
for (const message of output) {
|
|
179
|
+
const toolInvocations = message?.content?.toolInvocations;
|
|
180
|
+
if (!toolInvocations) continue;
|
|
181
|
+
for (const invocation of toolInvocations) {
|
|
182
|
+
if (invocation.state === "result" && invocation.result !== void 0) {
|
|
183
|
+
results.push({
|
|
184
|
+
toolName: invocation.toolName,
|
|
185
|
+
toolCallId: invocation.toolCallId || "",
|
|
186
|
+
args: invocation.args || {},
|
|
187
|
+
result: invocation.result
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return results;
|
|
193
|
+
}
|
|
133
194
|
|
|
134
195
|
exports.createAgentTestRun = createAgentTestRun;
|
|
196
|
+
exports.createTestMessage = createTestMessage;
|
|
135
197
|
exports.createTestRun = createTestRun;
|
|
136
198
|
exports.createToolInvocation = createToolInvocation;
|
|
137
|
-
exports.createUIMessage = createUIMessage;
|
|
138
199
|
exports.extractAgentResponseMessages = extractAgentResponseMessages;
|
|
139
200
|
exports.extractInputMessages = extractInputMessages;
|
|
140
201
|
exports.extractToolCalls = extractToolCalls;
|
|
202
|
+
exports.extractToolResults = extractToolResults;
|
|
141
203
|
exports.getAssistantMessageFromRunOutput = getAssistantMessageFromRunOutput;
|
|
142
204
|
exports.getCombinedSystemPrompt = getCombinedSystemPrompt;
|
|
205
|
+
exports.getReasoningFromRunOutput = getReasoningFromRunOutput;
|
|
143
206
|
exports.getSystemMessagesFromRunInput = getSystemMessagesFromRunInput;
|
|
207
|
+
exports.getTextContentFromMastraDBMessage = getTextContentFromMastraDBMessage;
|
|
144
208
|
exports.getUserMessageFromRunInput = getUserMessageFromRunInput;
|
|
145
209
|
exports.isCloserTo = isCloserTo;
|
|
146
210
|
exports.roundToTwoDecimals = roundToTwoDecimals;
|
|
147
|
-
//# sourceMappingURL=chunk-
|
|
148
|
-
//# sourceMappingURL=chunk-
|
|
211
|
+
//# sourceMappingURL=chunk-W3U7MMDX.cjs.map
|
|
212
|
+
//# sourceMappingURL=chunk-W3U7MMDX.cjs.map
|