@mastra/core 0.5.0-alpha.9 → 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 -2140
  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-CMEKtEnE.d.cts → base-CIPKleAU.d.cts} +97 -60
  6. package/dist/{base-B78F6w8S.d.ts → base-C_Oq53qk.d.ts} +97 -60
  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-IM7CM3DU.js → chunk-4Y74D74B.js} +1 -1
  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-TWAIC2XA.js → chunk-KP5UAFLN.js} +1 -1
  22. package/dist/chunk-KPKFLQFR.cjs +12 -0
  23. package/dist/{chunk-NR5T72G7.js → chunk-MLFXOST6.js} +1 -1
  24. package/dist/{chunk-6V737PR2.js → chunk-OD7ZMKHY.js} +166 -58
  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-4AQBRUR2.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-EWB556GS.js → chunk-YPD6BQIM.js} +29 -1
  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 -7516
  45. package/dist/index.d.cts +3 -3
  46. package/dist/index.d.ts +3 -3
  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 -2201
  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 -350
  80. package/dist/utils.d.cts +3 -3
  81. package/dist/utils.d.ts +3 -3
  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 -1936
  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,2209 +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 isZodType(value) {
478
- return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
479
- }
480
- function createDeterministicId(input) {
481
- return crypto$1.createHash("sha256").update(input).digest("hex").slice(0, 8);
482
- }
483
- function setVercelToolProperties(tool) {
484
- const inputSchema = convertVercelToolParameters(tool);
485
- const toolId = !("id" in tool) ? tool.description ? `tool-${createDeterministicId(tool.description)}` : `tool-${Math.random().toString(36).substring(2, 9)}` : tool.id;
486
- return {
487
- ...tool,
488
- id: toolId,
489
- inputSchema
490
- };
491
- }
492
- function ensureToolProperties(tools) {
493
- const toolsWithProperties = Object.keys(tools).reduce((acc, key) => {
494
- const tool = tools?.[key];
495
- if (tool) {
496
- if (isVercelTool(tool)) {
497
- acc[key] = setVercelToolProperties(tool);
498
- } else {
499
- acc[key] = tool;
500
- }
501
- }
502
- return acc;
503
- }, {});
504
- return toolsWithProperties;
505
- }
506
- function convertVercelToolParameters(tool) {
507
- const schema = tool.parameters ?? zod.z.object({});
508
- return isZodType(schema) ? schema : resolveSerializedZodOutput(jsonSchemaToZod__default.default(schema));
509
- }
510
- function makeCoreTool(tool, options, logType) {
511
- const getParameters = () => {
512
- if (isVercelTool(tool)) {
513
- return convertVercelToolParameters(tool);
514
- }
515
- return tool.inputSchema ?? zod.z.object({});
516
- };
517
- return {
518
- description: tool.description,
519
- parameters: getParameters(),
520
- execute: tool.execute ? createExecute(tool, {
521
- ...options,
522
- description: tool.description
523
- }, logType) : void 0
524
- };
525
- }
526
- function createMastraProxy({
527
- mastra,
528
- logger
529
- }) {
530
- return new Proxy(mastra, {
531
- get(target, prop) {
532
- const hasProp = Reflect.has(target, prop);
533
- if (hasProp) {
534
- const value = Reflect.get(target, prop);
535
- const isFunction = typeof value === "function";
536
- if (isFunction) {
537
- return value.bind(target);
538
- }
539
- return value;
540
- }
541
- if (prop === "logger") {
542
- logger.warn(`Please use 'getLogger' instead, logger is deprecated`);
543
- return Reflect.apply(target.getLogger, target, []);
544
- }
545
- if (prop === "telemetry") {
546
- logger.warn(`Please use 'getTelemetry' instead, telemetry is deprecated`);
547
- return Reflect.apply(target.getTelemetry, target, []);
548
- }
549
- if (prop === "storage") {
550
- logger.warn(`Please use 'getStorage' instead, storage is deprecated`);
551
- return Reflect.get(target, "storage");
552
- }
553
- if (prop === "agents") {
554
- logger.warn(`Please use 'getAgents' instead, agents is deprecated`);
555
- return Reflect.apply(target.getAgents, target, []);
556
- }
557
- if (prop === "tts") {
558
- logger.warn(`Please use 'getTTS' instead, tts is deprecated`);
559
- return Reflect.apply(target.getTTS, target, []);
560
- }
561
- if (prop === "vectors") {
562
- logger.warn(`Please use 'getVectors' instead, vectors is deprecated`);
563
- return Reflect.apply(target.getVectors, target, []);
564
- }
565
- if (prop === "memory") {
566
- logger.warn(`Please use 'getMemory' instead, memory is deprecated`);
567
- return Reflect.get(target, "memory");
568
- }
569
- return Reflect.get(target, prop);
570
- }
571
- });
572
- }
573
-
574
- // src/llm/model/model.ts
575
- var MastraLLM = class extends MastraLLMBase {
576
- #model;
577
- #mastra;
578
- constructor({
579
- model,
580
- mastra
581
- }) {
582
- super({
583
- name: "aisdk",
584
- model
585
- });
586
- this.#model = model;
587
- if (mastra) {
588
- this.#mastra = mastra;
589
- if (mastra.logger) {
590
- this.__setLogger(mastra.logger);
591
- }
592
- }
593
- }
594
- __registerPrimitives(p) {
595
- if (p.telemetry) {
596
- this.__setTelemetry(p.telemetry);
597
- }
598
- if (p.logger) {
599
- this.__setLogger(p.logger);
600
- }
601
- this.#mastra = p;
602
- }
603
- getProvider() {
604
- return this.#model.provider;
605
- }
606
- getModelId() {
607
- return this.#model.modelId;
608
- }
609
- getModel() {
610
- return this.#model;
611
- }
612
- convertTools({
613
- tools,
614
- runId,
615
- threadId,
616
- resourceId,
617
- memory
618
- } = {}) {
619
- this.logger.debug("Starting tool conversion for LLM");
620
- const converted = Object.entries(tools || {}).reduce((memo, value) => {
621
- const k = value[0];
622
- const tool = value[1];
623
- if (tool) {
624
- const options = {
625
- name: k,
626
- runId,
627
- threadId,
628
- resourceId,
629
- logger: this.logger,
630
- memory,
631
- mastra: this.#mastra
632
- };
633
- memo[k] = makeCoreTool(tool, options);
634
- }
635
- return memo;
636
- }, {});
637
- this.logger.debug(`Converted tools for LLM`);
638
- return converted;
639
- }
640
- async __text({
641
- runId,
642
- messages,
643
- maxSteps,
644
- tools,
645
- convertedTools,
646
- temperature,
647
- toolChoice = "auto",
648
- onStepFinish,
649
- experimental_output,
650
- telemetry,
651
- threadId,
652
- resourceId,
653
- memory,
654
- ...rest
655
- }) {
656
- const model = this.#model;
657
- this.logger.debug(`[LLM] - Generating text`, {
658
- runId,
659
- messages,
660
- maxSteps,
661
- threadId,
662
- resourceId,
663
- tools: Object.keys(tools || convertedTools || {})
664
- });
665
- const finalTools = convertedTools || this.convertTools({
666
- tools,
667
- runId,
668
- threadId,
669
- resourceId,
670
- memory
671
- });
672
- const argsForExecute = {
673
- model,
674
- temperature,
675
- tools: {
676
- ...finalTools
677
- },
678
- toolChoice,
679
- maxSteps,
680
- onStepFinish: async props => {
681
- onStepFinish?.(JSON.stringify(props, null, 2));
682
- this.logger.debug("[LLM] - Step Change:", {
683
- text: props?.text,
684
- toolCalls: props?.toolCalls,
685
- toolResults: props?.toolResults,
686
- finishReason: props?.finishReason,
687
- usage: props?.usage,
688
- runId
689
- });
690
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
691
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
692
- runId
693
- });
694
- await delay(10 * 1e3);
695
- }
696
- },
697
- ...rest
698
- };
699
- let schema;
700
- if (experimental_output) {
701
- this.logger.debug("[LLM] - Using experimental output", {
702
- runId
703
- });
704
- if (typeof experimental_output.parse === "function") {
705
- schema = experimental_output;
706
- if (schema instanceof zod.z.ZodArray) {
707
- schema = schema._def.type;
708
- }
709
- } else {
710
- schema = ai.jsonSchema(experimental_output);
711
- }
712
- }
713
- return await ai.generateText({
714
- messages,
715
- ...argsForExecute,
716
- experimental_telemetry: {
717
- ...this.experimental_telemetry,
718
- ...telemetry
719
- },
720
- experimental_output: schema ? ai.Output.object({
721
- schema
722
- }) : void 0
723
- });
724
- }
725
- async __textObject({
726
- messages,
727
- onStepFinish,
728
- maxSteps = 5,
729
- tools,
730
- convertedTools,
731
- structuredOutput,
732
- runId,
733
- temperature,
734
- toolChoice = "auto",
735
- telemetry,
736
- threadId,
737
- resourceId,
738
- memory,
739
- ...rest
740
- }) {
741
- const model = this.#model;
742
- this.logger.debug(`[LLM] - Generating a text object`, {
743
- runId
744
- });
745
- const finalTools = convertedTools || this.convertTools({
746
- tools,
747
- runId,
748
- threadId,
749
- resourceId,
750
- memory
751
- });
752
- const argsForExecute = {
753
- model,
754
- temperature,
755
- tools: {
756
- ...finalTools
757
- },
758
- maxSteps,
759
- toolChoice,
760
- onStepFinish: async props => {
761
- onStepFinish?.(JSON.stringify(props, null, 2));
762
- this.logger.debug("[LLM] - Step Change:", {
763
- text: props?.text,
764
- toolCalls: props?.toolCalls,
765
- toolResults: props?.toolResults,
766
- finishReason: props?.finishReason,
767
- usage: props?.usage,
768
- runId
769
- });
770
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
771
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
772
- runId
773
- });
774
- await delay(10 * 1e3);
775
- }
776
- },
777
- ...rest
778
- };
779
- let schema;
780
- let output = "object";
781
- if (typeof structuredOutput.parse === "function") {
782
- schema = structuredOutput;
783
- if (schema instanceof zod.z.ZodArray) {
784
- output = "array";
785
- schema = schema._def.type;
786
- }
787
- } else {
788
- schema = ai.jsonSchema(structuredOutput);
789
- }
790
- return await ai.generateObject({
791
- messages,
792
- ...argsForExecute,
793
- output,
794
- schema,
795
- experimental_telemetry: {
796
- ...this.experimental_telemetry,
797
- ...telemetry
798
- }
799
- });
800
- }
801
- async __stream({
802
- messages,
803
- onStepFinish,
804
- onFinish,
805
- maxSteps = 5,
806
- tools,
807
- convertedTools,
808
- runId,
809
- temperature,
810
- toolChoice = "auto",
811
- experimental_output,
812
- telemetry,
813
- threadId,
814
- resourceId,
815
- memory,
816
- ...rest
817
- }) {
818
- const model = this.#model;
819
- this.logger.debug(`[LLM] - Streaming text`, {
820
- runId,
821
- threadId,
822
- resourceId,
823
- messages,
824
- maxSteps,
825
- tools: Object.keys(tools || convertedTools || {})
826
- });
827
- const finalTools = convertedTools || this.convertTools({
828
- tools,
829
- runId,
830
- threadId,
831
- resourceId,
832
- memory
833
- });
834
- const argsForExecute = {
835
- model,
836
- temperature,
837
- tools: {
838
- ...finalTools
839
- },
840
- maxSteps,
841
- toolChoice,
842
- onStepFinish: async props => {
843
- onStepFinish?.(JSON.stringify(props, null, 2));
844
- this.logger.debug("[LLM] - Stream Step Change:", {
845
- text: props?.text,
846
- toolCalls: props?.toolCalls,
847
- toolResults: props?.toolResults,
848
- finishReason: props?.finishReason,
849
- usage: props?.usage,
850
- runId
851
- });
852
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
853
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
854
- runId
855
- });
856
- await delay(10 * 1e3);
857
- }
858
- },
859
- onFinish: async props => {
860
- void onFinish?.(JSON.stringify(props, null, 2));
861
- this.logger.debug("[LLM] - Stream Finished:", {
862
- text: props?.text,
863
- toolCalls: props?.toolCalls,
864
- toolResults: props?.toolResults,
865
- finishReason: props?.finishReason,
866
- usage: props?.usage,
867
- runId,
868
- threadId,
869
- resourceId
870
- });
871
- },
872
- ...rest
873
- };
874
- let schema;
875
- if (experimental_output) {
876
- this.logger.debug("[LLM] - Using experimental output", {
877
- runId
878
- });
879
- if (typeof experimental_output.parse === "function") {
880
- schema = experimental_output;
881
- if (schema instanceof zod.z.ZodArray) {
882
- schema = schema._def.type;
883
- }
884
- } else {
885
- schema = ai.jsonSchema(experimental_output);
886
- }
887
- }
888
- return await ai.streamText({
889
- messages,
890
- ...argsForExecute,
891
- experimental_telemetry: {
892
- ...this.experimental_telemetry,
893
- ...telemetry
894
- },
895
- experimental_output: schema ? ai.Output.object({
896
- schema
897
- }) : void 0
898
- });
899
- }
900
- async __streamObject({
901
- messages,
902
- onStepFinish,
903
- onFinish,
904
- maxSteps = 5,
905
- tools,
906
- convertedTools,
907
- structuredOutput,
908
- runId,
909
- temperature,
910
- toolChoice = "auto",
911
- telemetry,
912
- threadId,
913
- resourceId,
914
- memory,
915
- ...rest
916
- }) {
917
- const model = this.#model;
918
- this.logger.debug(`[LLM] - Streaming structured output`, {
919
- runId,
920
- messages,
921
- maxSteps,
922
- tools: Object.keys(tools || convertedTools || {})
923
- });
924
- const finalTools = convertedTools || this.convertTools({
925
- tools,
926
- runId,
927
- threadId,
928
- resourceId,
929
- memory
930
- });
931
- const argsForExecute = {
932
- model,
933
- temperature,
934
- tools: {
935
- ...finalTools
936
- },
937
- maxSteps,
938
- toolChoice,
939
- onStepFinish: async props => {
940
- onStepFinish?.(JSON.stringify(props, null, 2));
941
- this.logger.debug("[LLM] - Stream Step Change:", {
942
- text: props?.text,
943
- toolCalls: props?.toolCalls,
944
- toolResults: props?.toolResults,
945
- finishReason: props?.finishReason,
946
- usage: props?.usage,
947
- runId,
948
- threadId,
949
- resourceId
950
- });
951
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
952
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
953
- runId
954
- });
955
- await delay(10 * 1e3);
956
- }
957
- },
958
- onFinish: async props => {
959
- void onFinish?.(JSON.stringify(props, null, 2));
960
- this.logger.debug("[LLM] - Stream Finished:", {
961
- text: props?.text,
962
- toolCalls: props?.toolCalls,
963
- toolResults: props?.toolResults,
964
- finishReason: props?.finishReason,
965
- usage: props?.usage,
966
- runId,
967
- threadId,
968
- resourceId
969
- });
970
- },
971
- ...rest
972
- };
973
- let schema;
974
- let output = "object";
975
- if (typeof structuredOutput.parse === "function") {
976
- schema = structuredOutput;
977
- if (schema instanceof zod.z.ZodArray) {
978
- output = "array";
979
- schema = schema._def.type;
980
- }
981
- } else {
982
- schema = ai.jsonSchema(structuredOutput);
983
- }
984
- return ai.streamObject({
985
- messages,
986
- ...argsForExecute,
987
- output,
988
- schema,
989
- experimental_telemetry: {
990
- ...this.experimental_telemetry,
991
- ...telemetry
992
- }
993
- });
994
- }
995
- async generate(messages, {
996
- maxSteps = 5,
997
- onStepFinish,
998
- tools,
999
- convertedTools,
1000
- runId,
1001
- output,
1002
- temperature,
1003
- telemetry,
1004
- memory,
1005
- ...rest
1006
- } = {}) {
1007
- const msgs = this.convertToMessages(messages);
1008
- if (!output) {
1009
- return await this.__text({
1010
- messages: msgs,
1011
- onStepFinish,
1012
- maxSteps,
1013
- tools,
1014
- convertedTools,
1015
- runId,
1016
- temperature,
1017
- memory,
1018
- ...rest
1019
- });
1020
- }
1021
- return await this.__textObject({
1022
- messages: msgs,
1023
- structuredOutput: output,
1024
- onStepFinish,
1025
- maxSteps,
1026
- tools,
1027
- convertedTools,
1028
- runId,
1029
- telemetry,
1030
- memory,
1031
- ...rest
1032
- });
1033
- }
1034
- async stream(messages, {
1035
- maxSteps = 5,
1036
- onFinish,
1037
- onStepFinish,
1038
- tools,
1039
- convertedTools,
1040
- runId,
1041
- output,
1042
- temperature,
1043
- telemetry,
1044
- ...rest
1045
- } = {}) {
1046
- const msgs = this.convertToMessages(messages);
1047
- if (!output) {
1048
- return await this.__stream({
1049
- messages: msgs,
1050
- onStepFinish,
1051
- onFinish,
1052
- maxSteps,
1053
- tools,
1054
- convertedTools,
1055
- runId,
1056
- temperature,
1057
- telemetry,
1058
- ...rest
1059
- });
1060
- }
1061
- return await this.__streamObject({
1062
- messages: msgs,
1063
- structuredOutput: output,
1064
- onStepFinish,
1065
- onFinish,
1066
- maxSteps,
1067
- tools,
1068
- convertedTools,
1069
- runId,
1070
- temperature,
1071
- telemetry,
1072
- ...rest
1073
- });
1074
- }
1075
- };
1076
- function hasActiveTelemetry(tracerName = "default-tracer") {
1077
- try {
1078
- return !!api.trace.getTracer(tracerName);
1079
- } catch {
1080
- return false;
1081
- }
1082
- }
1083
-
1084
- // src/telemetry/telemetry.decorators.ts
1085
- function withSpan(options) {
1086
- return function (_target, propertyKey, descriptor) {
1087
- if (!descriptor || typeof descriptor === "number") return;
1088
- const originalMethod = descriptor.value;
1089
- const methodName = String(propertyKey);
1090
- descriptor.value = function (...args) {
1091
- if (options?.skipIfNoTelemetry && !hasActiveTelemetry(options?.tracerName)) {
1092
- return originalMethod.apply(this, args);
1093
- }
1094
- const tracer = api.trace.getTracer(options?.tracerName ?? "default-tracer");
1095
- let spanName;
1096
- let spanKind;
1097
- if (typeof options === "string") {
1098
- spanName = options;
1099
- } else if (options) {
1100
- spanName = options.spanName || methodName;
1101
- spanKind = options.spanKind;
1102
- } else {
1103
- spanName = methodName;
1104
- }
1105
- const span = tracer.startSpan(spanName, {
1106
- kind: spanKind
1107
- });
1108
- let ctx = api.trace.setSpan(api.context.active(), span);
1109
- args.forEach((arg, index) => {
1110
- try {
1111
- span.setAttribute(`${spanName}.argument.${index}`, JSON.stringify(arg));
1112
- } catch {
1113
- span.setAttribute(`${spanName}.argument.${index}`, "[Not Serializable]");
1114
- }
1115
- });
1116
- const currentBaggage = api.propagation.getBaggage(ctx);
1117
- if (currentBaggage?.componentName) {
1118
- span.setAttribute("componentName", currentBaggage?.componentName);
1119
- span.setAttribute("runId", currentBaggage?.runId);
1120
- } else if (this && this.name) {
1121
- span.setAttribute("componentName", this.name);
1122
- span.setAttribute("runId", this.runId);
1123
- ctx = api.propagation.setBaggage(ctx, {
1124
- componentName: this.name,
1125
- runId: this.runId
1126
- });
1127
- }
1128
- let result;
1129
- try {
1130
- result = api.context.with(ctx, () => originalMethod.apply(this, args));
1131
- if (result instanceof Promise) {
1132
- return result.then(resolvedValue => {
1133
- try {
1134
- span.setAttribute(`${spanName}.result`, JSON.stringify(resolvedValue));
1135
- } catch {
1136
- span.setAttribute(`${spanName}.result`, "[Not Serializable]");
1137
- }
1138
- return resolvedValue;
1139
- }).finally(() => span.end());
1140
- }
1141
- try {
1142
- span.setAttribute(`${spanName}.result`, JSON.stringify(result));
1143
- } catch {
1144
- span.setAttribute(`${spanName}.result`, "[Not Serializable]");
1145
- }
1146
- return result;
1147
- } catch (error) {
1148
- span.setStatus({
1149
- code: api.SpanStatusCode.ERROR,
1150
- message: error instanceof Error ? error.message : "Unknown error"
1151
- });
1152
- if (error instanceof Error) {
1153
- span.recordException(error);
1154
- }
1155
- throw error;
1156
- } finally {
1157
- if (!(result instanceof Promise)) {
1158
- span.end();
1159
- }
1160
- }
1161
- };
1162
- return descriptor;
1163
- };
1164
- }
1165
- function InstrumentClass(options) {
1166
- return function (target) {
1167
- const methods = Object.getOwnPropertyNames(target.prototype);
1168
- methods.forEach(method => {
1169
- if (options?.excludeMethods?.includes(method) || method === "constructor") return;
1170
- if (options?.methodFilter && !options.methodFilter(method)) return;
1171
- const descriptor = Object.getOwnPropertyDescriptor(target.prototype, method);
1172
- if (descriptor && typeof descriptor.value === "function") {
1173
- Object.defineProperty(target.prototype, method, withSpan({
1174
- spanName: options?.prefix ? `${options.prefix}.${method}` : method,
1175
- skipIfNoTelemetry: true,
1176
- spanKind: options?.spanKind || api.SpanKind.INTERNAL,
1177
- tracerName: options?.tracerName
1178
- })(target, method, descriptor));
1179
- }
1180
- });
1181
- return target;
1182
- };
1183
- }
1184
-
1185
- // src/agent/index.ts
1186
- var _Agent_decorators, _init, _a;
1187
- _Agent_decorators = [InstrumentClass({
1188
- prefix: "agent",
1189
- excludeMethods: ["__setTools", "__setLogger", "__setTelemetry", "log"]
1190
- })];
1191
- var Agent = class extends (_a = MastraBase) {
1192
- name;
1193
- llm;
1194
- instructions;
1195
- model;
1196
- #mastra;
1197
- #memory;
1198
- tools;
1199
- /** @deprecated This property is deprecated. Use evals instead. */
1200
- metrics;
1201
- evals;
1202
- voice;
1203
- constructor(config) {
1204
- super({
1205
- component: RegisteredLogger.AGENT
1206
- });
1207
- this.name = config.name;
1208
- this.instructions = config.instructions;
1209
- if (!config.model) {
1210
- throw new Error(`LanguageModel is required to create an Agent. Please provide the 'model'.`);
1211
- }
1212
- this.llm = new MastraLLM({
1213
- model: config.model
1214
- });
1215
- this.tools = {};
1216
- this.metrics = {};
1217
- this.evals = {};
1218
- if (config.tools) {
1219
- this.tools = ensureToolProperties(config.tools);
1220
- }
1221
- if (config.mastra) {
1222
- this.__registerPrimitives({
1223
- telemetry: config.mastra.getTelemetry(),
1224
- logger: config.mastra.getLogger()
1225
- });
1226
- }
1227
- if (config.metrics) {
1228
- this.logger.warn("The metrics property is deprecated. Please use evals instead to add evaluation metrics.");
1229
- this.metrics = config.metrics;
1230
- this.evals = config.metrics;
1231
- }
1232
- if (config.evals) {
1233
- this.evals = config.evals;
1234
- }
1235
- if (config.memory) {
1236
- this.#memory = config.memory;
1237
- }
1238
- if (config.voice) {
1239
- this.voice = config.voice;
1240
- }
1241
- }
1242
- hasOwnMemory() {
1243
- return Boolean(this.#memory);
1244
- }
1245
- getMemory() {
1246
- return this.#memory ?? this.#mastra?.memory;
1247
- }
1248
- __updateInstructions(newInstructions) {
1249
- this.instructions = newInstructions;
1250
- this.logger.debug(`[Agents:${this.name}] Instructions updated.`, {
1251
- model: this.model,
1252
- name: this.name
1253
- });
1254
- }
1255
- __registerPrimitives(p) {
1256
- if (p.telemetry) {
1257
- this.__setTelemetry(p.telemetry);
1258
- }
1259
- if (p.logger) {
1260
- this.__setLogger(p.logger);
1261
- }
1262
- this.llm.__registerPrimitives(p);
1263
- this.logger.debug(`[Agents:${this.name}] initialized.`, {
1264
- model: this.model,
1265
- name: this.name
1266
- });
1267
- }
1268
- __registerMastra(mastra) {
1269
- this.#mastra = mastra;
1270
- }
1271
- /**
1272
- * Set the concrete tools for the agent
1273
- * @param tools
1274
- */
1275
- __setTools(tools) {
1276
- this.tools = tools;
1277
- this.logger.debug(`[Agents:${this.name}] Tools set for agent ${this.name}`, {
1278
- model: this.model,
1279
- name: this.name
1280
- });
1281
- }
1282
- async generateTitleFromUserMessage({
1283
- message
1284
- }) {
1285
- const {
1286
- text
1287
- } = await this.llm.__text({
1288
- messages: [{
1289
- role: "system",
1290
- content: `
1291
-
1292
- - you will generate a short title based on the first message a user begins a conversation with
1293
- - ensure it is not more than 80 characters long
1294
- - the title should be a summary of the user's message
1295
- - do not use quotes or colons
1296
- - the entire text you return will be used as the title`
1297
- }, {
1298
- role: "user",
1299
- content: JSON.stringify(message)
1300
- }]
1301
- });
1302
- const cleanedText = text.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
1303
- return cleanedText;
1304
- }
1305
- getMostRecentUserMessage(messages) {
1306
- const userMessages = messages.filter(message => message.role === "user");
1307
- return userMessages.at(-1);
1308
- }
1309
- async genTitle(userMessage) {
1310
- let title = `New Thread ${(/* @__PURE__ */new Date()).toISOString()}`;
1311
- try {
1312
- if (userMessage) {
1313
- title = await this.generateTitleFromUserMessage({
1314
- message: userMessage
1315
- });
1316
- }
1317
- } catch (e) {
1318
- console.error("Error generating title:", e);
1319
- }
1320
- return title;
1321
- }
1322
- async saveMemory({
1323
- threadId,
1324
- memoryConfig,
1325
- resourceId,
1326
- userMessages,
1327
- runId
1328
- }) {
1329
- const userMessage = this.getMostRecentUserMessage(userMessages);
1330
- const memory = this.getMemory();
1331
- if (memory) {
1332
- const config = memory.getMergedThreadConfig(memoryConfig);
1333
- let thread;
1334
- if (!threadId) {
1335
- this.logger.debug(`No threadId, creating new thread for agent ${this.name}`, {
1336
- runId: runId || this.name
1337
- });
1338
- const title = config?.threads?.generateTitle ? await this.genTitle(userMessage) : void 0;
1339
- thread = await memory.createThread({
1340
- threadId,
1341
- resourceId,
1342
- memoryConfig,
1343
- title
1344
- });
1345
- } else {
1346
- thread = await memory.getThreadById({
1347
- threadId
1348
- });
1349
- if (!thread) {
1350
- this.logger.debug(`Thread with id ${threadId} not found, creating new thread for agent ${this.name}`, {
1351
- runId: runId || this.name
1352
- });
1353
- const title = config?.threads?.generateTitle ? await this.genTitle(userMessage) : void 0;
1354
- thread = await memory.createThread({
1355
- threadId,
1356
- resourceId,
1357
- title,
1358
- memoryConfig
1359
- });
1360
- }
1361
- }
1362
- const newMessages = userMessage ? [userMessage] : userMessages;
1363
- if (thread) {
1364
- const messages = newMessages.map(u => {
1365
- return {
1366
- id: this.getMemory()?.generateId(),
1367
- createdAt: /* @__PURE__ */new Date(),
1368
- threadId: thread.id,
1369
- ...u,
1370
- content: u.content,
1371
- role: u.role,
1372
- type: "text"
1373
- };
1374
- });
1375
- const memoryMessages = threadId && memory ? (await memory.rememberMessages({
1376
- threadId,
1377
- resourceId,
1378
- config: memoryConfig,
1379
- vectorMessageSearch: messages.slice(-1).map(m => {
1380
- if (typeof m === `string`) {
1381
- return m;
1382
- }
1383
- return m?.content || ``;
1384
- }).join(`
1385
- `)
1386
- })).messages : [];
1387
- if (memory) {
1388
- await memory.saveMessages({
1389
- messages,
1390
- memoryConfig
1391
- });
1392
- }
1393
- this.logger.debug("Saved messages to memory", {
1394
- threadId: thread.id,
1395
- runId
1396
- });
1397
- const memorySystemMessage = memory && threadId ? await memory.getSystemMessage({
1398
- threadId,
1399
- memoryConfig
1400
- }) : null;
1401
- return {
1402
- threadId: thread.id,
1403
- messages: [memorySystemMessage ? {
1404
- role: "system",
1405
- content: memorySystemMessage
1406
- } : null, ...this.sanitizeResponseMessages(memoryMessages), ...newMessages].filter(message => Boolean(message))
1407
- };
1408
- }
1409
- return {
1410
- threadId: thread?.id || threadId || "",
1411
- messages: userMessages
1412
- };
1413
- }
1414
- return {
1415
- threadId: threadId || "",
1416
- messages: userMessages
1417
- };
1418
- }
1419
- async saveResponse({
1420
- result,
1421
- threadId,
1422
- resourceId,
1423
- runId,
1424
- memoryConfig
1425
- }) {
1426
- const {
1427
- response
1428
- } = result;
1429
- try {
1430
- if (response.messages) {
1431
- const ms = Array.isArray(response.messages) ? response.messages : [response.messages];
1432
- const responseMessagesWithoutIncompleteToolCalls = this.sanitizeResponseMessages(ms);
1433
- const memory = this.getMemory();
1434
- if (memory) {
1435
- this.logger.debug(`[Agent:${this.name}] - Memory persistence: store=${this.getMemory()?.constructor.name} threadId=${threadId}`, {
1436
- runId,
1437
- resourceId,
1438
- threadId,
1439
- memoryStore: this.getMemory()?.constructor.name
1440
- });
1441
- await memory.saveMessages({
1442
- memoryConfig,
1443
- messages: responseMessagesWithoutIncompleteToolCalls.map((message, index) => {
1444
- const messageId = crypto$1.randomUUID();
1445
- let toolCallIds;
1446
- let toolCallArgs;
1447
- let toolNames;
1448
- let type = "text";
1449
- if (message.role === "tool") {
1450
- toolCallIds = message.content.map(content => content.toolCallId);
1451
- type = "tool-result";
1452
- }
1453
- if (message.role === "assistant") {
1454
- const assistantContent = message.content;
1455
- const assistantToolCalls = assistantContent.map(content => {
1456
- if (content.type === "tool-call") {
1457
- return {
1458
- toolCallId: content.toolCallId,
1459
- toolArgs: content.args,
1460
- toolName: content.toolName
1461
- };
1462
- }
1463
- return void 0;
1464
- })?.filter(Boolean);
1465
- toolCallIds = assistantToolCalls?.map(toolCall => toolCall.toolCallId);
1466
- toolCallArgs = assistantToolCalls?.map(toolCall => toolCall.toolArgs);
1467
- toolNames = assistantToolCalls?.map(toolCall => toolCall.toolName);
1468
- type = assistantContent?.[0]?.type;
1469
- }
1470
- return {
1471
- id: messageId,
1472
- threadId,
1473
- role: message.role,
1474
- content: message.content,
1475
- createdAt: new Date(Date.now() + index),
1476
- // use Date.now() + index to make sure every message is atleast one millisecond apart
1477
- toolCallIds: toolCallIds?.length ? toolCallIds : void 0,
1478
- toolCallArgs: toolCallArgs?.length ? toolCallArgs : void 0,
1479
- toolNames: toolNames?.length ? toolNames : void 0,
1480
- type
1481
- };
1482
- })
1483
- });
1484
- }
1485
- }
1486
- } catch (err) {
1487
- this.logger.error(`[Agent:${this.name}] - Failed to save assistant response`, {
1488
- error: err,
1489
- runId
1490
- });
1491
- }
1492
- }
1493
- sanitizeResponseMessages(messages) {
1494
- let toolResultIds = [];
1495
- let toolCallIds = [];
1496
- for (const message of messages) {
1497
- if (!Array.isArray(message.content)) continue;
1498
- if (message.role === "tool") {
1499
- for (const content of message.content) {
1500
- if (content.type === "tool-result") {
1501
- toolResultIds.push(content.toolCallId);
1502
- }
1503
- }
1504
- } else if (message.role === "assistant" || message.role === "user") {
1505
- for (const content of message.content) {
1506
- if (typeof content !== `string`) {
1507
- if (content.type === `tool-call`) {
1508
- toolCallIds.push(content.toolCallId);
1509
- }
1510
- }
1511
- }
1512
- }
1513
- }
1514
- const messagesBySanitizedContent = messages.map(message => {
1515
- if (message.role !== "assistant" && message.role !== `tool` && message.role !== `user`) return message;
1516
- if (!message.content || typeof message.content === "string" || typeof message.content === "number") {
1517
- return message;
1518
- }
1519
- const sanitizedContent = message.content.filter(content => {
1520
- if (content.type === `tool-call`) {
1521
- return toolResultIds.includes(content.toolCallId);
1522
- }
1523
- if (content.type === `text`) {
1524
- return content.text.trim() !== ``;
1525
- }
1526
- if (content.type === `tool-result`) {
1527
- return toolCallIds.includes(content.toolCallId);
1528
- }
1529
- return true;
1530
- });
1531
- return {
1532
- ...message,
1533
- content: sanitizedContent
1534
- };
1535
- });
1536
- return messagesBySanitizedContent.filter(message => {
1537
- if (typeof message.content === `string`) {
1538
- return message.content !== "";
1539
- }
1540
- if (Array.isArray(message.content)) {
1541
- return message.content.length && message.content.every(c => {
1542
- if (c.type === `text`) {
1543
- return c.text && c.text !== "";
1544
- }
1545
- return true;
1546
- });
1547
- }
1548
- return true;
1549
- });
1550
- }
1551
- convertTools({
1552
- toolsets,
1553
- threadId,
1554
- resourceId,
1555
- runId
1556
- }) {
1557
- this.logger.debug(`[Agents:${this.name}] - Assigning tools`, {
1558
- runId,
1559
- threadId,
1560
- resourceId
1561
- });
1562
- const memory = this.getMemory();
1563
- const memoryTools = memory?.getTools?.();
1564
- let mastraProxy = void 0;
1565
- const logger = this.logger;
1566
- if (this.#mastra) {
1567
- mastraProxy = createMastraProxy({
1568
- mastra: this.#mastra,
1569
- logger
1570
- });
1571
- }
1572
- const converted = Object.entries(this.tools || {}).reduce((memo, value) => {
1573
- const k = value[0];
1574
- const tool = this.tools[k];
1575
- if (tool) {
1576
- const options = {
1577
- name: k,
1578
- runId,
1579
- threadId,
1580
- resourceId,
1581
- logger: this.logger,
1582
- mastra: mastraProxy,
1583
- memory,
1584
- agentName: this.name
1585
- };
1586
- memo[k] = makeCoreTool(tool, options);
1587
- }
1588
- return memo;
1589
- }, {});
1590
- const convertedMemoryTools = memoryTools ? Object.entries(memoryTools).reduce((memo, [k, tool]) => {
1591
- memo[k] = {
1592
- description: tool.description,
1593
- parameters: tool.parameters,
1594
- execute: typeof tool?.execute === "function" ? async (args, options) => {
1595
- try {
1596
- this.logger.debug(`[Agent:${this.name}] - Executing memory tool ${k}`, {
1597
- name: k,
1598
- description: tool.description,
1599
- args,
1600
- runId,
1601
- threadId,
1602
- resourceId
1603
- });
1604
- return tool?.execute?.({
1605
- context: args,
1606
- mastra: mastraProxy,
1607
- memory,
1608
- runId,
1609
- threadId,
1610
- resourceId
1611
- }, options) ?? void 0;
1612
- } catch (err) {
1613
- this.logger.error(`[Agent:${this.name}] - Failed memory tool execution`, {
1614
- error: err,
1615
- runId,
1616
- threadId,
1617
- resourceId
1618
- });
1619
- throw err;
1620
- }
1621
- } : void 0
1622
- };
1623
- return memo;
1624
- }, {}) : {};
1625
- const toolsFromToolsetsConverted = {
1626
- ...converted,
1627
- ...convertedMemoryTools
1628
- };
1629
- const toolsFromToolsets = Object.values(toolsets || {});
1630
- if (toolsFromToolsets.length > 0) {
1631
- this.logger.debug(`[Agent:${this.name}] - Adding tools from toolsets ${Object.keys(toolsets || {}).join(", ")}`, {
1632
- runId
1633
- });
1634
- toolsFromToolsets.forEach(toolset => {
1635
- Object.entries(toolset).forEach(([toolName, tool]) => {
1636
- const toolObj = tool;
1637
- const options = {
1638
- name: toolName,
1639
- runId,
1640
- threadId,
1641
- resourceId,
1642
- logger: this.logger,
1643
- agentName: this.name
1644
- };
1645
- toolsFromToolsetsConverted[toolName] = makeCoreTool(toolObj, options, "toolset");
1646
- });
1647
- });
1648
- }
1649
- return toolsFromToolsetsConverted;
1650
- }
1651
- async preExecute({
1652
- resourceId,
1653
- runId,
1654
- threadId,
1655
- memoryConfig,
1656
- messages
1657
- }) {
1658
- let coreMessages = [];
1659
- let threadIdToUse = threadId;
1660
- this.logger.debug(`Saving user messages in memory for agent ${this.name}`, {
1661
- runId
1662
- });
1663
- const saveMessageResponse = await this.saveMemory({
1664
- threadId,
1665
- resourceId,
1666
- userMessages: messages,
1667
- memoryConfig
1668
- });
1669
- coreMessages = saveMessageResponse.messages;
1670
- threadIdToUse = saveMessageResponse.threadId;
1671
- return {
1672
- coreMessages,
1673
- threadIdToUse
1674
- };
1675
- }
1676
- __primitive({
1677
- messages,
1678
- context: context2,
1679
- threadId,
1680
- memoryConfig,
1681
- resourceId,
1682
- runId,
1683
- toolsets
1684
- }) {
1685
- return {
1686
- before: async () => {
1687
- if (process.env.NODE_ENV !== "test") {
1688
- this.logger.debug(`[Agents:${this.name}] - Starting generation`, {
1689
- runId
1690
- });
1691
- }
1692
- const systemMessage = {
1693
- role: "system",
1694
- content: `${this.instructions}.`
1695
- };
1696
- let coreMessages = messages;
1697
- let threadIdToUse = threadId;
1698
- const memory = this.getMemory();
1699
- if (threadId && memory && !resourceId) {
1700
- throw new Error(`A resourceId must be provided when passing a threadId and using Memory. Saw threadId ${threadId} but resourceId is ${resourceId}`);
1701
- }
1702
- if (memory && resourceId) {
1703
- this.logger.debug(`[Agent:${this.name}] - Memory persistence enabled: store=${this.getMemory()?.constructor.name}, resourceId=${resourceId}`, {
1704
- runId,
1705
- resourceId,
1706
- threadId: threadIdToUse,
1707
- memoryStore: this.getMemory()?.constructor.name
1708
- });
1709
- const preExecuteResult = await this.preExecute({
1710
- resourceId,
1711
- runId,
1712
- threadId: threadIdToUse,
1713
- memoryConfig,
1714
- messages
1715
- });
1716
- coreMessages = preExecuteResult.coreMessages;
1717
- threadIdToUse = preExecuteResult.threadIdToUse;
1718
- }
1719
- let convertedTools;
1720
- if (toolsets && Object.keys(toolsets || {}).length > 0 || this.getMemory() && resourceId) {
1721
- const reasons = [];
1722
- if (toolsets && Object.keys(toolsets || {}).length > 0) {
1723
- reasons.push(`toolsets present (${Object.keys(toolsets || {}).length} tools)`);
1724
- }
1725
- if (this.getMemory() && resourceId) {
1726
- reasons.push("memory and resourceId available");
1727
- }
1728
- this.logger.debug(`[Agent:${this.name}] - Enhancing tools: ${reasons.join(", ")}`, {
1729
- runId,
1730
- toolsets: toolsets ? Object.keys(toolsets) : void 0,
1731
- hasMemory: !!this.getMemory(),
1732
- hasResourceId: !!resourceId
1733
- });
1734
- convertedTools = this.convertTools({
1735
- toolsets,
1736
- threadId: threadIdToUse,
1737
- resourceId,
1738
- runId
1739
- });
1740
- }
1741
- const messageObjects = [systemMessage, ...(context2 || []), ...coreMessages];
1742
- return {
1743
- messageObjects,
1744
- convertedTools,
1745
- threadId: threadIdToUse
1746
- };
1747
- },
1748
- after: async ({
1749
- result,
1750
- threadId: threadId2,
1751
- memoryConfig: memoryConfig2,
1752
- outputText,
1753
- runId: runId2
1754
- }) => {
1755
- const resToLog = {
1756
- text: result?.text,
1757
- object: result?.object,
1758
- toolResults: result?.toolResults,
1759
- toolCalls: result?.toolCalls,
1760
- usage: result?.usage,
1761
- steps: result?.steps?.map(s => {
1762
- return {
1763
- stepType: s?.stepType,
1764
- text: result?.text,
1765
- object: result?.object,
1766
- toolResults: result?.toolResults,
1767
- toolCalls: result?.toolCalls,
1768
- usage: result?.usage
1769
- };
1770
- })
1771
- };
1772
- this.logger.debug(`[Agent:${this.name}] - Post processing LLM response`, {
1773
- runId: runId2,
1774
- result: resToLog,
1775
- threadId: threadId2
1776
- });
1777
- if (this.getMemory() && resourceId) {
1778
- try {
1779
- await this.saveResponse({
1780
- result,
1781
- threadId: threadId2,
1782
- resourceId,
1783
- memoryConfig: memoryConfig2,
1784
- runId: runId2
1785
- });
1786
- } catch (e) {
1787
- this.logger.error("Error saving response", {
1788
- error: e,
1789
- runId: runId2,
1790
- result: resToLog,
1791
- threadId: threadId2
1792
- });
1793
- }
1794
- }
1795
- if (Object.keys(this.evals || {}).length > 0) {
1796
- const input = messages.map(message => message.content).join("\n");
1797
- const runIdToUse = runId2 || crypto.randomUUID();
1798
- for (const metric of Object.values(this.evals || {})) {
1799
- executeHook("onGeneration" /* ON_GENERATION */, {
1800
- input,
1801
- output: outputText,
1802
- runId: runIdToUse,
1803
- metric,
1804
- agentName: this.name,
1805
- instructions: this.instructions
1806
- });
1807
- }
1808
- }
1809
- }
1810
- };
1811
- }
1812
- async generate(messages, {
1813
- context: context2,
1814
- threadId: threadIdInFn,
1815
- memoryOptions,
1816
- resourceId,
1817
- maxSteps = 5,
1818
- onStepFinish,
1819
- runId,
1820
- output,
1821
- toolsets,
1822
- temperature,
1823
- toolChoice = "auto",
1824
- experimental_output,
1825
- telemetry,
1826
- ...rest
1827
- } = {}) {
1828
- let messagesToUse = [];
1829
- if (typeof messages === `string`) {
1830
- messagesToUse = [{
1831
- role: "user",
1832
- content: messages
1833
- }];
1834
- } else {
1835
- messagesToUse = messages.map(message => {
1836
- if (typeof message === `string`) {
1837
- return {
1838
- role: "user",
1839
- content: message
1840
- };
1841
- }
1842
- return message;
1843
- });
1844
- }
1845
- const runIdToUse = runId || crypto$1.randomUUID();
1846
- const {
1847
- before,
1848
- after
1849
- } = this.__primitive({
1850
- messages: messagesToUse,
1851
- context: context2,
1852
- threadId: threadIdInFn,
1853
- memoryConfig: memoryOptions,
1854
- resourceId,
1855
- runId: runIdToUse,
1856
- toolsets
1857
- });
1858
- const {
1859
- threadId,
1860
- messageObjects,
1861
- convertedTools
1862
- } = await before();
1863
- if (!output && experimental_output) {
1864
- const result2 = await this.llm.__text({
1865
- messages: messageObjects,
1866
- tools: this.tools,
1867
- convertedTools,
1868
- onStepFinish,
1869
- maxSteps: maxSteps || 5,
1870
- runId: runIdToUse,
1871
- temperature,
1872
- toolChoice: toolChoice || "auto",
1873
- experimental_output,
1874
- threadId,
1875
- resourceId,
1876
- memory: this.getMemory(),
1877
- ...rest
1878
- });
1879
- const outputText2 = result2.text;
1880
- await after({
1881
- result: result2,
1882
- threadId,
1883
- memoryConfig: memoryOptions,
1884
- outputText: outputText2,
1885
- runId: runIdToUse
1886
- });
1887
- const newResult = result2;
1888
- newResult.object = result2.experimental_output;
1889
- return newResult;
1890
- }
1891
- if (!output) {
1892
- const result2 = await this.llm.__text({
1893
- messages: messageObjects,
1894
- tools: this.tools,
1895
- convertedTools,
1896
- onStepFinish,
1897
- maxSteps,
1898
- runId: runIdToUse,
1899
- temperature,
1900
- toolChoice,
1901
- telemetry,
1902
- threadId,
1903
- resourceId,
1904
- memory: this.getMemory(),
1905
- ...rest
1906
- });
1907
- const outputText2 = result2.text;
1908
- await after({
1909
- result: result2,
1910
- threadId,
1911
- memoryConfig: memoryOptions,
1912
- outputText: outputText2,
1913
- runId: runIdToUse
1914
- });
1915
- return result2;
1916
- }
1917
- const result = await this.llm.__textObject({
1918
- messages: messageObjects,
1919
- tools: this.tools,
1920
- structuredOutput: output,
1921
- convertedTools,
1922
- onStepFinish,
1923
- maxSteps,
1924
- runId: runIdToUse,
1925
- temperature,
1926
- toolChoice,
1927
- telemetry,
1928
- memory: this.getMemory(),
1929
- ...rest
1930
- });
1931
- const outputText = JSON.stringify(result.object);
1932
- await after({
1933
- result,
1934
- threadId,
1935
- memoryConfig: memoryOptions,
1936
- outputText,
1937
- runId: runIdToUse
1938
- });
1939
- return result;
1940
- }
1941
- async stream(messages, {
1942
- context: context2,
1943
- threadId: threadIdInFn,
1944
- memoryOptions,
1945
- resourceId,
1946
- maxSteps = 5,
1947
- onFinish,
1948
- onStepFinish,
1949
- runId,
1950
- toolsets,
1951
- output,
1952
- temperature,
1953
- toolChoice = "auto",
1954
- experimental_output,
1955
- telemetry,
1956
- ...rest
1957
- } = {}) {
1958
- const runIdToUse = runId || crypto$1.randomUUID();
1959
- let messagesToUse = [];
1960
- if (typeof messages === `string`) {
1961
- messagesToUse = [{
1962
- role: "user",
1963
- content: messages
1964
- }];
1965
- } else {
1966
- messagesToUse = messages.map(message => {
1967
- if (typeof message === `string`) {
1968
- return {
1969
- role: "user",
1970
- content: message
1971
- };
1972
- }
1973
- return message;
1974
- });
1975
- }
1976
- const {
1977
- before,
1978
- after
1979
- } = this.__primitive({
1980
- messages: messagesToUse,
1981
- context: context2,
1982
- threadId: threadIdInFn,
1983
- memoryConfig: memoryOptions,
1984
- resourceId,
1985
- runId: runIdToUse,
1986
- toolsets
1987
- });
1988
- const {
1989
- threadId,
1990
- messageObjects,
1991
- convertedTools
1992
- } = await before();
1993
- if (!output && experimental_output) {
1994
- this.logger.debug(`Starting agent ${this.name} llm stream call`, {
1995
- runId
1996
- });
1997
- const streamResult = await this.llm.__stream({
1998
- messages: messageObjects,
1999
- temperature,
2000
- tools: this.tools,
2001
- convertedTools,
2002
- onStepFinish,
2003
- onFinish: async result => {
2004
- try {
2005
- const res = JSON.parse(result) || {};
2006
- const outputText = res.text;
2007
- await after({
2008
- result: res,
2009
- threadId,
2010
- memoryConfig: memoryOptions,
2011
- outputText,
2012
- runId: runIdToUse
2013
- });
2014
- } catch (e) {
2015
- this.logger.error("Error saving memory on finish", {
2016
- error: e,
2017
- runId
2018
- });
2019
- }
2020
- onFinish?.(result);
2021
- },
2022
- maxSteps,
2023
- runId: runIdToUse,
2024
- toolChoice,
2025
- experimental_output,
2026
- memory: this.getMemory(),
2027
- ...rest
2028
- });
2029
- const newStreamResult = streamResult;
2030
- newStreamResult.partialObjectStream = streamResult.experimental_partialOutputStream;
2031
- return newStreamResult;
2032
- } else if (!output) {
2033
- this.logger.debug(`Starting agent ${this.name} llm stream call`, {
2034
- runId
2035
- });
2036
- return this.llm.__stream({
2037
- messages: messageObjects,
2038
- temperature,
2039
- tools: this.tools,
2040
- convertedTools,
2041
- onStepFinish,
2042
- onFinish: async result => {
2043
- try {
2044
- const res = JSON.parse(result) || {};
2045
- const outputText = res.text;
2046
- await after({
2047
- result: res,
2048
- threadId,
2049
- memoryConfig: memoryOptions,
2050
- outputText,
2051
- runId: runIdToUse
2052
- });
2053
- } catch (e) {
2054
- this.logger.error("Error saving memory on finish", {
2055
- error: e,
2056
- runId
2057
- });
2058
- }
2059
- onFinish?.(result);
2060
- },
2061
- maxSteps,
2062
- runId: runIdToUse,
2063
- toolChoice,
2064
- telemetry,
2065
- memory: this.getMemory(),
2066
- ...rest
2067
- });
2068
- }
2069
- this.logger.debug(`Starting agent ${this.name} llm streamObject call`, {
2070
- runId
2071
- });
2072
- return this.llm.__streamObject({
2073
- messages: messageObjects,
2074
- tools: this.tools,
2075
- temperature,
2076
- structuredOutput: output,
2077
- convertedTools,
2078
- onStepFinish,
2079
- onFinish: async result => {
2080
- try {
2081
- const res = JSON.parse(result) || {};
2082
- const outputText = JSON.stringify(res.object);
2083
- await after({
2084
- result: res,
2085
- threadId,
2086
- memoryConfig: memoryOptions,
2087
- outputText,
2088
- runId: runIdToUse
2089
- });
2090
- } catch (e) {
2091
- this.logger.error("Error saving memory on finish", {
2092
- error: e,
2093
- runId
2094
- });
2095
- }
2096
- onFinish?.(result);
2097
- },
2098
- runId: runIdToUse,
2099
- toolChoice,
2100
- telemetry,
2101
- memory: this.getMemory(),
2102
- ...rest
2103
- });
2104
- }
2105
- /**
2106
- * Convert text to speech using the configured voice provider
2107
- * @param input Text or text stream to convert to speech
2108
- * @param options Speech options including speaker and provider-specific options
2109
- * @returns Audio stream
2110
- */
2111
- async speak(input, options) {
2112
- if (!this.voice) {
2113
- throw new Error("No voice provider configured");
2114
- }
2115
- try {
2116
- return this.voice.speak(input, options);
2117
- } catch (e) {
2118
- this.logger.error("Error during agent speak", {
2119
- error: e
2120
- });
2121
- throw e;
2122
- }
2123
- }
2124
- /**
2125
- * Convert speech to text using the configured voice provider
2126
- * @param audioStream Audio stream to transcribe
2127
- * @param options Provider-specific transcription options
2128
- * @returns Text or text stream
2129
- */
2130
- async listen(audioStream, options) {
2131
- if (!this.voice) {
2132
- throw new Error("No voice provider configured");
2133
- }
2134
- try {
2135
- return this.voice.listen(audioStream, options);
2136
- } catch (e) {
2137
- this.logger.error("Error during agent listen", {
2138
- error: e
2139
- });
2140
- throw e;
2141
- }
2142
- }
2143
- /**
2144
- * Get a list of available speakers from the configured voice provider
2145
- * @throws {Error} If no voice provider is configured
2146
- * @returns {Promise<Array<{voiceId: string}>>} List of available speakers
2147
- */
2148
- async getSpeakers() {
2149
- if (!this.voice) {
2150
- throw new Error("No voice provider configured");
2151
- }
2152
- try {
2153
- return await this.voice.getSpeakers();
2154
- } catch (e) {
2155
- this.logger.error("Error during agent getSpeakers", {
2156
- error: e
2157
- });
2158
- throw e;
2159
- }
2160
- }
2161
- };
2162
- Agent = /*@__PURE__*/(_ => {
2163
- _init = __decoratorStart(_a);
2164
- Agent = __decorateElement(_init, 0, "Agent", _Agent_decorators, Agent);
2165
- __runInitializers(_init, 1, Agent);
2166
-
2167
- // src/relevance/relevance-score-provider.ts
2168
- return Agent;
2169
- })();
2170
- // src/relevance/relevance-score-provider.ts
2171
- function createSimilarityPrompt(query, text) {
2172
- 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:
2173
-
2174
- Query: ${query}
2175
-
2176
- Text: ${text}
2177
-
2178
- Relevance score (0-1):`;
2179
- }
2180
-
2181
- // src/relevance/mastra-agent/index.ts
2182
- var MastraAgentRelevanceScorer = class {
2183
- agent;
2184
- constructor(name, model) {
2185
- this.agent = new Agent({
2186
- name: `Relevance Scorer ${name}`,
2187
- instructions: `You are a specialized agent for evaluating the relevance of text to queries.
2188
- Your task is to rate how well a text passage answers a given query.
2189
- Output only a number between 0 and 1, where:
2190
- 1.0 = Perfectly relevant, directly answers the query
2191
- 0.0 = Completely irrelevant
2192
- Consider:
2193
- - Direct relevance to the question
2194
- - Completeness of information
2195
- - Quality and specificity
2196
- Always return just the number, no explanation.`,
2197
- model
2198
- });
2199
- }
2200
- async getRelevanceScore(query, text) {
2201
- const prompt = createSimilarityPrompt(query, text);
2202
- const response = await this.agent.generate(prompt);
2203
- return parseFloat(response.text);
2204
- }
2205
- };
2206
-
2207
- exports.CohereRelevanceScorer = CohereRelevanceScorer;
2208
- exports.MastraAgentRelevanceScorer = MastraAgentRelevanceScorer;
2209
- exports.createSimilarityPrompt = createSimilarityPrompt;