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