@mastra/core 0.5.0-alpha.8 → 0.5.0

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 (91) hide show
  1. package/dist/agent/index.cjs +3 -2100
  2. package/dist/agent/index.d.cts +1 -1
  3. package/dist/agent/index.d.ts +1 -1
  4. package/dist/agent/index.js +1 -1
  5. package/dist/{base-CTdONy0_.d.cts → base-CIPKleAU.d.cts} +103 -70
  6. package/dist/{base-DIn_km7X.d.ts → base-C_Oq53qk.d.ts} +103 -70
  7. package/dist/base.cjs +5 -140
  8. package/dist/bundler/index.cjs +5 -160
  9. package/dist/chunk-2W2GYEYQ.cjs +25 -0
  10. package/dist/chunk-3ASEZT7U.cjs +1586 -0
  11. package/dist/chunk-43Y7WG5W.cjs +335 -0
  12. package/dist/{chunk-HBHPTMAC.js → chunk-4Y74D74B.js} +46 -6
  13. package/dist/chunk-ENT7U27Y.cjs +37 -0
  14. package/dist/chunk-F5UYWPV4.cjs +14 -0
  15. package/dist/chunk-FL3GQXQ2.cjs +218 -0
  16. package/dist/chunk-FRQFWZDN.cjs +2 -0
  17. package/dist/chunk-GXQRMKSN.cjs +367 -0
  18. package/dist/chunk-HJPMYDWO.cjs +37 -0
  19. package/dist/chunk-IIWRJFLQ.cjs +51 -0
  20. package/dist/chunk-KFQ7Z3PO.cjs +347 -0
  21. package/dist/{chunk-SWDQYPJS.js → chunk-KP5UAFLN.js} +3 -2
  22. package/dist/chunk-KPKFLQFR.cjs +12 -0
  23. package/dist/{chunk-RRJB4TCC.js → chunk-MLFXOST6.js} +1 -1
  24. package/dist/{chunk-KBSR2LLT.js → chunk-OD7ZMKHY.js} +176 -63
  25. package/dist/chunk-OTFLHXHZ.cjs +65 -0
  26. package/dist/chunk-RWTSGWWL.cjs +81 -0
  27. package/dist/chunk-ST5RMVLG.cjs +87 -0
  28. package/dist/chunk-SYQ7NK2E.cjs +24 -0
  29. package/dist/chunk-UZNQG7QO.cjs +1868 -0
  30. package/dist/chunk-V5ORZPFW.cjs +38 -0
  31. package/dist/chunk-VA4P7QJT.cjs +443 -0
  32. package/dist/chunk-WB2HREXE.cjs +166 -0
  33. package/dist/chunk-WOMOGDGR.cjs +691 -0
  34. package/dist/chunk-XB2TJ7LX.cjs +408 -0
  35. package/dist/{chunk-QABMKXI3.js → chunk-XF2FMJYK.js} +1 -1
  36. package/dist/chunk-XLSROQ26.cjs +91 -0
  37. package/dist/chunk-YK3XJ52U.cjs +192 -0
  38. package/dist/{chunk-SF5GHHOQ.js → chunk-YPD6BQIM.js} +121 -93
  39. package/dist/deployer/index.cjs +5 -167
  40. package/dist/eval/index.cjs +9 -105
  41. package/dist/eval/index.d.cts +1 -1
  42. package/dist/eval/index.d.ts +1 -1
  43. package/dist/hooks/index.cjs +14 -83
  44. package/dist/index.cjs +253 -7470
  45. package/dist/index.d.cts +4 -4
  46. package/dist/index.d.ts +4 -4
  47. package/dist/index.js +7 -7
  48. package/dist/integration/index.cjs +9 -108
  49. package/dist/integration/index.d.cts +1 -1
  50. package/dist/integration/index.d.ts +1 -1
  51. package/dist/llm/index.d.cts +1 -1
  52. package/dist/llm/index.d.ts +1 -1
  53. package/dist/logger/index.cjs +33 -161
  54. package/dist/mastra/index.cjs +3 -1755
  55. package/dist/mastra/index.d.cts +1 -1
  56. package/dist/mastra/index.d.ts +1 -1
  57. package/dist/mastra/index.js +1 -1
  58. package/dist/memory/index.cjs +4 -2050
  59. package/dist/memory/index.d.cts +1 -1
  60. package/dist/memory/index.d.ts +1 -1
  61. package/dist/memory/index.js +1 -1
  62. package/dist/relevance/index.cjs +10 -2161
  63. package/dist/relevance/index.d.cts +19 -2
  64. package/dist/relevance/index.d.ts +19 -2
  65. package/dist/relevance/index.js +1 -1
  66. package/dist/storage/index.cjs +29 -367
  67. package/dist/storage/index.d.cts +1 -1
  68. package/dist/storage/index.d.ts +1 -1
  69. package/dist/storage/libsql/index.cjs +9 -798
  70. package/dist/storage/libsql/index.d.cts +1 -1
  71. package/dist/storage/libsql/index.d.ts +1 -1
  72. package/dist/telemetry/index.cjs +21 -408
  73. package/dist/telemetry/index.d.cts +1 -1
  74. package/dist/telemetry/index.d.ts +1 -1
  75. package/dist/tools/index.cjs +11 -22
  76. package/dist/tools/index.d.cts +3 -3
  77. package/dist/tools/index.d.ts +3 -3
  78. package/dist/tts/index.cjs +3 -328
  79. package/dist/utils.cjs +41 -309
  80. package/dist/utils.d.cts +10 -4
  81. package/dist/utils.d.ts +10 -4
  82. package/dist/utils.js +1 -1
  83. package/dist/vector/filter/index.cjs +7 -189
  84. package/dist/vector/index.cjs +5 -172
  85. package/dist/vector/libsql/index.cjs +9 -1047
  86. package/dist/voice/index.cjs +8 -306
  87. package/dist/workflows/index.cjs +65 -1925
  88. package/dist/workflows/index.d.cts +4 -3
  89. package/dist/workflows/index.d.ts +4 -3
  90. package/dist/workflows/index.js +1 -1
  91. package/package.json +27 -27
@@ -1,2169 +1,18 @@
1
1
  'use strict';
2
2
 
3
- var cohereAi = require('cohere-ai');
4
- var crypto$1 = require('crypto');
5
- var stream = require('stream');
6
- var pino = require('pino');
7
- var pretty = require('pino-pretty');
8
- var ai = require('ai');
9
- var zod = require('zod');
10
- var jsonSchemaToZod = require('json-schema-to-zod');
11
- var api = require('@opentelemetry/api');
3
+ var chunkOTFLHXHZ_cjs = require('../chunk-OTFLHXHZ.cjs');
12
4
 
13
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
5
 
15
- var pino__default = /*#__PURE__*/_interopDefault(pino);
16
- var pretty__default = /*#__PURE__*/_interopDefault(pretty);
17
- var jsonSchemaToZod__default = /*#__PURE__*/_interopDefault(jsonSchemaToZod);
18
6
 
19
- var __create = Object.create;
20
- var __defProp = Object.defineProperty;
21
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
22
- var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
23
- var __typeError = msg => {
24
- throw TypeError(msg);
25
- };
26
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
7
+ Object.defineProperty(exports, "CohereRelevanceScorer", {
27
8
  enumerable: true,
28
- configurable: true,
29
- writable: true,
30
- value
31
- }) : obj[key] = value;
32
- var __name = (target, value) => __defProp(target, "name", {
33
- value,
34
- configurable: true
9
+ get: function () { return chunkOTFLHXHZ_cjs.CohereRelevanceScorer; }
35
10
  });
36
- var __decoratorStart = base => [,,, __create(base?.[__knownSymbol("metadata")] ?? null)];
37
- var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
38
- var __expectFn = fn => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
39
- var __decoratorContext = (kind, name, done, metadata, fns) => ({
40
- kind: __decoratorStrings[kind],
41
- name,
42
- metadata,
43
- addInitializer: fn => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null))
11
+ Object.defineProperty(exports, "MastraAgentRelevanceScorer", {
12
+ enumerable: true,
13
+ get: function () { return chunkOTFLHXHZ_cjs.MastraAgentRelevanceScorer; }
14
+ });
15
+ Object.defineProperty(exports, "createSimilarityPrompt", {
16
+ enumerable: true,
17
+ get: function () { return chunkOTFLHXHZ_cjs.createSimilarityPrompt; }
44
18
  });
45
- var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
46
- var __runInitializers = (array, flags, self, value) => {
47
- for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) fns[i].call(self) ;
48
- return value;
49
- };
50
- var __decorateElement = (array, flags, name, decorators, target, extra) => {
51
- var it,
52
- done,
53
- ctx,
54
- k = flags & 7,
55
- p = false;
56
- var j = 0;
57
- var extraInitializers = array[j] || (array[j] = []);
58
- var desc = k && ((target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(target , name));
59
- __name(target, name);
60
- for (var i = decorators.length - 1; i >= 0; i--) {
61
- ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
62
- it = (0, decorators[i])(target, ctx), done._ = 1;
63
- __expectFn(it) && (target = it);
64
- }
65
- return __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
66
- };
67
- var CohereRelevanceScorer = class {
68
- client;
69
- model;
70
- constructor(model, apiKey) {
71
- this.client = new cohereAi.CohereClient({
72
- token: apiKey || process.env.COHERE_API_KEY || ""
73
- });
74
- this.model = model;
75
- }
76
- async getRelevanceScore(query, text) {
77
- const response = await this.client.rerank({
78
- query,
79
- documents: [text],
80
- model: this.model,
81
- topN: 1
82
- });
83
- return response.results[0].relevanceScore;
84
- }
85
- };
86
- var RegisteredLogger = {
87
- AGENT: "AGENT",
88
- LLM: "LLM"};
89
- var LogLevel = {
90
- INFO: "info"};
91
- var Logger = class {
92
- logger;
93
- transports;
94
- constructor(options = {}) {
95
- this.transports = options.transports || {};
96
- const transportsAry = Object.entries(this.transports);
97
- this.logger = pino__default.default({
98
- name: options.name || "app",
99
- level: options.level || LogLevel.INFO,
100
- formatters: {
101
- level: label => {
102
- return {
103
- level: label
104
- };
105
- }
106
- }
107
- }, options.overrideDefaultTransports ? options?.transports?.default : transportsAry.length === 0 ? pretty__default.default({
108
- colorize: true,
109
- levelFirst: true,
110
- ignore: "pid,hostname",
111
- colorizeObjects: true,
112
- translateTime: "SYS:standard",
113
- singleLine: false
114
- }) : pino__default.default.multistream([...transportsAry.map(([_, transport]) => ({
115
- stream: transport,
116
- level: options.level || LogLevel.INFO
117
- })), {
118
- stream: pretty__default.default({
119
- colorize: true,
120
- levelFirst: true,
121
- ignore: "pid,hostname",
122
- colorizeObjects: true,
123
- translateTime: "SYS:standard",
124
- singleLine: false
125
- }),
126
- level: options.level || LogLevel.INFO
127
- }]));
128
- }
129
- debug(message, args = {}) {
130
- this.logger.debug(args, message);
131
- }
132
- info(message, args = {}) {
133
- this.logger.info(args, message);
134
- }
135
- warn(message, args = {}) {
136
- this.logger.warn(args, message);
137
- }
138
- error(message, args = {}) {
139
- this.logger.error(args, message);
140
- }
141
- // Stream creation for process output handling
142
- createStream() {
143
- return new stream.Transform({
144
- transform: (chunk, _encoding, callback) => {
145
- const line = chunk.toString().trim();
146
- if (line) {
147
- this.info(line);
148
- }
149
- callback(null, chunk);
150
- }
151
- });
152
- }
153
- async getLogs(transportId) {
154
- if (!transportId || !this.transports[transportId]) {
155
- return [];
156
- }
157
- return this.transports[transportId].getLogs();
158
- }
159
- async getLogsByRunId({
160
- runId,
161
- transportId
162
- }) {
163
- return this.transports[transportId]?.getLogsByRunId({
164
- runId
165
- });
166
- }
167
- };
168
- function createLogger(options) {
169
- return new Logger(options);
170
- }
171
-
172
- // src/base.ts
173
- var MastraBase = class {
174
- component = RegisteredLogger.LLM;
175
- logger;
176
- name;
177
- telemetry;
178
- constructor({
179
- component,
180
- name
181
- }) {
182
- this.component = component || RegisteredLogger.LLM;
183
- this.name = name;
184
- this.logger = createLogger({
185
- name: `${this.component} - ${this.name}`
186
- });
187
- }
188
- /**
189
- * Set the logger for the agent
190
- * @param logger
191
- */
192
- __setLogger(logger) {
193
- this.logger = logger;
194
- this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);
195
- }
196
- /**
197
- * Set the telemetry for the
198
- * @param telemetry
199
- */
200
- __setTelemetry(telemetry) {
201
- this.telemetry = telemetry;
202
- this.logger.debug(`Telemetry updated [component=${this.component}] [tracer=${this.telemetry.tracer}]`);
203
- }
204
- /**
205
- * Get the telemetry on the vector
206
- * @returns telemetry
207
- */
208
- __getTelemetry() {
209
- return this.telemetry;
210
- }
211
- /*
212
- get experimental_telemetry config
213
- */
214
- get experimental_telemetry() {
215
- return this.telemetry ? {
216
- // tracer: this.telemetry.tracer,
217
- tracer: this.telemetry.getBaggageTracer(),
218
- isEnabled: !!this.telemetry.tracer
219
- } : void 0;
220
- }
221
- };
222
-
223
- // src/hooks/mitt.ts
224
- function mitt(all) {
225
- all = all || /* @__PURE__ */new Map();
226
- return {
227
- /**
228
- * A Map of event names to registered handler functions.
229
- */
230
- all,
231
- /**
232
- * Register an event handler for the given type.
233
- * @param {string|symbol} type Type of event to listen for, or `'*'` for all events
234
- * @param {Function} handler Function to call in response to given event
235
- * @memberOf mitt
236
- */
237
- on(type, handler) {
238
- const handlers = all.get(type);
239
- if (handlers) {
240
- handlers.push(handler);
241
- } else {
242
- all.set(type, [handler]);
243
- }
244
- },
245
- /**
246
- * Remove an event handler for the given type.
247
- * If `handler` is omitted, all handlers of the given type are removed.
248
- * @param {string|symbol} type Type of event to unregister `handler` from (`'*'` to remove a wildcard handler)
249
- * @param {Function} [handler] Handler function to remove
250
- * @memberOf mitt
251
- */
252
- off(type, handler) {
253
- const handlers = all.get(type);
254
- if (handlers) {
255
- if (handler) {
256
- handlers.splice(handlers.indexOf(handler) >>> 0, 1);
257
- } else {
258
- all.set(type, []);
259
- }
260
- }
261
- },
262
- /**
263
- * Invoke all handlers for the given type.
264
- * If present, `'*'` handlers are invoked after type-matched handlers.
265
- *
266
- * Note: Manually firing '*' handlers is not supported.
267
- *
268
- * @param {string|symbol} type The event type to invoke
269
- * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
270
- * @memberOf mitt
271
- */
272
- emit(type, evt) {
273
- let handlers = all.get(type);
274
- if (handlers) {
275
- handlers.slice().map(handler => {
276
- handler(evt);
277
- });
278
- }
279
- handlers = all.get("*");
280
- if (handlers) {
281
- handlers.slice().map(handler => {
282
- handler(type, evt);
283
- });
284
- }
285
- }
286
- };
287
- }
288
-
289
- // src/hooks/index.ts
290
- var hooks = mitt();
291
- function executeHook(hook, data) {
292
- setImmediate(() => {
293
- hooks.emit(hook, data);
294
- });
295
- }
296
-
297
- // src/llm/model/base.ts
298
- var MastraLLMBase = class extends MastraBase {
299
- // @ts-ignore
300
- #mastra;
301
- #model;
302
- constructor({
303
- name,
304
- model
305
- }) {
306
- super({
307
- component: RegisteredLogger.LLM,
308
- name
309
- });
310
- this.#model = model;
311
- }
312
- getProvider() {
313
- return this.#model.provider;
314
- }
315
- getModelId() {
316
- return this.#model.modelId;
317
- }
318
- getModel() {
319
- return this.#model;
320
- }
321
- convertToMessages(messages) {
322
- if (Array.isArray(messages)) {
323
- return messages.map(m => {
324
- if (typeof m === "string") {
325
- return {
326
- role: "user",
327
- content: m
328
- };
329
- }
330
- return m;
331
- });
332
- }
333
- return [{
334
- role: "user",
335
- content: messages
336
- }];
337
- }
338
- __registerPrimitives(p) {
339
- if (p.telemetry) {
340
- this.__setTelemetry(p.telemetry);
341
- }
342
- if (p.logger) {
343
- this.__setLogger(p.logger);
344
- }
345
- this.#mastra = p;
346
- }
347
- async __text(input) {
348
- this.logger.debug(`[LLMs:${this.name}] Generating text.`, {
349
- input
350
- });
351
- throw new Error("Method not implemented.");
352
- }
353
- async __textObject(input) {
354
- this.logger.debug(`[LLMs:${this.name}] Generating object.`, {
355
- input
356
- });
357
- throw new Error("Method not implemented.");
358
- }
359
- async generate(messages, options = {}) {
360
- this.logger.debug(`[LLMs:${this.name}] Generating text.`, {
361
- messages,
362
- options
363
- });
364
- throw new Error("Method not implemented.");
365
- }
366
- async __stream(input) {
367
- this.logger.debug(`[LLMs:${this.name}] Streaming text.`, {
368
- input
369
- });
370
- throw new Error("Method not implemented.");
371
- }
372
- async __streamObject(input) {
373
- this.logger.debug(`[LLMs:${this.name}] Streaming object.`, {
374
- input
375
- });
376
- throw new Error("Method not implemented.");
377
- }
378
- async stream(messages, options = {}) {
379
- this.logger.debug(`[LLMs:${this.name}] Streaming text.`, {
380
- messages,
381
- options
382
- });
383
- throw new Error("Method not implemented.");
384
- }
385
- };
386
-
387
- // src/tools/tool.ts
388
- var Tool = class {
389
- id;
390
- description;
391
- inputSchema;
392
- outputSchema;
393
- execute;
394
- mastra;
395
- constructor(opts) {
396
- this.id = opts.id;
397
- this.description = opts.description;
398
- this.inputSchema = opts.inputSchema;
399
- this.outputSchema = opts.outputSchema;
400
- this.execute = opts.execute;
401
- this.mastra = opts.mastra;
402
- }
403
- };
404
-
405
- // src/utils.ts
406
- var delay = ms => new Promise(resolve => setTimeout(resolve, ms));
407
- function resolveSerializedZodOutput(schema) {
408
- return Function("z", `"use strict";return (${schema});`)(zod.z);
409
- }
410
- function isVercelTool(tool) {
411
- return !(tool instanceof Tool);
412
- }
413
- function createLogMessageOptions({
414
- agentName,
415
- toolName,
416
- tool,
417
- type
418
- }) {
419
- if (!agentName) {
420
- return {
421
- start: `Executing tool ${toolName}`,
422
- error: `Failed tool execution`
423
- };
424
- }
425
- const prefix = `[Agent:${agentName}]`;
426
- const vercelPrefix = isVercelTool(tool) ? "Vercel " : "";
427
- const toolType = type === "toolset" ? "toolset" : "tool";
428
- return {
429
- start: `${prefix} - Executing ${vercelPrefix}${toolType} ${toolName}`,
430
- error: `${prefix} - Failed ${vercelPrefix}${toolType} execution`
431
- };
432
- }
433
- function createExecute(tool, options, logType) {
434
- const {
435
- logger,
436
- ...rest
437
- } = options;
438
- const {
439
- start,
440
- error
441
- } = createLogMessageOptions({
442
- agentName: options.agentName,
443
- toolName: options.name,
444
- tool,
445
- type: logType
446
- });
447
- const execFunction = async (args, execOptions) => {
448
- if (isVercelTool(tool)) {
449
- return tool?.execute?.(args, execOptions) ?? void 0;
450
- }
451
- return tool?.execute?.({
452
- context: args,
453
- threadId: options.threadId,
454
- resourceId: options.resourceId,
455
- mastra: options.mastra,
456
- memory: options.memory,
457
- runId: options.runId
458
- }, execOptions) ?? void 0;
459
- };
460
- return async (args, execOptions) => {
461
- try {
462
- logger.debug(start, {
463
- ...rest,
464
- args
465
- });
466
- return await execFunction(args, execOptions);
467
- } catch (err) {
468
- logger.error(error, {
469
- ...rest,
470
- error: err,
471
- args
472
- });
473
- throw err;
474
- }
475
- };
476
- }
477
- function makeCoreTool(tool, options, logType) {
478
- const getParameters = () => {
479
- if (isVercelTool(tool)) {
480
- return tool.parameters instanceof zod.z.ZodType ? tool.parameters : resolveSerializedZodOutput(jsonSchemaToZod__default.default(tool.parameters));
481
- }
482
- return tool.inputSchema;
483
- };
484
- return {
485
- description: tool.description,
486
- parameters: getParameters(),
487
- execute: tool.execute ? createExecute(tool, {
488
- ...options,
489
- description: tool.description
490
- }, logType) : void 0
491
- };
492
- }
493
- function createMastraProxy({
494
- mastra,
495
- logger
496
- }) {
497
- return new Proxy(mastra, {
498
- get(target, prop) {
499
- if (Reflect.has(target, prop)) {
500
- return Reflect.get(target, prop);
501
- }
502
- if (prop === "logger") {
503
- logger.warn(`Please use 'getLogger' instead, logger is deprecated`);
504
- return Reflect.apply(target.getLogger, target, []);
505
- }
506
- if (prop === "telemetry") {
507
- logger.warn(`Please use 'getTelemetry' instead, telemetry is deprecated`);
508
- return Reflect.apply(target.getTelemetry, target, []);
509
- }
510
- if (prop === "storage") {
511
- logger.warn(`Please use 'getStorage' instead, storage is deprecated`);
512
- return Reflect.get(target, "storage");
513
- }
514
- if (prop === "agents") {
515
- logger.warn(`Please use 'getAgents' instead, agents is deprecated`);
516
- return Reflect.apply(target.getAgents, target, []);
517
- }
518
- if (prop === "tts") {
519
- logger.warn(`Please use 'getTTS' instead, tts is deprecated`);
520
- return Reflect.apply(target.getTTS, target, []);
521
- }
522
- if (prop === "vectors") {
523
- logger.warn(`Please use 'getVectors' instead, vectors is deprecated`);
524
- return Reflect.apply(target.getVectors, target, []);
525
- }
526
- if (prop === "memory") {
527
- logger.warn(`Please use 'getMemory' instead, memory is deprecated`);
528
- return Reflect.get(target, "memory");
529
- }
530
- return Reflect.get(target, prop);
531
- }
532
- });
533
- }
534
-
535
- // src/llm/model/model.ts
536
- var MastraLLM = class extends MastraLLMBase {
537
- #model;
538
- #mastra;
539
- constructor({
540
- model,
541
- mastra
542
- }) {
543
- super({
544
- name: "aisdk",
545
- model
546
- });
547
- this.#model = model;
548
- if (mastra) {
549
- this.#mastra = mastra;
550
- if (mastra.logger) {
551
- this.__setLogger(mastra.logger);
552
- }
553
- }
554
- }
555
- __registerPrimitives(p) {
556
- if (p.telemetry) {
557
- this.__setTelemetry(p.telemetry);
558
- }
559
- if (p.logger) {
560
- this.__setLogger(p.logger);
561
- }
562
- this.#mastra = p;
563
- }
564
- getProvider() {
565
- return this.#model.provider;
566
- }
567
- getModelId() {
568
- return this.#model.modelId;
569
- }
570
- getModel() {
571
- return this.#model;
572
- }
573
- convertTools({
574
- tools,
575
- runId,
576
- threadId,
577
- resourceId,
578
- memory
579
- } = {}) {
580
- this.logger.debug("Starting tool conversion for LLM");
581
- const converted = Object.entries(tools || {}).reduce((memo, value) => {
582
- const k = value[0];
583
- const tool = value[1];
584
- if (tool) {
585
- const options = {
586
- name: k,
587
- runId,
588
- threadId,
589
- resourceId,
590
- logger: this.logger,
591
- memory,
592
- mastra: this.#mastra
593
- };
594
- memo[k] = makeCoreTool(tool, options);
595
- }
596
- return memo;
597
- }, {});
598
- this.logger.debug(`Converted tools for LLM`);
599
- return converted;
600
- }
601
- async __text({
602
- runId,
603
- messages,
604
- maxSteps,
605
- tools,
606
- convertedTools,
607
- temperature,
608
- toolChoice = "auto",
609
- onStepFinish,
610
- experimental_output,
611
- telemetry,
612
- threadId,
613
- resourceId,
614
- memory,
615
- ...rest
616
- }) {
617
- const model = this.#model;
618
- this.logger.debug(`[LLM] - Generating text`, {
619
- runId,
620
- messages,
621
- maxSteps,
622
- threadId,
623
- resourceId,
624
- tools: Object.keys(tools || convertedTools || {})
625
- });
626
- const finalTools = convertedTools || this.convertTools({
627
- tools,
628
- runId,
629
- threadId,
630
- resourceId,
631
- memory
632
- });
633
- const argsForExecute = {
634
- model,
635
- temperature,
636
- tools: {
637
- ...finalTools
638
- },
639
- toolChoice,
640
- maxSteps,
641
- onStepFinish: async props => {
642
- onStepFinish?.(JSON.stringify(props, null, 2));
643
- this.logger.debug("[LLM] - Step Change:", {
644
- text: props?.text,
645
- toolCalls: props?.toolCalls,
646
- toolResults: props?.toolResults,
647
- finishReason: props?.finishReason,
648
- usage: props?.usage,
649
- runId
650
- });
651
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
652
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
653
- runId
654
- });
655
- await delay(10 * 1e3);
656
- }
657
- },
658
- ...rest
659
- };
660
- let schema;
661
- if (experimental_output) {
662
- this.logger.debug("[LLM] - Using experimental output", {
663
- runId
664
- });
665
- if (typeof experimental_output.parse === "function") {
666
- schema = experimental_output;
667
- if (schema instanceof zod.z.ZodArray) {
668
- schema = schema._def.type;
669
- }
670
- } else {
671
- schema = ai.jsonSchema(experimental_output);
672
- }
673
- }
674
- return await ai.generateText({
675
- messages,
676
- ...argsForExecute,
677
- experimental_telemetry: {
678
- ...this.experimental_telemetry,
679
- ...telemetry
680
- },
681
- experimental_output: schema ? ai.Output.object({
682
- schema
683
- }) : void 0
684
- });
685
- }
686
- async __textObject({
687
- messages,
688
- onStepFinish,
689
- maxSteps = 5,
690
- tools,
691
- convertedTools,
692
- structuredOutput,
693
- runId,
694
- temperature,
695
- toolChoice = "auto",
696
- telemetry,
697
- threadId,
698
- resourceId,
699
- memory,
700
- ...rest
701
- }) {
702
- const model = this.#model;
703
- this.logger.debug(`[LLM] - Generating a text object`, {
704
- runId
705
- });
706
- const finalTools = convertedTools || this.convertTools({
707
- tools,
708
- runId,
709
- threadId,
710
- resourceId,
711
- memory
712
- });
713
- const argsForExecute = {
714
- model,
715
- temperature,
716
- tools: {
717
- ...finalTools
718
- },
719
- maxSteps,
720
- toolChoice,
721
- onStepFinish: async props => {
722
- onStepFinish?.(JSON.stringify(props, null, 2));
723
- this.logger.debug("[LLM] - Step Change:", {
724
- text: props?.text,
725
- toolCalls: props?.toolCalls,
726
- toolResults: props?.toolResults,
727
- finishReason: props?.finishReason,
728
- usage: props?.usage,
729
- runId
730
- });
731
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
732
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
733
- runId
734
- });
735
- await delay(10 * 1e3);
736
- }
737
- },
738
- ...rest
739
- };
740
- let schema;
741
- let output = "object";
742
- if (typeof structuredOutput.parse === "function") {
743
- schema = structuredOutput;
744
- if (schema instanceof zod.z.ZodArray) {
745
- output = "array";
746
- schema = schema._def.type;
747
- }
748
- } else {
749
- schema = ai.jsonSchema(structuredOutput);
750
- }
751
- return await ai.generateObject({
752
- messages,
753
- ...argsForExecute,
754
- output,
755
- schema,
756
- experimental_telemetry: {
757
- ...this.experimental_telemetry,
758
- ...telemetry
759
- }
760
- });
761
- }
762
- async __stream({
763
- messages,
764
- onStepFinish,
765
- onFinish,
766
- maxSteps = 5,
767
- tools,
768
- convertedTools,
769
- runId,
770
- temperature,
771
- toolChoice = "auto",
772
- experimental_output,
773
- telemetry,
774
- threadId,
775
- resourceId,
776
- memory,
777
- ...rest
778
- }) {
779
- const model = this.#model;
780
- this.logger.debug(`[LLM] - Streaming text`, {
781
- runId,
782
- threadId,
783
- resourceId,
784
- messages,
785
- maxSteps,
786
- tools: Object.keys(tools || convertedTools || {})
787
- });
788
- const finalTools = convertedTools || this.convertTools({
789
- tools,
790
- runId,
791
- threadId,
792
- resourceId,
793
- memory
794
- });
795
- const argsForExecute = {
796
- model,
797
- temperature,
798
- tools: {
799
- ...finalTools
800
- },
801
- maxSteps,
802
- toolChoice,
803
- onStepFinish: async props => {
804
- onStepFinish?.(JSON.stringify(props, null, 2));
805
- this.logger.debug("[LLM] - Stream Step Change:", {
806
- text: props?.text,
807
- toolCalls: props?.toolCalls,
808
- toolResults: props?.toolResults,
809
- finishReason: props?.finishReason,
810
- usage: props?.usage,
811
- runId
812
- });
813
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
814
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
815
- runId
816
- });
817
- await delay(10 * 1e3);
818
- }
819
- },
820
- onFinish: async props => {
821
- void onFinish?.(JSON.stringify(props, null, 2));
822
- this.logger.debug("[LLM] - Stream Finished:", {
823
- text: props?.text,
824
- toolCalls: props?.toolCalls,
825
- toolResults: props?.toolResults,
826
- finishReason: props?.finishReason,
827
- usage: props?.usage,
828
- runId,
829
- threadId,
830
- resourceId
831
- });
832
- },
833
- ...rest
834
- };
835
- let schema;
836
- if (experimental_output) {
837
- this.logger.debug("[LLM] - Using experimental output", {
838
- runId
839
- });
840
- if (typeof experimental_output.parse === "function") {
841
- schema = experimental_output;
842
- if (schema instanceof zod.z.ZodArray) {
843
- schema = schema._def.type;
844
- }
845
- } else {
846
- schema = ai.jsonSchema(experimental_output);
847
- }
848
- }
849
- return await ai.streamText({
850
- messages,
851
- ...argsForExecute,
852
- experimental_telemetry: {
853
- ...this.experimental_telemetry,
854
- ...telemetry
855
- },
856
- experimental_output: schema ? ai.Output.object({
857
- schema
858
- }) : void 0
859
- });
860
- }
861
- async __streamObject({
862
- messages,
863
- onStepFinish,
864
- onFinish,
865
- maxSteps = 5,
866
- tools,
867
- convertedTools,
868
- structuredOutput,
869
- runId,
870
- temperature,
871
- toolChoice = "auto",
872
- telemetry,
873
- threadId,
874
- resourceId,
875
- memory,
876
- ...rest
877
- }) {
878
- const model = this.#model;
879
- this.logger.debug(`[LLM] - Streaming structured output`, {
880
- runId,
881
- messages,
882
- maxSteps,
883
- tools: Object.keys(tools || convertedTools || {})
884
- });
885
- const finalTools = convertedTools || this.convertTools({
886
- tools,
887
- runId,
888
- threadId,
889
- resourceId,
890
- memory
891
- });
892
- const argsForExecute = {
893
- model,
894
- temperature,
895
- tools: {
896
- ...finalTools
897
- },
898
- maxSteps,
899
- toolChoice,
900
- onStepFinish: async props => {
901
- onStepFinish?.(JSON.stringify(props, null, 2));
902
- this.logger.debug("[LLM] - Stream Step Change:", {
903
- text: props?.text,
904
- toolCalls: props?.toolCalls,
905
- toolResults: props?.toolResults,
906
- finishReason: props?.finishReason,
907
- usage: props?.usage,
908
- runId,
909
- threadId,
910
- resourceId
911
- });
912
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
913
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
914
- runId
915
- });
916
- await delay(10 * 1e3);
917
- }
918
- },
919
- onFinish: async props => {
920
- void onFinish?.(JSON.stringify(props, null, 2));
921
- this.logger.debug("[LLM] - Stream Finished:", {
922
- text: props?.text,
923
- toolCalls: props?.toolCalls,
924
- toolResults: props?.toolResults,
925
- finishReason: props?.finishReason,
926
- usage: props?.usage,
927
- runId,
928
- threadId,
929
- resourceId
930
- });
931
- },
932
- ...rest
933
- };
934
- let schema;
935
- let output = "object";
936
- if (typeof structuredOutput.parse === "function") {
937
- schema = structuredOutput;
938
- if (schema instanceof zod.z.ZodArray) {
939
- output = "array";
940
- schema = schema._def.type;
941
- }
942
- } else {
943
- schema = ai.jsonSchema(structuredOutput);
944
- }
945
- return ai.streamObject({
946
- messages,
947
- ...argsForExecute,
948
- output,
949
- schema,
950
- experimental_telemetry: {
951
- ...this.experimental_telemetry,
952
- ...telemetry
953
- }
954
- });
955
- }
956
- async generate(messages, {
957
- maxSteps = 5,
958
- onStepFinish,
959
- tools,
960
- convertedTools,
961
- runId,
962
- output,
963
- temperature,
964
- telemetry,
965
- memory,
966
- ...rest
967
- } = {}) {
968
- const msgs = this.convertToMessages(messages);
969
- if (!output) {
970
- return await this.__text({
971
- messages: msgs,
972
- onStepFinish,
973
- maxSteps,
974
- tools,
975
- convertedTools,
976
- runId,
977
- temperature,
978
- memory,
979
- ...rest
980
- });
981
- }
982
- return await this.__textObject({
983
- messages: msgs,
984
- structuredOutput: output,
985
- onStepFinish,
986
- maxSteps,
987
- tools,
988
- convertedTools,
989
- runId,
990
- telemetry,
991
- memory,
992
- ...rest
993
- });
994
- }
995
- async stream(messages, {
996
- maxSteps = 5,
997
- onFinish,
998
- onStepFinish,
999
- tools,
1000
- convertedTools,
1001
- runId,
1002
- output,
1003
- temperature,
1004
- telemetry,
1005
- ...rest
1006
- } = {}) {
1007
- const msgs = this.convertToMessages(messages);
1008
- if (!output) {
1009
- return await this.__stream({
1010
- messages: msgs,
1011
- onStepFinish,
1012
- onFinish,
1013
- maxSteps,
1014
- tools,
1015
- convertedTools,
1016
- runId,
1017
- temperature,
1018
- telemetry,
1019
- ...rest
1020
- });
1021
- }
1022
- return await this.__streamObject({
1023
- messages: msgs,
1024
- structuredOutput: output,
1025
- onStepFinish,
1026
- onFinish,
1027
- maxSteps,
1028
- tools,
1029
- convertedTools,
1030
- runId,
1031
- temperature,
1032
- telemetry,
1033
- ...rest
1034
- });
1035
- }
1036
- };
1037
- function hasActiveTelemetry(tracerName = "default-tracer") {
1038
- try {
1039
- return !!api.trace.getTracer(tracerName);
1040
- } catch {
1041
- return false;
1042
- }
1043
- }
1044
-
1045
- // src/telemetry/telemetry.decorators.ts
1046
- function withSpan(options) {
1047
- return function (_target, propertyKey, descriptor) {
1048
- if (!descriptor || typeof descriptor === "number") return;
1049
- const originalMethod = descriptor.value;
1050
- const methodName = String(propertyKey);
1051
- descriptor.value = function (...args) {
1052
- if (options?.skipIfNoTelemetry && !hasActiveTelemetry(options?.tracerName)) {
1053
- return originalMethod.apply(this, args);
1054
- }
1055
- const tracer = api.trace.getTracer(options?.tracerName ?? "default-tracer");
1056
- let spanName;
1057
- let spanKind;
1058
- if (typeof options === "string") {
1059
- spanName = options;
1060
- } else if (options) {
1061
- spanName = options.spanName || methodName;
1062
- spanKind = options.spanKind;
1063
- } else {
1064
- spanName = methodName;
1065
- }
1066
- const span = tracer.startSpan(spanName, {
1067
- kind: spanKind
1068
- });
1069
- let ctx = api.trace.setSpan(api.context.active(), span);
1070
- args.forEach((arg, index) => {
1071
- try {
1072
- span.setAttribute(`${spanName}.argument.${index}`, JSON.stringify(arg));
1073
- } catch {
1074
- span.setAttribute(`${spanName}.argument.${index}`, "[Not Serializable]");
1075
- }
1076
- });
1077
- const currentBaggage = api.propagation.getBaggage(ctx);
1078
- if (currentBaggage?.componentName) {
1079
- span.setAttribute("componentName", currentBaggage?.componentName);
1080
- span.setAttribute("runId", currentBaggage?.runId);
1081
- } else if (this && this.name) {
1082
- span.setAttribute("componentName", this.name);
1083
- span.setAttribute("runId", this.runId);
1084
- ctx = api.propagation.setBaggage(ctx, {
1085
- componentName: this.name,
1086
- runId: this.runId
1087
- });
1088
- }
1089
- let result;
1090
- try {
1091
- result = api.context.with(ctx, () => originalMethod.apply(this, args));
1092
- if (result instanceof Promise) {
1093
- return result.then(resolvedValue => {
1094
- try {
1095
- span.setAttribute(`${spanName}.result`, JSON.stringify(resolvedValue));
1096
- } catch {
1097
- span.setAttribute(`${spanName}.result`, "[Not Serializable]");
1098
- }
1099
- return resolvedValue;
1100
- }).finally(() => span.end());
1101
- }
1102
- try {
1103
- span.setAttribute(`${spanName}.result`, JSON.stringify(result));
1104
- } catch {
1105
- span.setAttribute(`${spanName}.result`, "[Not Serializable]");
1106
- }
1107
- return result;
1108
- } catch (error) {
1109
- span.setStatus({
1110
- code: api.SpanStatusCode.ERROR,
1111
- message: error instanceof Error ? error.message : "Unknown error"
1112
- });
1113
- if (error instanceof Error) {
1114
- span.recordException(error);
1115
- }
1116
- throw error;
1117
- } finally {
1118
- if (!(result instanceof Promise)) {
1119
- span.end();
1120
- }
1121
- }
1122
- };
1123
- return descriptor;
1124
- };
1125
- }
1126
- function InstrumentClass(options) {
1127
- return function (target) {
1128
- const methods = Object.getOwnPropertyNames(target.prototype);
1129
- methods.forEach(method => {
1130
- if (options?.excludeMethods?.includes(method) || method === "constructor") return;
1131
- if (options?.methodFilter && !options.methodFilter(method)) return;
1132
- const descriptor = Object.getOwnPropertyDescriptor(target.prototype, method);
1133
- if (descriptor && typeof descriptor.value === "function") {
1134
- Object.defineProperty(target.prototype, method, withSpan({
1135
- spanName: options?.prefix ? `${options.prefix}.${method}` : method,
1136
- skipIfNoTelemetry: true,
1137
- spanKind: options?.spanKind || api.SpanKind.INTERNAL,
1138
- tracerName: options?.tracerName
1139
- })(target, method, descriptor));
1140
- }
1141
- });
1142
- return target;
1143
- };
1144
- }
1145
-
1146
- // src/agent/index.ts
1147
- var _Agent_decorators, _init, _a;
1148
- _Agent_decorators = [InstrumentClass({
1149
- prefix: "agent",
1150
- excludeMethods: ["__setTools", "__setLogger", "__setTelemetry", "log"]
1151
- })];
1152
- var Agent = class extends (_a = MastraBase) {
1153
- name;
1154
- llm;
1155
- instructions;
1156
- model;
1157
- #mastra;
1158
- #memory;
1159
- tools;
1160
- /** @deprecated This property is deprecated. Use evals instead. */
1161
- metrics;
1162
- evals;
1163
- voice;
1164
- constructor(config) {
1165
- super({
1166
- component: RegisteredLogger.AGENT
1167
- });
1168
- this.name = config.name;
1169
- this.instructions = config.instructions;
1170
- if (!config.model) {
1171
- throw new Error(`LanguageModel is required to create an Agent. Please provide the 'model'.`);
1172
- }
1173
- this.llm = new MastraLLM({
1174
- model: config.model
1175
- });
1176
- this.tools = {};
1177
- this.metrics = {};
1178
- this.evals = {};
1179
- if (config.tools) {
1180
- this.tools = config.tools;
1181
- }
1182
- if (config.mastra) {
1183
- this.__registerPrimitives({
1184
- telemetry: config.mastra.getTelemetry(),
1185
- logger: config.mastra.getLogger()
1186
- });
1187
- }
1188
- if (config.metrics) {
1189
- this.logger.warn("The metrics property is deprecated. Please use evals instead to add evaluation metrics.");
1190
- this.metrics = config.metrics;
1191
- this.evals = config.metrics;
1192
- }
1193
- if (config.evals) {
1194
- this.evals = config.evals;
1195
- }
1196
- if (config.memory) {
1197
- this.#memory = config.memory;
1198
- }
1199
- if (config.voice) {
1200
- this.voice = config.voice;
1201
- }
1202
- }
1203
- hasOwnMemory() {
1204
- return Boolean(this.#memory);
1205
- }
1206
- getMemory() {
1207
- return this.#memory ?? this.#mastra?.memory;
1208
- }
1209
- __updateInstructions(newInstructions) {
1210
- this.instructions = newInstructions;
1211
- this.logger.debug(`[Agents:${this.name}] Instructions updated.`, {
1212
- model: this.model,
1213
- name: this.name
1214
- });
1215
- }
1216
- __registerPrimitives(p) {
1217
- if (p.telemetry) {
1218
- this.__setTelemetry(p.telemetry);
1219
- }
1220
- if (p.logger) {
1221
- this.__setLogger(p.logger);
1222
- }
1223
- this.llm.__registerPrimitives(p);
1224
- this.logger.debug(`[Agents:${this.name}] initialized.`, {
1225
- model: this.model,
1226
- name: this.name
1227
- });
1228
- }
1229
- __registerMastra(mastra) {
1230
- this.#mastra = mastra;
1231
- }
1232
- /**
1233
- * Set the concrete tools for the agent
1234
- * @param tools
1235
- */
1236
- __setTools(tools) {
1237
- this.tools = tools;
1238
- this.logger.debug(`[Agents:${this.name}] Tools set for agent ${this.name}`, {
1239
- model: this.model,
1240
- name: this.name
1241
- });
1242
- }
1243
- async generateTitleFromUserMessage({
1244
- message
1245
- }) {
1246
- const {
1247
- text
1248
- } = await this.llm.__text({
1249
- messages: [{
1250
- role: "system",
1251
- content: `
1252
-
1253
- - you will generate a short title based on the first message a user begins a conversation with
1254
- - ensure it is not more than 80 characters long
1255
- - the title should be a summary of the user's message
1256
- - do not use quotes or colons
1257
- - the entire text you return will be used as the title`
1258
- }, {
1259
- role: "user",
1260
- content: JSON.stringify(message)
1261
- }]
1262
- });
1263
- const cleanedText = text.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
1264
- return cleanedText;
1265
- }
1266
- getMostRecentUserMessage(messages) {
1267
- const userMessages = messages.filter(message => message.role === "user");
1268
- return userMessages.at(-1);
1269
- }
1270
- async genTitle(userMessage) {
1271
- let title = `New Thread ${(/* @__PURE__ */new Date()).toISOString()}`;
1272
- try {
1273
- if (userMessage) {
1274
- title = await this.generateTitleFromUserMessage({
1275
- message: userMessage
1276
- });
1277
- }
1278
- } catch (e) {
1279
- console.error("Error generating title:", e);
1280
- }
1281
- return title;
1282
- }
1283
- async saveMemory({
1284
- threadId,
1285
- memoryConfig,
1286
- resourceId,
1287
- userMessages,
1288
- runId
1289
- }) {
1290
- const userMessage = this.getMostRecentUserMessage(userMessages);
1291
- const memory = this.getMemory();
1292
- if (memory) {
1293
- const config = memory.getMergedThreadConfig(memoryConfig);
1294
- let thread;
1295
- if (!threadId) {
1296
- this.logger.debug(`No threadId, creating new thread for agent ${this.name}`, {
1297
- runId: runId || this.name
1298
- });
1299
- const title = config?.threads?.generateTitle ? await this.genTitle(userMessage) : void 0;
1300
- thread = await memory.createThread({
1301
- threadId,
1302
- resourceId,
1303
- memoryConfig,
1304
- title
1305
- });
1306
- } else {
1307
- thread = await memory.getThreadById({
1308
- threadId
1309
- });
1310
- if (!thread) {
1311
- this.logger.debug(`Thread with id ${threadId} not found, creating new thread for agent ${this.name}`, {
1312
- runId: runId || this.name
1313
- });
1314
- const title = config?.threads?.generateTitle ? await this.genTitle(userMessage) : void 0;
1315
- thread = await memory.createThread({
1316
- threadId,
1317
- resourceId,
1318
- title,
1319
- memoryConfig
1320
- });
1321
- }
1322
- }
1323
- const newMessages = userMessage ? [userMessage] : userMessages;
1324
- if (thread) {
1325
- const messages = newMessages.map(u => {
1326
- return {
1327
- id: this.getMemory()?.generateId(),
1328
- createdAt: /* @__PURE__ */new Date(),
1329
- threadId: thread.id,
1330
- ...u,
1331
- content: u.content,
1332
- role: u.role,
1333
- type: "text"
1334
- };
1335
- });
1336
- const memoryMessages = threadId && memory ? (await memory.rememberMessages({
1337
- threadId,
1338
- config: memoryConfig,
1339
- vectorMessageSearch: messages.slice(-1).map(m => {
1340
- if (typeof m === `string`) {
1341
- return m;
1342
- }
1343
- return m?.content || ``;
1344
- }).join(`
1345
- `)
1346
- })).messages : [];
1347
- if (memory) {
1348
- await memory.saveMessages({
1349
- messages,
1350
- memoryConfig
1351
- });
1352
- }
1353
- this.logger.debug("Saved messages to memory", {
1354
- threadId: thread.id,
1355
- runId
1356
- });
1357
- const memorySystemMessage = memory && threadId ? await memory.getSystemMessage({
1358
- threadId,
1359
- memoryConfig
1360
- }) : null;
1361
- return {
1362
- threadId: thread.id,
1363
- messages: [memorySystemMessage ? {
1364
- role: "system",
1365
- content: memorySystemMessage
1366
- } : null, ...this.sanitizeResponseMessages(memoryMessages), ...newMessages].filter(message => Boolean(message))
1367
- };
1368
- }
1369
- return {
1370
- threadId: thread?.id || threadId || "",
1371
- messages: userMessages
1372
- };
1373
- }
1374
- return {
1375
- threadId: threadId || "",
1376
- messages: userMessages
1377
- };
1378
- }
1379
- async saveResponse({
1380
- result,
1381
- threadId,
1382
- resourceId,
1383
- runId,
1384
- memoryConfig
1385
- }) {
1386
- const {
1387
- response
1388
- } = result;
1389
- try {
1390
- if (response.messages) {
1391
- const ms = Array.isArray(response.messages) ? response.messages : [response.messages];
1392
- const responseMessagesWithoutIncompleteToolCalls = this.sanitizeResponseMessages(ms);
1393
- const memory = this.getMemory();
1394
- if (memory) {
1395
- this.logger.debug(`[Agent:${this.name}] - Memory persistence: store=${this.getMemory()?.constructor.name} threadId=${threadId}`, {
1396
- runId,
1397
- resourceId,
1398
- threadId,
1399
- memoryStore: this.getMemory()?.constructor.name
1400
- });
1401
- await memory.saveMessages({
1402
- memoryConfig,
1403
- messages: responseMessagesWithoutIncompleteToolCalls.map((message, index) => {
1404
- const messageId = crypto$1.randomUUID();
1405
- let toolCallIds;
1406
- let toolCallArgs;
1407
- let toolNames;
1408
- let type = "text";
1409
- if (message.role === "tool") {
1410
- toolCallIds = message.content.map(content => content.toolCallId);
1411
- type = "tool-result";
1412
- }
1413
- if (message.role === "assistant") {
1414
- const assistantContent = message.content;
1415
- const assistantToolCalls = assistantContent.map(content => {
1416
- if (content.type === "tool-call") {
1417
- return {
1418
- toolCallId: content.toolCallId,
1419
- toolArgs: content.args,
1420
- toolName: content.toolName
1421
- };
1422
- }
1423
- return void 0;
1424
- })?.filter(Boolean);
1425
- toolCallIds = assistantToolCalls?.map(toolCall => toolCall.toolCallId);
1426
- toolCallArgs = assistantToolCalls?.map(toolCall => toolCall.toolArgs);
1427
- toolNames = assistantToolCalls?.map(toolCall => toolCall.toolName);
1428
- type = assistantContent?.[0]?.type;
1429
- }
1430
- return {
1431
- id: messageId,
1432
- threadId,
1433
- role: message.role,
1434
- content: message.content,
1435
- createdAt: new Date(Date.now() + index),
1436
- // use Date.now() + index to make sure every message is atleast one millisecond apart
1437
- toolCallIds: toolCallIds?.length ? toolCallIds : void 0,
1438
- toolCallArgs: toolCallArgs?.length ? toolCallArgs : void 0,
1439
- toolNames: toolNames?.length ? toolNames : void 0,
1440
- type
1441
- };
1442
- })
1443
- });
1444
- }
1445
- }
1446
- } catch (err) {
1447
- this.logger.error(`[Agent:${this.name}] - Failed to save assistant response`, {
1448
- error: err,
1449
- runId
1450
- });
1451
- }
1452
- }
1453
- sanitizeResponseMessages(messages) {
1454
- let toolResultIds = [];
1455
- let toolCallIds = [];
1456
- for (const message of messages) {
1457
- if (!Array.isArray(message.content)) continue;
1458
- if (message.role === "tool") {
1459
- for (const content of message.content) {
1460
- if (content.type === "tool-result") {
1461
- toolResultIds.push(content.toolCallId);
1462
- }
1463
- }
1464
- } else if (message.role === "assistant" || message.role === "user") {
1465
- for (const content of message.content) {
1466
- if (typeof content !== `string`) {
1467
- if (content.type === `tool-call`) {
1468
- toolCallIds.push(content.toolCallId);
1469
- }
1470
- }
1471
- }
1472
- }
1473
- }
1474
- const messagesBySanitizedContent = messages.map(message => {
1475
- if (message.role !== "assistant" && message.role !== `tool` && message.role !== `user`) return message;
1476
- if (!message.content || typeof message.content === "string" || typeof message.content === "number") {
1477
- return message;
1478
- }
1479
- const sanitizedContent = message.content.filter(content => {
1480
- if (content.type === `tool-call`) {
1481
- return toolResultIds.includes(content.toolCallId);
1482
- }
1483
- if (content.type === `text`) {
1484
- return content.text.trim() !== ``;
1485
- }
1486
- if (content.type === `tool-result`) {
1487
- return toolCallIds.includes(content.toolCallId);
1488
- }
1489
- return true;
1490
- });
1491
- return {
1492
- ...message,
1493
- content: sanitizedContent
1494
- };
1495
- });
1496
- return messagesBySanitizedContent.filter(message => {
1497
- if (typeof message.content === `string`) {
1498
- return message.content !== "";
1499
- }
1500
- if (Array.isArray(message.content)) {
1501
- return message.content.length && message.content.every(c => {
1502
- if (c.type === `text`) {
1503
- return c.text && c.text !== "";
1504
- }
1505
- return true;
1506
- });
1507
- }
1508
- return true;
1509
- });
1510
- }
1511
- convertTools({
1512
- toolsets,
1513
- threadId,
1514
- resourceId,
1515
- runId
1516
- }) {
1517
- this.logger.debug(`[Agents:${this.name}] - Assigning tools`, {
1518
- runId,
1519
- threadId,
1520
- resourceId
1521
- });
1522
- const memory = this.getMemory();
1523
- const memoryTools = memory?.getTools?.();
1524
- let mastraProxy = void 0;
1525
- const logger = this.logger;
1526
- if (this.#mastra) {
1527
- mastraProxy = createMastraProxy({
1528
- mastra: this.#mastra,
1529
- logger
1530
- });
1531
- }
1532
- const converted = Object.entries(this.tools || {}).reduce((memo, value) => {
1533
- const k = value[0];
1534
- const tool = this.tools[k];
1535
- if (tool) {
1536
- const options = {
1537
- name: k,
1538
- runId,
1539
- threadId,
1540
- resourceId,
1541
- logger: this.logger,
1542
- mastra: mastraProxy,
1543
- memory,
1544
- agentName: this.name
1545
- };
1546
- memo[k] = makeCoreTool(tool, options);
1547
- }
1548
- return memo;
1549
- }, {});
1550
- const convertedMemoryTools = memoryTools ? Object.entries(memoryTools).reduce((memo, [k, tool]) => {
1551
- memo[k] = {
1552
- description: tool.description,
1553
- parameters: tool.parameters,
1554
- execute: typeof tool?.execute === "function" ? async (args, options) => {
1555
- try {
1556
- this.logger.debug(`[Agent:${this.name}] - Executing memory tool ${k}`, {
1557
- name: k,
1558
- description: tool.description,
1559
- args,
1560
- runId,
1561
- threadId,
1562
- resourceId
1563
- });
1564
- return tool?.execute?.({
1565
- context: args,
1566
- mastra: mastraProxy,
1567
- memory,
1568
- runId,
1569
- threadId,
1570
- resourceId
1571
- }, options) ?? void 0;
1572
- } catch (err) {
1573
- this.logger.error(`[Agent:${this.name}] - Failed memory tool execution`, {
1574
- error: err,
1575
- runId,
1576
- threadId,
1577
- resourceId
1578
- });
1579
- throw err;
1580
- }
1581
- } : void 0
1582
- };
1583
- return memo;
1584
- }, {}) : {};
1585
- const toolsFromToolsetsConverted = {
1586
- ...converted,
1587
- ...convertedMemoryTools
1588
- };
1589
- const toolsFromToolsets = Object.values(toolsets || {});
1590
- if (toolsFromToolsets.length > 0) {
1591
- this.logger.debug(`[Agent:${this.name}] - Adding tools from toolsets ${Object.keys(toolsets || {}).join(", ")}`, {
1592
- runId
1593
- });
1594
- toolsFromToolsets.forEach(toolset => {
1595
- Object.entries(toolset).forEach(([toolName, tool]) => {
1596
- const toolObj = tool;
1597
- const options = {
1598
- name: toolName,
1599
- runId,
1600
- threadId,
1601
- resourceId,
1602
- logger: this.logger,
1603
- agentName: this.name
1604
- };
1605
- toolsFromToolsetsConverted[toolName] = makeCoreTool(toolObj, options, "toolset");
1606
- });
1607
- });
1608
- }
1609
- return toolsFromToolsetsConverted;
1610
- }
1611
- async preExecute({
1612
- resourceId,
1613
- runId,
1614
- threadId,
1615
- memoryConfig,
1616
- messages
1617
- }) {
1618
- let coreMessages = [];
1619
- let threadIdToUse = threadId;
1620
- this.logger.debug(`Saving user messages in memory for agent ${this.name}`, {
1621
- runId
1622
- });
1623
- const saveMessageResponse = await this.saveMemory({
1624
- threadId,
1625
- resourceId,
1626
- userMessages: messages,
1627
- memoryConfig
1628
- });
1629
- coreMessages = saveMessageResponse.messages;
1630
- threadIdToUse = saveMessageResponse.threadId;
1631
- return {
1632
- coreMessages,
1633
- threadIdToUse
1634
- };
1635
- }
1636
- __primitive({
1637
- messages,
1638
- context: context2,
1639
- threadId,
1640
- memoryConfig,
1641
- resourceId,
1642
- runId,
1643
- toolsets
1644
- }) {
1645
- return {
1646
- before: async () => {
1647
- if (process.env.NODE_ENV !== "test") {
1648
- this.logger.debug(`[Agents:${this.name}] - Starting generation`, {
1649
- runId
1650
- });
1651
- }
1652
- const systemMessage = {
1653
- role: "system",
1654
- content: `${this.instructions}.`
1655
- };
1656
- let coreMessages = messages;
1657
- let threadIdToUse = threadId;
1658
- const memory = this.getMemory();
1659
- if (threadId && memory && !resourceId) {
1660
- throw new Error(`A resourceId must be provided when passing a threadId and using Memory. Saw threadId ${threadId} but resourceId is ${resourceId}`);
1661
- }
1662
- if (memory && resourceId) {
1663
- this.logger.debug(`[Agent:${this.name}] - Memory persistence enabled: store=${this.getMemory()?.constructor.name}, resourceId=${resourceId}`, {
1664
- runId,
1665
- resourceId,
1666
- threadId: threadIdToUse,
1667
- memoryStore: this.getMemory()?.constructor.name
1668
- });
1669
- const preExecuteResult = await this.preExecute({
1670
- resourceId,
1671
- runId,
1672
- threadId: threadIdToUse,
1673
- memoryConfig,
1674
- messages
1675
- });
1676
- coreMessages = preExecuteResult.coreMessages;
1677
- threadIdToUse = preExecuteResult.threadIdToUse;
1678
- }
1679
- let convertedTools;
1680
- if (toolsets && Object.keys(toolsets || {}).length > 0 || this.getMemory() && resourceId) {
1681
- const reasons = [];
1682
- if (toolsets && Object.keys(toolsets || {}).length > 0) {
1683
- reasons.push(`toolsets present (${Object.keys(toolsets || {}).length} tools)`);
1684
- }
1685
- if (this.getMemory() && resourceId) {
1686
- reasons.push("memory and resourceId available");
1687
- }
1688
- this.logger.debug(`[Agent:${this.name}] - Enhancing tools: ${reasons.join(", ")}`, {
1689
- runId,
1690
- toolsets: toolsets ? Object.keys(toolsets) : void 0,
1691
- hasMemory: !!this.getMemory(),
1692
- hasResourceId: !!resourceId
1693
- });
1694
- convertedTools = this.convertTools({
1695
- toolsets,
1696
- threadId: threadIdToUse,
1697
- resourceId,
1698
- runId
1699
- });
1700
- }
1701
- const messageObjects = [systemMessage, ...(context2 || []), ...coreMessages];
1702
- return {
1703
- messageObjects,
1704
- convertedTools,
1705
- threadId: threadIdToUse
1706
- };
1707
- },
1708
- after: async ({
1709
- result,
1710
- threadId: threadId2,
1711
- memoryConfig: memoryConfig2,
1712
- outputText,
1713
- runId: runId2
1714
- }) => {
1715
- const resToLog = {
1716
- text: result?.text,
1717
- object: result?.object,
1718
- toolResults: result?.toolResults,
1719
- toolCalls: result?.toolCalls,
1720
- usage: result?.usage,
1721
- steps: result?.steps?.map(s => {
1722
- return {
1723
- stepType: s?.stepType,
1724
- text: result?.text,
1725
- object: result?.object,
1726
- toolResults: result?.toolResults,
1727
- toolCalls: result?.toolCalls,
1728
- usage: result?.usage
1729
- };
1730
- })
1731
- };
1732
- this.logger.debug(`[Agent:${this.name}] - Post processing LLM response`, {
1733
- runId: runId2,
1734
- result: resToLog,
1735
- threadId: threadId2
1736
- });
1737
- if (this.getMemory() && resourceId) {
1738
- try {
1739
- await this.saveResponse({
1740
- result,
1741
- threadId: threadId2,
1742
- resourceId,
1743
- memoryConfig: memoryConfig2,
1744
- runId: runId2
1745
- });
1746
- } catch (e) {
1747
- this.logger.error("Error saving response", {
1748
- error: e,
1749
- runId: runId2,
1750
- result: resToLog,
1751
- threadId: threadId2
1752
- });
1753
- }
1754
- }
1755
- if (Object.keys(this.evals || {}).length > 0) {
1756
- const input = messages.map(message => message.content).join("\n");
1757
- const runIdToUse = runId2 || crypto.randomUUID();
1758
- for (const metric of Object.values(this.evals || {})) {
1759
- executeHook("onGeneration" /* ON_GENERATION */, {
1760
- input,
1761
- output: outputText,
1762
- runId: runIdToUse,
1763
- metric,
1764
- agentName: this.name,
1765
- instructions: this.instructions
1766
- });
1767
- }
1768
- }
1769
- }
1770
- };
1771
- }
1772
- async generate(messages, {
1773
- context: context2,
1774
- threadId: threadIdInFn,
1775
- memoryOptions,
1776
- resourceId,
1777
- maxSteps = 5,
1778
- onStepFinish,
1779
- runId,
1780
- output,
1781
- toolsets,
1782
- temperature,
1783
- toolChoice = "auto",
1784
- experimental_output,
1785
- telemetry,
1786
- ...rest
1787
- } = {}) {
1788
- let messagesToUse = [];
1789
- if (typeof messages === `string`) {
1790
- messagesToUse = [{
1791
- role: "user",
1792
- content: messages
1793
- }];
1794
- } else {
1795
- messagesToUse = messages.map(message => {
1796
- if (typeof message === `string`) {
1797
- return {
1798
- role: "user",
1799
- content: message
1800
- };
1801
- }
1802
- return message;
1803
- });
1804
- }
1805
- const runIdToUse = runId || crypto$1.randomUUID();
1806
- const {
1807
- before,
1808
- after
1809
- } = this.__primitive({
1810
- messages: messagesToUse,
1811
- context: context2,
1812
- threadId: threadIdInFn,
1813
- memoryConfig: memoryOptions,
1814
- resourceId,
1815
- runId: runIdToUse,
1816
- toolsets
1817
- });
1818
- const {
1819
- threadId,
1820
- messageObjects,
1821
- convertedTools
1822
- } = await before();
1823
- if (!output && experimental_output) {
1824
- const result2 = await this.llm.__text({
1825
- messages: messageObjects,
1826
- tools: this.tools,
1827
- convertedTools,
1828
- onStepFinish,
1829
- maxSteps: maxSteps || 5,
1830
- runId: runIdToUse,
1831
- temperature,
1832
- toolChoice: toolChoice || "auto",
1833
- experimental_output,
1834
- threadId,
1835
- resourceId,
1836
- memory: this.getMemory(),
1837
- ...rest
1838
- });
1839
- const outputText2 = result2.text;
1840
- await after({
1841
- result: result2,
1842
- threadId,
1843
- memoryConfig: memoryOptions,
1844
- outputText: outputText2,
1845
- runId: runIdToUse
1846
- });
1847
- const newResult = result2;
1848
- newResult.object = result2.experimental_output;
1849
- return newResult;
1850
- }
1851
- if (!output) {
1852
- const result2 = await this.llm.__text({
1853
- messages: messageObjects,
1854
- tools: this.tools,
1855
- convertedTools,
1856
- onStepFinish,
1857
- maxSteps,
1858
- runId: runIdToUse,
1859
- temperature,
1860
- toolChoice,
1861
- telemetry,
1862
- threadId,
1863
- resourceId,
1864
- memory: this.getMemory(),
1865
- ...rest
1866
- });
1867
- const outputText2 = result2.text;
1868
- await after({
1869
- result: result2,
1870
- threadId,
1871
- memoryConfig: memoryOptions,
1872
- outputText: outputText2,
1873
- runId: runIdToUse
1874
- });
1875
- return result2;
1876
- }
1877
- const result = await this.llm.__textObject({
1878
- messages: messageObjects,
1879
- tools: this.tools,
1880
- structuredOutput: output,
1881
- convertedTools,
1882
- onStepFinish,
1883
- maxSteps,
1884
- runId: runIdToUse,
1885
- temperature,
1886
- toolChoice,
1887
- telemetry,
1888
- memory: this.getMemory(),
1889
- ...rest
1890
- });
1891
- const outputText = JSON.stringify(result.object);
1892
- await after({
1893
- result,
1894
- threadId,
1895
- memoryConfig: memoryOptions,
1896
- outputText,
1897
- runId: runIdToUse
1898
- });
1899
- return result;
1900
- }
1901
- async stream(messages, {
1902
- context: context2,
1903
- threadId: threadIdInFn,
1904
- memoryOptions,
1905
- resourceId,
1906
- maxSteps = 5,
1907
- onFinish,
1908
- onStepFinish,
1909
- runId,
1910
- toolsets,
1911
- output,
1912
- temperature,
1913
- toolChoice = "auto",
1914
- experimental_output,
1915
- telemetry,
1916
- ...rest
1917
- } = {}) {
1918
- const runIdToUse = runId || crypto$1.randomUUID();
1919
- let messagesToUse = [];
1920
- if (typeof messages === `string`) {
1921
- messagesToUse = [{
1922
- role: "user",
1923
- content: messages
1924
- }];
1925
- } else {
1926
- messagesToUse = messages.map(message => {
1927
- if (typeof message === `string`) {
1928
- return {
1929
- role: "user",
1930
- content: message
1931
- };
1932
- }
1933
- return message;
1934
- });
1935
- }
1936
- const {
1937
- before,
1938
- after
1939
- } = this.__primitive({
1940
- messages: messagesToUse,
1941
- context: context2,
1942
- threadId: threadIdInFn,
1943
- memoryConfig: memoryOptions,
1944
- resourceId,
1945
- runId: runIdToUse,
1946
- toolsets
1947
- });
1948
- const {
1949
- threadId,
1950
- messageObjects,
1951
- convertedTools
1952
- } = await before();
1953
- if (!output && experimental_output) {
1954
- this.logger.debug(`Starting agent ${this.name} llm stream call`, {
1955
- runId
1956
- });
1957
- const streamResult = await this.llm.__stream({
1958
- messages: messageObjects,
1959
- temperature,
1960
- tools: this.tools,
1961
- convertedTools,
1962
- onStepFinish,
1963
- onFinish: async result => {
1964
- try {
1965
- const res = JSON.parse(result) || {};
1966
- const outputText = res.text;
1967
- await after({
1968
- result: res,
1969
- threadId,
1970
- memoryConfig: memoryOptions,
1971
- outputText,
1972
- runId: runIdToUse
1973
- });
1974
- } catch (e) {
1975
- this.logger.error("Error saving memory on finish", {
1976
- error: e,
1977
- runId
1978
- });
1979
- }
1980
- onFinish?.(result);
1981
- },
1982
- maxSteps,
1983
- runId: runIdToUse,
1984
- toolChoice,
1985
- experimental_output,
1986
- memory: this.getMemory(),
1987
- ...rest
1988
- });
1989
- const newStreamResult = streamResult;
1990
- newStreamResult.partialObjectStream = streamResult.experimental_partialOutputStream;
1991
- return newStreamResult;
1992
- } else if (!output) {
1993
- this.logger.debug(`Starting agent ${this.name} llm stream call`, {
1994
- runId
1995
- });
1996
- return this.llm.__stream({
1997
- messages: messageObjects,
1998
- temperature,
1999
- tools: this.tools,
2000
- convertedTools,
2001
- onStepFinish,
2002
- onFinish: async result => {
2003
- try {
2004
- const res = JSON.parse(result) || {};
2005
- const outputText = res.text;
2006
- await after({
2007
- result: res,
2008
- threadId,
2009
- memoryConfig: memoryOptions,
2010
- outputText,
2011
- runId: runIdToUse
2012
- });
2013
- } catch (e) {
2014
- this.logger.error("Error saving memory on finish", {
2015
- error: e,
2016
- runId
2017
- });
2018
- }
2019
- onFinish?.(result);
2020
- },
2021
- maxSteps,
2022
- runId: runIdToUse,
2023
- toolChoice,
2024
- telemetry,
2025
- memory: this.getMemory(),
2026
- ...rest
2027
- });
2028
- }
2029
- this.logger.debug(`Starting agent ${this.name} llm streamObject call`, {
2030
- runId
2031
- });
2032
- return this.llm.__streamObject({
2033
- messages: messageObjects,
2034
- tools: this.tools,
2035
- temperature,
2036
- structuredOutput: output,
2037
- convertedTools,
2038
- onStepFinish,
2039
- onFinish: async result => {
2040
- try {
2041
- const res = JSON.parse(result) || {};
2042
- const outputText = JSON.stringify(res.object);
2043
- await after({
2044
- result: res,
2045
- threadId,
2046
- memoryConfig: memoryOptions,
2047
- outputText,
2048
- runId: runIdToUse
2049
- });
2050
- } catch (e) {
2051
- this.logger.error("Error saving memory on finish", {
2052
- error: e,
2053
- runId
2054
- });
2055
- }
2056
- onFinish?.(result);
2057
- },
2058
- runId: runIdToUse,
2059
- toolChoice,
2060
- telemetry,
2061
- memory: this.getMemory(),
2062
- ...rest
2063
- });
2064
- }
2065
- /**
2066
- * Convert text to speech using the configured voice provider
2067
- * @param input Text or text stream to convert to speech
2068
- * @param options Speech options including speaker and provider-specific options
2069
- * @returns Audio stream
2070
- */
2071
- async speak(input, options) {
2072
- if (!this.voice) {
2073
- throw new Error("No voice provider configured");
2074
- }
2075
- try {
2076
- return this.voice.speak(input, options);
2077
- } catch (e) {
2078
- this.logger.error("Error during agent speak", {
2079
- error: e
2080
- });
2081
- throw e;
2082
- }
2083
- }
2084
- /**
2085
- * Convert speech to text using the configured voice provider
2086
- * @param audioStream Audio stream to transcribe
2087
- * @param options Provider-specific transcription options
2088
- * @returns Text or text stream
2089
- */
2090
- async listen(audioStream, options) {
2091
- if (!this.voice) {
2092
- throw new Error("No voice provider configured");
2093
- }
2094
- try {
2095
- return this.voice.listen(audioStream, options);
2096
- } catch (e) {
2097
- this.logger.error("Error during agent listen", {
2098
- error: e
2099
- });
2100
- throw e;
2101
- }
2102
- }
2103
- /**
2104
- * Get a list of available speakers from the configured voice provider
2105
- * @throws {Error} If no voice provider is configured
2106
- * @returns {Promise<Array<{voiceId: string}>>} List of available speakers
2107
- */
2108
- async getSpeakers() {
2109
- if (!this.voice) {
2110
- throw new Error("No voice provider configured");
2111
- }
2112
- try {
2113
- return await this.voice.getSpeakers();
2114
- } catch (e) {
2115
- this.logger.error("Error during agent getSpeakers", {
2116
- error: e
2117
- });
2118
- throw e;
2119
- }
2120
- }
2121
- };
2122
- Agent = /*@__PURE__*/(_ => {
2123
- _init = __decoratorStart(_a);
2124
- Agent = __decorateElement(_init, 0, "Agent", _Agent_decorators, Agent);
2125
- __runInitializers(_init, 1, Agent);
2126
-
2127
- // src/relevance/relevance-score-provider.ts
2128
- return Agent;
2129
- })();
2130
- // src/relevance/relevance-score-provider.ts
2131
- function createSimilarityPrompt(query, text) {
2132
- return `Rate the semantic similarity between the following the query and the text on a scale from 0 to 1 (decimals allowed), where 1 means exactly the same meaning and 0 means completely different:
2133
-
2134
- Query: ${query}
2135
-
2136
- Text: ${text}
2137
-
2138
- Relevance score (0-1):`;
2139
- }
2140
-
2141
- // src/relevance/mastra-agent/index.ts
2142
- var MastraAgentRelevanceScorer = class {
2143
- agent;
2144
- constructor(name, model) {
2145
- this.agent = new Agent({
2146
- name: `Relevance Scorer ${name}`,
2147
- instructions: `You are a specialized agent for evaluating the relevance of text to queries.
2148
- Your task is to rate how well a text passage answers a given query.
2149
- Output only a number between 0 and 1, where:
2150
- 1.0 = Perfectly relevant, directly answers the query
2151
- 0.0 = Completely irrelevant
2152
- Consider:
2153
- - Direct relevance to the question
2154
- - Completeness of information
2155
- - Quality and specificity
2156
- Always return just the number, no explanation.`,
2157
- model
2158
- });
2159
- }
2160
- async getRelevanceScore(query, text) {
2161
- const prompt = createSimilarityPrompt(query, text);
2162
- const response = await this.agent.generate(prompt);
2163
- return parseFloat(response.text);
2164
- }
2165
- };
2166
-
2167
- exports.CohereRelevanceScorer = CohereRelevanceScorer;
2168
- exports.MastraAgentRelevanceScorer = MastraAgentRelevanceScorer;
2169
- exports.createSimilarityPrompt = createSimilarityPrompt;