@mastra/core 0.15.3 → 0.16.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/agent/index.cjs +8 -8
  3. package/dist/agent/index.d.ts.map +1 -1
  4. package/dist/agent/index.js +1 -1
  5. package/dist/agent/input-processor/index.cjs +6 -6
  6. package/dist/agent/input-processor/index.js +1 -1
  7. package/dist/chunk-2BFCQRWV.cjs +673 -0
  8. package/dist/chunk-2BFCQRWV.cjs.map +1 -0
  9. package/dist/{chunk-K6UMYGK5.cjs → chunk-3CJXUAA2.cjs} +2 -2
  10. package/dist/{chunk-K6UMYGK5.cjs.map → chunk-3CJXUAA2.cjs.map} +1 -1
  11. package/dist/{chunk-EZCMCWSC.cjs → chunk-7GYN2OE3.cjs} +131 -61
  12. package/dist/chunk-7GYN2OE3.cjs.map +1 -0
  13. package/dist/{chunk-AWES6LTC.cjs → chunk-7NKIBBCV.cjs} +4 -4
  14. package/dist/{chunk-AWES6LTC.cjs.map → chunk-7NKIBBCV.cjs.map} +1 -1
  15. package/dist/{chunk-PDODMDSQ.js → chunk-A5VGUE2H.js} +3 -3
  16. package/dist/{chunk-PDODMDSQ.js.map → chunk-A5VGUE2H.js.map} +1 -1
  17. package/dist/chunk-ABJOUEVA.cjs +10 -0
  18. package/dist/chunk-ABJOUEVA.cjs.map +1 -0
  19. package/dist/{chunk-VZYIKGJ6.cjs → chunk-AHJY7RHO.cjs} +4 -4
  20. package/dist/{chunk-VZYIKGJ6.cjs.map → chunk-AHJY7RHO.cjs.map} +1 -1
  21. package/dist/{chunk-Z637KSJF.cjs → chunk-BHB4PDNV.cjs} +4 -4
  22. package/dist/{chunk-Z637KSJF.cjs.map → chunk-BHB4PDNV.cjs.map} +1 -1
  23. package/dist/{chunk-AEE54ND4.js → chunk-D2Y5SXZN.js} +13 -7
  24. package/dist/chunk-D2Y5SXZN.js.map +1 -0
  25. package/dist/{chunk-65ZPZGFH.cjs → chunk-DRMT4EQA.cjs} +4 -4
  26. package/dist/{chunk-65ZPZGFH.cjs.map → chunk-DRMT4EQA.cjs.map} +1 -1
  27. package/dist/chunk-IHVB4C5U.cjs +4 -0
  28. package/dist/{chunk-X4RMXTXF.cjs.map → chunk-IHVB4C5U.cjs.map} +1 -1
  29. package/dist/{chunk-QQO4SF3C.js → chunk-JT2QXHUD.js} +16 -6
  30. package/dist/chunk-JT2QXHUD.js.map +1 -0
  31. package/dist/{chunk-YGW2WEJ5.js → chunk-JTU7FZ5O.js} +2 -2
  32. package/dist/{chunk-YGW2WEJ5.js.map → chunk-JTU7FZ5O.js.map} +1 -1
  33. package/dist/chunk-MMYGYTJK.js +665 -0
  34. package/dist/chunk-MMYGYTJK.js.map +1 -0
  35. package/dist/chunk-NLNKQD2T.js +7 -0
  36. package/dist/chunk-NLNKQD2T.js.map +1 -0
  37. package/dist/{chunk-4VU6A5XE.js → chunk-QQIBOVFQ.js} +3 -3
  38. package/dist/{chunk-4VU6A5XE.js.map → chunk-QQIBOVFQ.js.map} +1 -1
  39. package/dist/chunk-S43VACTO.js +3 -0
  40. package/dist/{chunk-GXSERFAG.js.map → chunk-S43VACTO.js.map} +1 -1
  41. package/dist/{chunk-FTAXL6TR.cjs → chunk-SLDGELU7.cjs} +25 -15
  42. package/dist/chunk-SLDGELU7.cjs.map +1 -0
  43. package/dist/{chunk-R7K2QO7M.js → chunk-TLJPVRO5.js} +4 -4
  44. package/dist/{chunk-R7K2QO7M.js.map → chunk-TLJPVRO5.js.map} +1 -1
  45. package/dist/{chunk-ZHFYYSVY.cjs → chunk-YEZD4ZLX.cjs} +17 -11
  46. package/dist/chunk-YEZD4ZLX.cjs.map +1 -0
  47. package/dist/{chunk-VZS4UVKF.js → chunk-YFAHGS45.js} +3 -3
  48. package/dist/{chunk-VZS4UVKF.js.map → chunk-YFAHGS45.js.map} +1 -1
  49. package/dist/{chunk-AVPW677Z.js → chunk-YILDTNQM.js} +117 -47
  50. package/dist/chunk-YILDTNQM.js.map +1 -0
  51. package/dist/index.cjs +31 -31
  52. package/dist/index.js +8 -8
  53. package/dist/loop/index.cjs +2 -2
  54. package/dist/loop/index.js +1 -1
  55. package/dist/loop/workflow/llm-execution.d.ts +4 -4
  56. package/dist/loop/workflow/outer-llm-step.d.ts +2 -2
  57. package/dist/loop/workflow/schema.d.ts +2 -2
  58. package/dist/mastra/hooks.d.ts +3 -1
  59. package/dist/mastra/hooks.d.ts.map +1 -1
  60. package/dist/mastra/index.cjs +2 -2
  61. package/dist/mastra/index.js +1 -1
  62. package/dist/network/index.cjs +2 -2
  63. package/dist/network/index.js +1 -1
  64. package/dist/network/vNext/index.cjs +15 -15
  65. package/dist/network/vNext/index.js +2 -2
  66. package/dist/processors/index.cjs +8 -8
  67. package/dist/processors/index.js +2 -2
  68. package/dist/relevance/index.cjs +4 -4
  69. package/dist/relevance/index.js +1 -1
  70. package/dist/scores/hooks.d.ts +3 -1
  71. package/dist/scores/hooks.d.ts.map +1 -1
  72. package/dist/scores/index.cjs +29 -638
  73. package/dist/scores/index.cjs.map +1 -1
  74. package/dist/scores/index.js +1 -636
  75. package/dist/scores/index.js.map +1 -1
  76. package/dist/scores/types.d.ts +80 -0
  77. package/dist/scores/types.d.ts.map +1 -1
  78. package/dist/server/index.cjs +2 -2
  79. package/dist/server/index.js +1 -1
  80. package/dist/storage/base.d.ts +2 -2
  81. package/dist/storage/base.d.ts.map +1 -1
  82. package/dist/storage/domains/memory/inmemory.d.ts.map +1 -1
  83. package/dist/storage/index.cjs +8 -6
  84. package/dist/storage/index.cjs.map +1 -1
  85. package/dist/storage/index.js +4 -2
  86. package/dist/storage/index.js.map +1 -1
  87. package/dist/stream/base/output.d.ts.map +1 -1
  88. package/dist/stream/index.cjs +3 -3
  89. package/dist/stream/index.js +1 -1
  90. package/dist/telemetry/index.cjs +7 -7
  91. package/dist/telemetry/index.js +1 -1
  92. package/dist/tools/index.d.ts +1 -0
  93. package/dist/tools/index.d.ts.map +1 -1
  94. package/dist/tools/ui-types.d.ts +39 -0
  95. package/dist/tools/ui-types.d.ts.map +1 -0
  96. package/dist/tts/index.cjs +2 -2
  97. package/dist/tts/index.js +1 -1
  98. package/dist/voice/index.cjs +4 -4
  99. package/dist/voice/index.js +1 -1
  100. package/dist/workflows/constants.cjs +6 -2
  101. package/dist/workflows/constants.d.ts +1 -0
  102. package/dist/workflows/constants.d.ts.map +1 -1
  103. package/dist/workflows/constants.js +1 -1
  104. package/dist/workflows/default.d.ts +6 -3
  105. package/dist/workflows/default.d.ts.map +1 -1
  106. package/dist/workflows/evented/execution-engine.d.ts +1 -0
  107. package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
  108. package/dist/workflows/evented/index.cjs +10 -10
  109. package/dist/workflows/evented/index.js +1 -1
  110. package/dist/workflows/evented/step-executor.d.ts.map +1 -1
  111. package/dist/workflows/execution-engine.d.ts +1 -0
  112. package/dist/workflows/execution-engine.d.ts.map +1 -1
  113. package/dist/workflows/index.cjs +10 -10
  114. package/dist/workflows/index.js +1 -1
  115. package/dist/workflows/legacy/index.cjs +22 -22
  116. package/dist/workflows/legacy/index.js +1 -1
  117. package/dist/workflows/step.d.ts +2 -1
  118. package/dist/workflows/step.d.ts.map +1 -1
  119. package/dist/workflows/types.d.ts +13 -1
  120. package/dist/workflows/types.d.ts.map +1 -1
  121. package/dist/workflows/workflow.d.ts +9 -1
  122. package/dist/workflows/workflow.d.ts.map +1 -1
  123. package/package.json +3 -3
  124. package/dist/chunk-AEE54ND4.js.map +0 -1
  125. package/dist/chunk-AVPW677Z.js.map +0 -1
  126. package/dist/chunk-EZCMCWSC.cjs.map +0 -1
  127. package/dist/chunk-FTAXL6TR.cjs.map +0 -1
  128. package/dist/chunk-GK5V7YTQ.js +0 -6
  129. package/dist/chunk-GK5V7YTQ.js.map +0 -1
  130. package/dist/chunk-GXSERFAG.js +0 -3
  131. package/dist/chunk-NFXTYMWZ.cjs +0 -8
  132. package/dist/chunk-NFXTYMWZ.cjs.map +0 -1
  133. package/dist/chunk-QQO4SF3C.js.map +0 -1
  134. package/dist/chunk-X4RMXTXF.cjs +0 -4
  135. package/dist/chunk-ZHFYYSVY.cjs.map +0 -1
@@ -1,645 +1,36 @@
1
1
  'use strict';
2
2
 
3
- var chunkEZCMCWSC_cjs = require('../chunk-EZCMCWSC.cjs');
4
- var chunkC73WLCY3_cjs = require('../chunk-C73WLCY3.cjs');
5
- var zod = require('zod');
6
- var crypto = require('crypto');
3
+ var chunk2BFCQRWV_cjs = require('../chunk-2BFCQRWV.cjs');
7
4
 
8
- var scoringExtractStepResultSchema = zod.z.record(zod.z.string(), zod.z.any()).optional();
9
- var scoringValueSchema = zod.z.number();
10
- var scoreResultSchema = zod.z.object({
11
- result: zod.z.record(zod.z.string(), zod.z.any()).optional(),
12
- score: scoringValueSchema,
13
- prompt: zod.z.string().optional()
14
- });
15
- var MastraScorer = class _MastraScorer {
16
- constructor(config, steps = [], originalPromptObjects = /* @__PURE__ */ new Map()) {
17
- this.config = config;
18
- this.steps = steps;
19
- this.originalPromptObjects = originalPromptObjects;
20
- }
21
- get name() {
22
- return this.config.name;
23
- }
24
- get description() {
25
- return this.config.description;
26
- }
27
- get judge() {
28
- return this.config.judge;
29
- }
30
- preprocess(stepDef) {
31
- const isPromptObj = this.isPromptObject(stepDef);
32
- if (isPromptObj) {
33
- const promptObj = stepDef;
34
- this.originalPromptObjects.set("preprocess", promptObj);
35
- }
36
- return new _MastraScorer(
37
- this.config,
38
- [
39
- ...this.steps,
40
- {
41
- name: "preprocess",
42
- definition: stepDef,
43
- isPromptObject: isPromptObj
44
- }
45
- ],
46
- new Map(this.originalPromptObjects)
47
- );
48
- }
49
- analyze(stepDef) {
50
- const isPromptObj = this.isPromptObject(stepDef);
51
- if (isPromptObj) {
52
- const promptObj = stepDef;
53
- this.originalPromptObjects.set("analyze", promptObj);
54
- }
55
- return new _MastraScorer(
56
- this.config,
57
- [
58
- ...this.steps,
59
- {
60
- name: "analyze",
61
- definition: isPromptObj ? void 0 : stepDef,
62
- isPromptObject: isPromptObj
63
- }
64
- ],
65
- new Map(this.originalPromptObjects)
66
- );
67
- }
68
- generateScore(stepDef) {
69
- const isPromptObj = this.isPromptObject(stepDef);
70
- if (isPromptObj) {
71
- const promptObj = stepDef;
72
- this.originalPromptObjects.set("generateScore", promptObj);
73
- }
74
- return new _MastraScorer(
75
- this.config,
76
- [
77
- ...this.steps,
78
- {
79
- name: "generateScore",
80
- definition: isPromptObj ? void 0 : stepDef,
81
- isPromptObject: isPromptObj
82
- }
83
- ],
84
- new Map(this.originalPromptObjects)
85
- );
86
- }
87
- generateReason(stepDef) {
88
- const isPromptObj = this.isPromptObject(stepDef);
89
- if (isPromptObj) {
90
- const promptObj = stepDef;
91
- this.originalPromptObjects.set("generateReason", promptObj);
92
- }
93
- return new _MastraScorer(
94
- this.config,
95
- [
96
- ...this.steps,
97
- {
98
- name: "generateReason",
99
- definition: isPromptObj ? void 0 : stepDef,
100
- isPromptObject: isPromptObj
101
- }
102
- ],
103
- new Map(this.originalPromptObjects)
104
- );
105
- }
106
- get hasGenerateScore() {
107
- return this.steps.some((step) => step.name === "generateScore");
108
- }
109
- async run(input) {
110
- if (!this.hasGenerateScore) {
111
- throw new chunkC73WLCY3_cjs.MastraError({
112
- id: "MASTR_SCORER_FAILED_TO_RUN_MISSING_GENERATE_SCORE",
113
- domain: "SCORER" /* SCORER */,
114
- category: "USER" /* USER */,
115
- text: `Cannot execute pipeline without generateScore() step`,
116
- details: {
117
- scorerId: this.config.name,
118
- steps: this.steps.map((s) => s.name).join(", ")
119
- }
120
- });
121
- }
122
- const { tracingContext } = input;
123
- let runId = input.runId;
124
- if (!runId) {
125
- runId = crypto.randomUUID();
126
- }
127
- const run = { ...input, runId };
128
- const workflow = this.toMastraWorkflow();
129
- const workflowRun = await workflow.createRunAsync();
130
- const workflowResult = await workflowRun.start({
131
- inputData: {
132
- run
133
- },
134
- tracingContext
135
- });
136
- if (workflowResult.status === "failed") {
137
- throw new chunkC73WLCY3_cjs.MastraError({
138
- id: "MASTR_SCORER_FAILED_TO_RUN_WORKFLOW_FAILED",
139
- domain: "SCORER" /* SCORER */,
140
- category: "USER" /* USER */,
141
- text: `Scorer Run Failed: ${workflowResult.error}`,
142
- details: {
143
- scorerId: this.config.name,
144
- steps: this.steps.map((s) => s.name).join(", ")
145
- }
146
- });
147
- }
148
- return this.transformToScorerResult({ workflowResult, originalInput: run });
149
- }
150
- isPromptObject(stepDef) {
151
- if (typeof stepDef === "object" && "description" in stepDef && "createPrompt" in stepDef && !("outputSchema" in stepDef)) {
152
- return true;
153
- }
154
- const isOtherPromptObject = typeof stepDef === "object" && "description" in stepDef && "outputSchema" in stepDef && "createPrompt" in stepDef;
155
- return isOtherPromptObject;
156
- }
157
- getSteps() {
158
- return this.steps.map((step) => ({
159
- name: step.name,
160
- type: step.isPromptObject ? "prompt" : "function",
161
- description: step.definition.description
162
- }));
163
- }
164
- toMastraWorkflow() {
165
- const workflowSteps = this.steps.map((scorerStep) => {
166
- return chunkEZCMCWSC_cjs.createStep({
167
- id: scorerStep.name,
168
- description: `Scorer step: ${scorerStep.name}`,
169
- inputSchema: zod.z.any(),
170
- outputSchema: zod.z.any(),
171
- execute: async ({ inputData, getInitData, tracingContext }) => {
172
- const { accumulatedResults = {}, generatedPrompts = {} } = inputData;
173
- const { run } = getInitData();
174
- const context = this.createScorerContext(scorerStep.name, run, accumulatedResults);
175
- let stepResult;
176
- let newGeneratedPrompts = generatedPrompts;
177
- if (scorerStep.isPromptObject) {
178
- const { result, prompt } = await this.executePromptStep(scorerStep, tracingContext, context);
179
- stepResult = result;
180
- newGeneratedPrompts = {
181
- ...generatedPrompts,
182
- [`${scorerStep.name}Prompt`]: prompt
183
- };
184
- } else {
185
- stepResult = await this.executeFunctionStep(scorerStep, context);
186
- }
187
- const newAccumulatedResults = {
188
- ...accumulatedResults,
189
- [`${scorerStep.name}StepResult`]: stepResult
190
- };
191
- return {
192
- stepResult,
193
- accumulatedResults: newAccumulatedResults,
194
- generatedPrompts: newGeneratedPrompts
195
- };
196
- }
197
- });
198
- });
199
- const workflow = chunkEZCMCWSC_cjs.createWorkflow({
200
- id: `scorer-${this.config.name}`,
201
- description: this.config.description,
202
- inputSchema: zod.z.object({
203
- run: zod.z.any()
204
- // ScorerRun
205
- }),
206
- outputSchema: zod.z.object({
207
- run: zod.z.any(),
208
- score: zod.z.number(),
209
- reason: zod.z.string().optional(),
210
- preprocessResult: zod.z.any().optional(),
211
- analyzeResult: zod.z.any().optional(),
212
- preprocessPrompt: zod.z.string().optional(),
213
- analyzePrompt: zod.z.string().optional(),
214
- generateScorePrompt: zod.z.string().optional(),
215
- generateReasonPrompt: zod.z.string().optional()
216
- })
217
- });
218
- let chainedWorkflow = workflow;
219
- for (const step of workflowSteps) {
220
- chainedWorkflow = chainedWorkflow.then(step);
221
- }
222
- return chainedWorkflow.commit();
223
- }
224
- createScorerContext(stepName, run, accumulatedResults) {
225
- if (stepName === "generateReason") {
226
- const score = accumulatedResults.generateScoreStepResult;
227
- return { run, results: accumulatedResults, score };
228
- }
229
- return { run, results: accumulatedResults };
230
- }
231
- async executeFunctionStep(scorerStep, context) {
232
- return await scorerStep.definition(context);
233
- }
234
- async executePromptStep(scorerStep, tracingContext, context) {
235
- const originalStep = this.originalPromptObjects.get(scorerStep.name);
236
- if (!originalStep) {
237
- throw new Error(`Step "${scorerStep.name}" is not a prompt object`);
238
- }
239
- const prompt = await originalStep.createPrompt(context);
240
- const model = originalStep.judge?.model ?? this.config.judge?.model;
241
- const instructions = originalStep.judge?.instructions ?? this.config.judge?.instructions;
242
- if (!model || !instructions) {
243
- throw new chunkC73WLCY3_cjs.MastraError({
244
- id: "MASTR_SCORER_FAILED_TO_RUN_MISSING_MODEL_OR_INSTRUCTIONS",
245
- domain: "SCORER" /* SCORER */,
246
- category: "USER" /* USER */,
247
- text: `Step "${scorerStep.name}" requires a model and instructions`,
248
- details: {
249
- scorerId: this.config.name,
250
- step: scorerStep.name
251
- }
252
- });
253
- }
254
- const judge = new chunkEZCMCWSC_cjs.Agent({ name: "judge", model, instructions });
255
- if (scorerStep.name === "generateScore") {
256
- let result;
257
- if (model.specificationVersion === "v2") {
258
- result = await judge.generateVNext(prompt, {
259
- output: zod.z.object({ score: zod.z.number() }),
260
- tracingContext
261
- });
262
- } else {
263
- result = await judge.generate(prompt, {
264
- output: zod.z.object({ score: zod.z.number() }),
265
- tracingContext
266
- });
267
- }
268
- return { result: result.object.score, prompt };
269
- } else if (scorerStep.name === "generateReason") {
270
- let result;
271
- if (model.specificationVersion === "v2") {
272
- result = await judge.generateVNext(prompt, { tracingContext });
273
- } else {
274
- result = await judge.generate(prompt, { tracingContext });
275
- }
276
- return { result: result.text, prompt };
277
- } else {
278
- const promptStep = originalStep;
279
- let result;
280
- if (model.specificationVersion === "v2") {
281
- result = await judge.generateVNext(prompt, {
282
- output: promptStep.outputSchema,
283
- tracingContext
284
- });
285
- } else {
286
- result = await judge.generate(prompt, {
287
- output: promptStep.outputSchema,
288
- tracingContext
289
- });
290
- }
291
- return { result: result.object, prompt };
292
- }
293
- }
294
- transformToScorerResult({
295
- workflowResult,
296
- originalInput
297
- }) {
298
- const finalStepResult = workflowResult.result;
299
- const accumulatedResults = finalStepResult?.accumulatedResults || {};
300
- const generatedPrompts = finalStepResult?.generatedPrompts || {};
301
- return {
302
- ...originalInput,
303
- score: accumulatedResults.generateScoreStepResult,
304
- generateScorePrompt: generatedPrompts.generateScorePrompt,
305
- reason: accumulatedResults.generateReasonStepResult,
306
- generateReasonPrompt: generatedPrompts.generateReasonPrompt,
307
- preprocessStepResult: accumulatedResults.preprocessStepResult,
308
- preprocessPrompt: generatedPrompts.preprocessPrompt,
309
- analyzeStepResult: accumulatedResults.analyzeStepResult,
310
- analyzePrompt: generatedPrompts.analyzePrompt
311
- };
312
- }
313
- };
314
- function createScorer(config) {
315
- return new MastraScorer({
316
- name: config.name,
317
- description: config.description,
318
- judge: config.judge
319
- });
320
- }
321
-
322
- // src/scores/run-experiment/scorerAccumulator.ts
323
- var ScoreAccumulator = class {
324
- flatScores = {};
325
- workflowScores = {};
326
- stepScores = {};
327
- addScores(scorerResults) {
328
- const isTargetWorkflowAndHasStepScores = "steps" in scorerResults;
329
- if (isTargetWorkflowAndHasStepScores) {
330
- this.addNestedScores(scorerResults);
331
- } else {
332
- this.addFlatScores(scorerResults);
333
- }
334
- }
335
- addFlatScores(scorerResults) {
336
- for (const [scorerName, result] of Object.entries(scorerResults)) {
337
- if (!this.flatScores[scorerName]) {
338
- this.flatScores[scorerName] = [];
339
- }
340
- this.flatScores[scorerName].push(result.score);
341
- }
342
- }
343
- addNestedScores(scorerResults) {
344
- if ("workflow" in scorerResults && scorerResults.workflow) {
345
- for (const [scorerName, result] of Object.entries(scorerResults.workflow)) {
346
- if (!this.workflowScores[scorerName]) {
347
- this.workflowScores[scorerName] = [];
348
- }
349
- this.workflowScores[scorerName].push(result.score);
350
- }
351
- }
352
- if ("steps" in scorerResults && scorerResults.steps) {
353
- for (const [stepId, stepResults] of Object.entries(scorerResults.steps)) {
354
- if (!this.stepScores[stepId]) {
355
- this.stepScores[stepId] = {};
356
- }
357
- for (const [scorerName, result] of Object.entries(stepResults)) {
358
- if (!this.stepScores[stepId][scorerName]) {
359
- this.stepScores[stepId][scorerName] = [];
360
- }
361
- this.stepScores[stepId][scorerName].push(result.score);
362
- }
363
- }
364
- }
365
- }
366
- addStepScores(stepScorerResults) {
367
- for (const [stepId, stepResults] of Object.entries(stepScorerResults)) {
368
- if (!this.stepScores[stepId]) {
369
- this.stepScores[stepId] = {};
370
- }
371
- for (const [scorerName, result] of Object.entries(stepResults)) {
372
- if (!this.stepScores[stepId][scorerName]) {
373
- this.stepScores[stepId][scorerName] = [];
374
- }
375
- this.stepScores[stepId][scorerName].push(result.score);
376
- }
377
- }
378
- }
379
- getAverageScores() {
380
- const result = {};
381
- for (const [scorerName, scoreArray] of Object.entries(this.flatScores)) {
382
- result[scorerName] = this.getAverageScore(scoreArray);
383
- }
384
- if (Object.keys(this.workflowScores).length > 0) {
385
- result.workflow = {};
386
- for (const [scorerName, scoreArray] of Object.entries(this.workflowScores)) {
387
- result.workflow[scorerName] = this.getAverageScore(scoreArray);
388
- }
389
- }
390
- if (Object.keys(this.stepScores).length > 0) {
391
- result.steps = {};
392
- for (const [stepId, stepScorers] of Object.entries(this.stepScores)) {
393
- result.steps[stepId] = {};
394
- for (const [scorerName, scoreArray] of Object.entries(stepScorers)) {
395
- result.steps[stepId][scorerName] = this.getAverageScore(scoreArray);
396
- }
397
- }
398
- }
399
- return result;
400
- }
401
- getAverageScore(scoreArray) {
402
- if (scoreArray.length > 0) {
403
- return scoreArray.reduce((a, b) => a + b, 0) / scoreArray.length;
404
- } else {
405
- return 0;
406
- }
407
- }
408
- };
409
5
 
410
- // src/scores/run-experiment/index.ts
411
- async function runExperiment(config) {
412
- const { data, scorers, target, onItemComplete, concurrency = 1 } = config;
413
- validateExperimentInputs(data, scorers, target);
414
- let totalItems = 0;
415
- const scoreAccumulator = new ScoreAccumulator();
416
- const pMap = (await import('p-map')).default;
417
- await pMap(
418
- data,
419
- async (item) => {
420
- const targetResult = await executeTarget(target, item);
421
- const scorerResults = await runScorers(scorers, targetResult, item);
422
- scoreAccumulator.addScores(scorerResults);
423
- if (onItemComplete) {
424
- await onItemComplete({
425
- item,
426
- targetResult,
427
- scorerResults
428
- });
429
- }
430
- totalItems++;
431
- },
432
- { concurrency }
433
- );
434
- return {
435
- scores: scoreAccumulator.getAverageScores(),
436
- summary: {
437
- totalItems
438
- }
439
- };
440
- }
441
- function isWorkflow(target) {
442
- return target instanceof chunkEZCMCWSC_cjs.Workflow;
443
- }
444
- function isWorkflowScorerConfig(scorers) {
445
- return typeof scorers === "object" && !Array.isArray(scorers) && ("workflow" in scorers || "steps" in scorers);
446
- }
447
- function validateExperimentInputs(data, scorers, target) {
448
- if (data.length === 0) {
449
- throw new chunkC73WLCY3_cjs.MastraError({
450
- domain: "SCORER",
451
- id: "RUN_EXPERIMENT_FAILED_NO_DATA_PROVIDED",
452
- category: "USER",
453
- text: "Failed to run experiment: Data array is empty"
454
- });
455
- }
456
- for (let i = 0; i < data.length; i++) {
457
- const item = data[i];
458
- if (!item || typeof item !== "object" || !("input" in item)) {
459
- throw new chunkC73WLCY3_cjs.MastraError({
460
- domain: "SCORER",
461
- id: "INVALID_DATA_ITEM",
462
- category: "USER",
463
- text: `Invalid data item at index ${i}: must have 'input' properties`
464
- });
465
- }
466
- }
467
- if (Array.isArray(scorers)) {
468
- if (scorers.length === 0) {
469
- throw new chunkC73WLCY3_cjs.MastraError({
470
- domain: "SCORER",
471
- id: "NO_SCORERS_PROVIDED",
472
- category: "USER",
473
- text: "At least one scorer must be provided"
474
- });
475
- }
476
- } else if (isWorkflow(target) && isWorkflowScorerConfig(scorers)) {
477
- const hasScorers = scorers.workflow && scorers.workflow.length > 0 || scorers.steps && Object.keys(scorers.steps).length > 0;
478
- if (!hasScorers) {
479
- throw new chunkC73WLCY3_cjs.MastraError({
480
- domain: "SCORER",
481
- id: "NO_SCORERS_PROVIDED",
482
- category: "USER",
483
- text: "At least one workflow or step scorer must be provided"
484
- });
485
- }
486
- } else if (!isWorkflow(target) && !Array.isArray(scorers)) {
487
- throw new chunkC73WLCY3_cjs.MastraError({
488
- domain: "SCORER",
489
- id: "INVALID_AGENT_SCORERS",
490
- category: "USER",
491
- text: "Agent scorers must be an array of scorers"
492
- });
493
- }
494
- }
495
- async function executeTarget(target, item) {
496
- try {
497
- if (isWorkflow(target)) {
498
- return await executeWorkflow(target, item);
499
- } else {
500
- return await executeAgent(target, item);
501
- }
502
- } catch (error) {
503
- throw new chunkC73WLCY3_cjs.MastraError(
504
- {
505
- domain: "SCORER",
506
- id: "RUN_EXPERIMENT_TARGET_FAILED_TO_GENERATE_RESULT",
507
- category: "USER",
508
- text: "Failed to run experiment: Error generating result from target",
509
- details: {
510
- item: JSON.stringify(item)
511
- }
512
- },
513
- error
514
- );
515
- }
516
- }
517
- async function executeWorkflow(target, item) {
518
- const run = target.createRun({ disableScorers: true });
519
- const workflowResult = await run.start({
520
- inputData: item.input,
521
- runtimeContext: item.runtimeContext
522
- });
523
- return {
524
- scoringData: {
525
- input: item.input,
526
- output: workflowResult.status === "success" ? workflowResult.result : void 0,
527
- stepResults: workflowResult.steps
528
- }
529
- };
530
- }
531
- async function executeAgent(agent, item) {
532
- const model = await agent.getModel();
533
- if (model.specificationVersion === "v2") {
534
- return await agent.generateVNext(item.input, {
535
- scorers: {},
536
- returnScorerData: true,
537
- runtimeContext: item.runtimeContext
538
- });
539
- } else {
540
- return await agent.generate(item.input, {
541
- scorers: {},
542
- returnScorerData: true,
543
- runtimeContext: item.runtimeContext
544
- });
545
- }
546
- }
547
- async function runScorers(scorers, targetResult, item) {
548
- const scorerResults = {};
549
- if (Array.isArray(scorers)) {
550
- for (const scorer of scorers) {
551
- try {
552
- const score = await scorer.run({
553
- input: targetResult.scoringData?.input,
554
- output: targetResult.scoringData?.output,
555
- groundTruth: item.groundTruth,
556
- runtimeContext: item.runtimeContext,
557
- tracingContext: item.tracingContext
558
- });
559
- scorerResults[scorer.name] = score;
560
- } catch (error) {
561
- throw new chunkC73WLCY3_cjs.MastraError(
562
- {
563
- domain: "SCORER",
564
- id: "RUN_EXPERIMENT_SCORER_FAILED_TO_SCORE_RESULT",
565
- category: "USER",
566
- text: `Failed to run experiment: Error running scorer ${scorer.name}`,
567
- details: {
568
- scorerName: scorer.name,
569
- item: JSON.stringify(item)
570
- }
571
- },
572
- error
573
- );
574
- }
575
- }
576
- } else {
577
- if (scorers.workflow) {
578
- const workflowScorerResults = {};
579
- for (const scorer of scorers.workflow) {
580
- const score = await scorer.run({
581
- input: targetResult.scoringData.input,
582
- output: targetResult.scoringData.output,
583
- groundTruth: item.groundTruth,
584
- runtimeContext: item.runtimeContext,
585
- tracingContext: item.tracingContext
586
- });
587
- workflowScorerResults[scorer.name] = score;
588
- }
589
- if (Object.keys(workflowScorerResults).length > 0) {
590
- scorerResults.workflow = workflowScorerResults;
591
- }
592
- }
593
- if (scorers.steps) {
594
- const stepScorerResults = {};
595
- for (const [stepId, stepScorers] of Object.entries(scorers.steps)) {
596
- const stepResult = targetResult.scoringData.stepResults?.[stepId];
597
- if (stepResult?.status === "success" && stepResult.payload && stepResult.output) {
598
- const stepResults = {};
599
- for (const scorer of stepScorers) {
600
- try {
601
- const score = await scorer.run({
602
- input: stepResult.payload,
603
- output: stepResult.output,
604
- groundTruth: item.groundTruth,
605
- runtimeContext: item.runtimeContext,
606
- tracingContext: item.tracingContext
607
- });
608
- stepResults[scorer.name] = score;
609
- } catch (error) {
610
- throw new chunkC73WLCY3_cjs.MastraError(
611
- {
612
- domain: "SCORER",
613
- id: "RUN_EXPERIMENT_SCORER_FAILED_TO_SCORE_STEP_RESULT",
614
- category: "USER",
615
- text: `Failed to run experiment: Error running scorer ${scorer.name} on step ${stepId}`,
616
- details: {
617
- scorerName: scorer.name,
618
- stepId
619
- }
620
- },
621
- error
622
- );
623
- }
624
- }
625
- if (Object.keys(stepResults).length > 0) {
626
- stepScorerResults[stepId] = stepResults;
627
- }
628
- }
629
- }
630
- if (Object.keys(stepScorerResults).length > 0) {
631
- scorerResults.steps = stepScorerResults;
632
- }
633
- }
634
- }
635
- return scorerResults;
636
- }
637
6
 
638
- exports.MastraScorer = MastraScorer;
639
- exports.createScorer = createScorer;
640
- exports.runExperiment = runExperiment;
641
- exports.scoreResultSchema = scoreResultSchema;
642
- exports.scoringExtractStepResultSchema = scoringExtractStepResultSchema;
643
- exports.scoringValueSchema = scoringValueSchema;
7
+ Object.defineProperty(exports, "MastraScorer", {
8
+ enumerable: true,
9
+ get: function () { return chunk2BFCQRWV_cjs.MastraScorer; }
10
+ });
11
+ Object.defineProperty(exports, "createScorer", {
12
+ enumerable: true,
13
+ get: function () { return chunk2BFCQRWV_cjs.createScorer; }
14
+ });
15
+ Object.defineProperty(exports, "runExperiment", {
16
+ enumerable: true,
17
+ get: function () { return chunk2BFCQRWV_cjs.runExperiment; }
18
+ });
19
+ Object.defineProperty(exports, "saveScorePayloadSchema", {
20
+ enumerable: true,
21
+ get: function () { return chunk2BFCQRWV_cjs.saveScorePayloadSchema; }
22
+ });
23
+ Object.defineProperty(exports, "scoreResultSchema", {
24
+ enumerable: true,
25
+ get: function () { return chunk2BFCQRWV_cjs.scoreResultSchema; }
26
+ });
27
+ Object.defineProperty(exports, "scoringExtractStepResultSchema", {
28
+ enumerable: true,
29
+ get: function () { return chunk2BFCQRWV_cjs.scoringExtractStepResultSchema; }
30
+ });
31
+ Object.defineProperty(exports, "scoringValueSchema", {
32
+ enumerable: true,
33
+ get: function () { return chunk2BFCQRWV_cjs.scoringValueSchema; }
34
+ });
644
35
  //# sourceMappingURL=index.cjs.map
645
36
  //# sourceMappingURL=index.cjs.map