@mastra/core 0.7.0 → 0.8.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/agent/index.cjs +2 -2
  2. package/dist/agent/index.d.cts +3 -1
  3. package/dist/agent/index.d.ts +3 -1
  4. package/dist/agent/index.js +1 -1
  5. package/dist/{base-Cyl73WbV.d.ts → base-B65ZjbJw.d.ts} +100 -29
  6. package/dist/{base-C0wILuA9.d.cts → base-CYeyHJtc.d.cts} +100 -29
  7. package/dist/{chunk-ZBKJDQPM.js → chunk-5U7ZB5ID.js} +7 -0
  8. package/dist/{chunk-43SD5CUE.js → chunk-6IH4PY2A.js} +60 -6
  9. package/dist/{chunk-SMBKF6K5.js → chunk-APV5PNPE.js} +9 -0
  10. package/dist/chunk-AZEVFYZU.cjs +4609 -0
  11. package/dist/{chunk-ASFUEC75.cjs → chunk-BS2HQKYH.cjs} +61 -6
  12. package/dist/{chunk-YXJQFZOW.cjs → chunk-FKP3IMFA.cjs} +7 -0
  13. package/dist/{chunk-U7ONOIBO.cjs → chunk-G3GVZCXA.cjs} +9 -0
  14. package/dist/chunk-HWCOUI5E.js +4582 -0
  15. package/dist/{chunk-QM6WIIPM.js → chunk-TKOMVZT3.js} +1 -1
  16. package/dist/{chunk-WESJ2ZY7.cjs → chunk-TKOVKRVO.cjs} +2 -2
  17. package/dist/eval/index.d.cts +3 -1
  18. package/dist/eval/index.d.ts +3 -1
  19. package/dist/index.cjs +53 -42
  20. package/dist/index.d.cts +7 -5
  21. package/dist/index.d.ts +7 -5
  22. package/dist/index.js +6 -6
  23. package/dist/integration/index.d.cts +3 -1
  24. package/dist/integration/index.d.ts +3 -1
  25. package/dist/llm/index.d.cts +3 -1
  26. package/dist/llm/index.d.ts +3 -1
  27. package/dist/mastra/index.cjs +2 -2
  28. package/dist/mastra/index.d.cts +3 -1
  29. package/dist/mastra/index.d.ts +3 -1
  30. package/dist/mastra/index.js +1 -1
  31. package/dist/memory/index.cjs +6 -2
  32. package/dist/memory/index.d.cts +3 -1
  33. package/dist/memory/index.d.ts +3 -1
  34. package/dist/memory/index.js +1 -1
  35. package/dist/network/index.cjs +2 -2
  36. package/dist/network/index.d.cts +3 -1
  37. package/dist/network/index.d.ts +3 -1
  38. package/dist/network/index.js +1 -1
  39. package/dist/relevance/index.cjs +4 -4
  40. package/dist/relevance/index.d.cts +3 -1
  41. package/dist/relevance/index.d.ts +3 -1
  42. package/dist/relevance/index.js +1 -1
  43. package/dist/server/index.cjs +17 -0
  44. package/dist/server/index.d.cts +37 -0
  45. package/dist/server/index.d.ts +37 -0
  46. package/dist/server/index.js +15 -0
  47. package/dist/storage/index.d.cts +3 -1
  48. package/dist/storage/index.d.ts +3 -1
  49. package/dist/storage/libsql/index.d.cts +3 -1
  50. package/dist/storage/libsql/index.d.ts +3 -1
  51. package/dist/telemetry/index.d.cts +3 -1
  52. package/dist/telemetry/index.d.ts +3 -1
  53. package/dist/tools/index.d.cts +3 -1
  54. package/dist/tools/index.d.ts +3 -1
  55. package/dist/utils.d.cts +5 -3
  56. package/dist/utils.d.ts +5 -3
  57. package/dist/vector/libsql/index.cjs +3 -3
  58. package/dist/vector/libsql/index.js +1 -1
  59. package/dist/voice/index.d.cts +3 -1
  60. package/dist/voice/index.d.ts +3 -1
  61. package/dist/workflows/index.cjs +28 -20
  62. package/dist/workflows/index.d.cts +14 -5
  63. package/dist/workflows/index.d.ts +14 -5
  64. package/dist/workflows/index.js +1 -1
  65. package/package.json +4 -2
  66. package/dist/chunk-C6BBAS4I.cjs +0 -1715
  67. package/dist/chunk-GG6TEAMJ.cjs +0 -2289
  68. package/dist/chunk-R2M5CZ5U.js +0 -2264
  69. package/dist/chunk-VNQRLYIA.js +0 -1715
@@ -1,1715 +0,0 @@
1
- import { InstrumentClass } from './chunk-W5HVJX45.js';
2
- import { ensureToolProperties, ensureAllMessagesAreCoreMessages, createMastraProxy, makeCoreTool, delay } from './chunk-2YF5JYTJ.js';
3
- import { MastraBase } from './chunk-VN4M67DA.js';
4
- import { RegisteredLogger } from './chunk-L7CR75HA.js';
5
- import { executeHook } from './chunk-BB4KXGBU.js';
6
- import { __decoratorStart, __decorateElement, __runInitializers } from './chunk-C6A6W6XS.js';
7
- import { randomUUID } from 'crypto';
8
- import { jsonSchema, generateText, Output, generateObject, streamText, streamObject } from 'ai';
9
- import { z } from 'zod';
10
-
11
- // src/llm/model/base.ts
12
- var MastraLLMBase = class extends MastraBase {
13
- // @ts-ignore
14
- #mastra;
15
- #model;
16
- constructor({
17
- name,
18
- model
19
- }) {
20
- super({
21
- component: RegisteredLogger.LLM,
22
- name
23
- });
24
- this.#model = model;
25
- }
26
- getProvider() {
27
- return this.#model.provider;
28
- }
29
- getModelId() {
30
- return this.#model.modelId;
31
- }
32
- getModel() {
33
- return this.#model;
34
- }
35
- convertToMessages(messages) {
36
- if (Array.isArray(messages)) {
37
- return messages.map(m => {
38
- if (typeof m === "string") {
39
- return {
40
- role: "user",
41
- content: m
42
- };
43
- }
44
- return m;
45
- });
46
- }
47
- return [{
48
- role: "user",
49
- content: messages
50
- }];
51
- }
52
- __registerPrimitives(p) {
53
- if (p.telemetry) {
54
- this.__setTelemetry(p.telemetry);
55
- }
56
- if (p.logger) {
57
- this.__setLogger(p.logger);
58
- }
59
- }
60
- __registerMastra(p) {
61
- this.#mastra = p;
62
- }
63
- async __text(input) {
64
- this.logger.debug(`[LLMs:${this.name}] Generating text.`, {
65
- input
66
- });
67
- throw new Error("Method not implemented.");
68
- }
69
- async __textObject(input) {
70
- this.logger.debug(`[LLMs:${this.name}] Generating object.`, {
71
- input
72
- });
73
- throw new Error("Method not implemented.");
74
- }
75
- async generate(messages, options = {}) {
76
- this.logger.debug(`[LLMs:${this.name}] Generating text.`, {
77
- messages,
78
- options
79
- });
80
- throw new Error("Method not implemented.");
81
- }
82
- async __stream(input) {
83
- this.logger.debug(`[LLMs:${this.name}] Streaming text.`, {
84
- input
85
- });
86
- throw new Error("Method not implemented.");
87
- }
88
- async __streamObject(input) {
89
- this.logger.debug(`[LLMs:${this.name}] Streaming object.`, {
90
- input
91
- });
92
- throw new Error("Method not implemented.");
93
- }
94
- async stream(messages, options = {}) {
95
- this.logger.debug(`[LLMs:${this.name}] Streaming text.`, {
96
- messages,
97
- options
98
- });
99
- throw new Error("Method not implemented.");
100
- }
101
- };
102
- var MastraLLM = class extends MastraLLMBase {
103
- #model;
104
- #mastra;
105
- constructor({
106
- model,
107
- mastra
108
- }) {
109
- super({
110
- name: "aisdk",
111
- model
112
- });
113
- this.#model = model;
114
- if (mastra) {
115
- this.#mastra = mastra;
116
- if (mastra.getLogger()) {
117
- this.__setLogger(mastra.getLogger());
118
- }
119
- }
120
- }
121
- __registerPrimitives(p) {
122
- if (p.telemetry) {
123
- this.__setTelemetry(p.telemetry);
124
- }
125
- if (p.logger) {
126
- this.__setLogger(p.logger);
127
- }
128
- }
129
- __registerMastra(p) {
130
- this.#mastra = p;
131
- }
132
- getProvider() {
133
- return this.#model.provider;
134
- }
135
- getModelId() {
136
- return this.#model.modelId;
137
- }
138
- getModel() {
139
- return this.#model;
140
- }
141
- convertTools({
142
- tools,
143
- runId,
144
- threadId,
145
- resourceId,
146
- memory
147
- } = {}) {
148
- this.logger.debug("Starting tool conversion for LLM");
149
- let mastraProxy = void 0;
150
- const logger = this.logger;
151
- if (this.#mastra) {
152
- mastraProxy = createMastraProxy({
153
- mastra: this.#mastra,
154
- logger
155
- });
156
- }
157
- const converted = Object.entries(tools || {}).reduce((memo, value) => {
158
- const k = value[0];
159
- const tool = value[1];
160
- if (tool) {
161
- const options = {
162
- name: k,
163
- runId,
164
- threadId,
165
- resourceId,
166
- logger: this.logger,
167
- memory,
168
- mastra: mastraProxy
169
- };
170
- memo[k] = makeCoreTool(tool, options);
171
- }
172
- return memo;
173
- }, {});
174
- this.logger.debug(`Converted tools for LLM`);
175
- return converted;
176
- }
177
- async __text({
178
- runId,
179
- messages,
180
- maxSteps,
181
- tools,
182
- convertedTools,
183
- temperature,
184
- toolChoice = "auto",
185
- onStepFinish,
186
- experimental_output,
187
- telemetry,
188
- threadId,
189
- resourceId,
190
- memory,
191
- ...rest
192
- }) {
193
- const model = this.#model;
194
- this.logger.debug(`[LLM] - Generating text`, {
195
- runId,
196
- messages,
197
- maxSteps,
198
- threadId,
199
- resourceId,
200
- tools: Object.keys(tools || convertedTools || {})
201
- });
202
- const finalTools = convertedTools || this.convertTools({
203
- tools,
204
- runId,
205
- threadId,
206
- resourceId,
207
- memory
208
- });
209
- const argsForExecute = {
210
- model,
211
- temperature,
212
- tools: {
213
- ...finalTools
214
- },
215
- toolChoice,
216
- maxSteps,
217
- onStepFinish: async props => {
218
- void onStepFinish?.(props);
219
- this.logger.debug("[LLM] - Step Change:", {
220
- text: props?.text,
221
- toolCalls: props?.toolCalls,
222
- toolResults: props?.toolResults,
223
- finishReason: props?.finishReason,
224
- usage: props?.usage,
225
- runId
226
- });
227
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
228
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
229
- runId
230
- });
231
- await delay(10 * 1e3);
232
- }
233
- },
234
- ...rest
235
- };
236
- let schema;
237
- if (experimental_output) {
238
- this.logger.debug("[LLM] - Using experimental output", {
239
- runId
240
- });
241
- if (typeof experimental_output.parse === "function") {
242
- schema = experimental_output;
243
- if (schema instanceof z.ZodArray) {
244
- schema = schema._def.type;
245
- }
246
- } else {
247
- schema = jsonSchema(experimental_output);
248
- }
249
- }
250
- return await generateText({
251
- messages,
252
- ...argsForExecute,
253
- experimental_telemetry: {
254
- ...this.experimental_telemetry,
255
- ...telemetry
256
- },
257
- experimental_output: schema ? Output.object({
258
- schema
259
- }) : void 0
260
- });
261
- }
262
- async __textObject({
263
- messages,
264
- onStepFinish,
265
- maxSteps = 5,
266
- tools,
267
- convertedTools,
268
- structuredOutput,
269
- runId,
270
- temperature,
271
- toolChoice = "auto",
272
- telemetry,
273
- threadId,
274
- resourceId,
275
- memory,
276
- ...rest
277
- }) {
278
- const model = this.#model;
279
- this.logger.debug(`[LLM] - Generating a text object`, {
280
- runId
281
- });
282
- const finalTools = convertedTools || this.convertTools({
283
- tools,
284
- runId,
285
- threadId,
286
- resourceId,
287
- memory
288
- });
289
- const argsForExecute = {
290
- model,
291
- temperature,
292
- tools: {
293
- ...finalTools
294
- },
295
- maxSteps,
296
- toolChoice,
297
- onStepFinish: async props => {
298
- void onStepFinish?.(props);
299
- this.logger.debug("[LLM] - Step Change:", {
300
- text: props?.text,
301
- toolCalls: props?.toolCalls,
302
- toolResults: props?.toolResults,
303
- finishReason: props?.finishReason,
304
- usage: props?.usage,
305
- runId
306
- });
307
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
308
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
309
- runId
310
- });
311
- await delay(10 * 1e3);
312
- }
313
- },
314
- ...rest
315
- };
316
- let schema;
317
- let output = "object";
318
- if (typeof structuredOutput.parse === "function") {
319
- schema = structuredOutput;
320
- if (schema instanceof z.ZodArray) {
321
- output = "array";
322
- schema = schema._def.type;
323
- }
324
- } else {
325
- schema = jsonSchema(structuredOutput);
326
- }
327
- return await generateObject({
328
- messages,
329
- ...argsForExecute,
330
- output,
331
- schema,
332
- experimental_telemetry: {
333
- ...this.experimental_telemetry,
334
- ...telemetry
335
- }
336
- });
337
- }
338
- async __stream({
339
- messages,
340
- onStepFinish,
341
- onFinish,
342
- maxSteps = 5,
343
- tools,
344
- convertedTools,
345
- runId,
346
- temperature,
347
- toolChoice = "auto",
348
- experimental_output,
349
- telemetry,
350
- threadId,
351
- resourceId,
352
- memory,
353
- ...rest
354
- }) {
355
- const model = this.#model;
356
- this.logger.debug(`[LLM] - Streaming text`, {
357
- runId,
358
- threadId,
359
- resourceId,
360
- messages,
361
- maxSteps,
362
- tools: Object.keys(tools || convertedTools || {})
363
- });
364
- const finalTools = convertedTools || this.convertTools({
365
- tools,
366
- runId,
367
- threadId,
368
- resourceId,
369
- memory
370
- });
371
- const argsForExecute = {
372
- model,
373
- temperature,
374
- tools: {
375
- ...finalTools
376
- },
377
- maxSteps,
378
- toolChoice,
379
- onStepFinish: async props => {
380
- void onStepFinish?.(props);
381
- this.logger.debug("[LLM] - Stream Step Change:", {
382
- text: props?.text,
383
- toolCalls: props?.toolCalls,
384
- toolResults: props?.toolResults,
385
- finishReason: props?.finishReason,
386
- usage: props?.usage,
387
- runId
388
- });
389
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
390
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
391
- runId
392
- });
393
- await delay(10 * 1e3);
394
- }
395
- },
396
- onFinish: async props => {
397
- void onFinish?.(props);
398
- this.logger.debug("[LLM] - Stream Finished:", {
399
- text: props?.text,
400
- toolCalls: props?.toolCalls,
401
- toolResults: props?.toolResults,
402
- finishReason: props?.finishReason,
403
- usage: props?.usage,
404
- runId,
405
- threadId,
406
- resourceId
407
- });
408
- },
409
- ...rest
410
- };
411
- let schema;
412
- if (experimental_output) {
413
- this.logger.debug("[LLM] - Using experimental output", {
414
- runId
415
- });
416
- if (typeof experimental_output.parse === "function") {
417
- schema = experimental_output;
418
- if (schema instanceof z.ZodArray) {
419
- schema = schema._def.type;
420
- }
421
- } else {
422
- schema = jsonSchema(experimental_output);
423
- }
424
- }
425
- return await streamText({
426
- messages,
427
- ...argsForExecute,
428
- experimental_telemetry: {
429
- ...this.experimental_telemetry,
430
- ...telemetry
431
- },
432
- experimental_output: schema ? Output.object({
433
- schema
434
- }) : void 0
435
- });
436
- }
437
- async __streamObject({
438
- messages,
439
- onStepFinish,
440
- onFinish,
441
- maxSteps = 5,
442
- tools,
443
- convertedTools,
444
- structuredOutput,
445
- runId,
446
- temperature,
447
- toolChoice = "auto",
448
- telemetry,
449
- threadId,
450
- resourceId,
451
- memory,
452
- ...rest
453
- }) {
454
- const model = this.#model;
455
- this.logger.debug(`[LLM] - Streaming structured output`, {
456
- runId,
457
- messages,
458
- maxSteps,
459
- tools: Object.keys(tools || convertedTools || {})
460
- });
461
- const finalTools = convertedTools || this.convertTools({
462
- tools,
463
- runId,
464
- threadId,
465
- resourceId,
466
- memory
467
- });
468
- const argsForExecute = {
469
- model,
470
- temperature,
471
- tools: {
472
- ...finalTools
473
- },
474
- maxSteps,
475
- toolChoice,
476
- onStepFinish: async props => {
477
- void onStepFinish?.(props);
478
- this.logger.debug("[LLM] - Stream Step Change:", {
479
- text: props?.text,
480
- toolCalls: props?.toolCalls,
481
- toolResults: props?.toolResults,
482
- finishReason: props?.finishReason,
483
- usage: props?.usage,
484
- runId,
485
- threadId,
486
- resourceId
487
- });
488
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
489
- this.logger.warn("Rate limit approaching, waiting 10 seconds", {
490
- runId
491
- });
492
- await delay(10 * 1e3);
493
- }
494
- },
495
- onFinish: async props => {
496
- void onFinish?.(props);
497
- this.logger.debug("[LLM] - Stream Finished:", {
498
- text: props?.text,
499
- toolCalls: props?.toolCalls,
500
- toolResults: props?.toolResults,
501
- finishReason: props?.finishReason,
502
- usage: props?.usage,
503
- runId,
504
- threadId,
505
- resourceId
506
- });
507
- },
508
- ...rest
509
- };
510
- let schema;
511
- let output = "object";
512
- if (typeof structuredOutput.parse === "function") {
513
- schema = structuredOutput;
514
- if (schema instanceof z.ZodArray) {
515
- output = "array";
516
- schema = schema._def.type;
517
- }
518
- } else {
519
- schema = jsonSchema(structuredOutput);
520
- }
521
- return streamObject({
522
- messages,
523
- ...argsForExecute,
524
- output,
525
- schema,
526
- experimental_telemetry: {
527
- ...this.experimental_telemetry,
528
- ...telemetry
529
- }
530
- });
531
- }
532
- async generate(messages, {
533
- maxSteps = 5,
534
- onStepFinish,
535
- tools,
536
- convertedTools,
537
- runId,
538
- output,
539
- temperature,
540
- telemetry,
541
- memory,
542
- ...rest
543
- } = {}) {
544
- const msgs = this.convertToMessages(messages);
545
- if (!output) {
546
- return await this.__text({
547
- messages: msgs,
548
- onStepFinish,
549
- maxSteps,
550
- tools,
551
- convertedTools,
552
- runId,
553
- temperature,
554
- memory,
555
- ...rest
556
- });
557
- }
558
- return await this.__textObject({
559
- messages: msgs,
560
- structuredOutput: output,
561
- onStepFinish,
562
- maxSteps,
563
- tools,
564
- convertedTools,
565
- runId,
566
- telemetry,
567
- memory,
568
- ...rest
569
- });
570
- }
571
- async stream(messages, {
572
- maxSteps = 5,
573
- onFinish,
574
- onStepFinish,
575
- tools,
576
- convertedTools,
577
- runId,
578
- output,
579
- temperature,
580
- telemetry,
581
- ...rest
582
- } = {}) {
583
- const msgs = this.convertToMessages(messages);
584
- if (!output) {
585
- return await this.__stream({
586
- messages: msgs,
587
- onStepFinish,
588
- onFinish,
589
- maxSteps,
590
- tools,
591
- convertedTools,
592
- runId,
593
- temperature,
594
- telemetry,
595
- ...rest
596
- });
597
- }
598
- return await this.__streamObject({
599
- messages: msgs,
600
- structuredOutput: output,
601
- onStepFinish,
602
- onFinish,
603
- maxSteps,
604
- tools,
605
- convertedTools,
606
- runId,
607
- temperature,
608
- telemetry,
609
- ...rest
610
- });
611
- }
612
- convertToUIMessages(messages) {
613
- function addToolMessageToChat({
614
- toolMessage,
615
- messages: messages2,
616
- toolResultContents
617
- }) {
618
- const chatMessages2 = messages2.map(message => {
619
- if (message.toolInvocations) {
620
- return {
621
- ...message,
622
- toolInvocations: message.toolInvocations.map(toolInvocation => {
623
- const toolResult = toolMessage.content.find(tool => tool.toolCallId === toolInvocation.toolCallId);
624
- if (toolResult) {
625
- return {
626
- ...toolInvocation,
627
- state: "result",
628
- result: toolResult.result
629
- };
630
- }
631
- return toolInvocation;
632
- })
633
- };
634
- }
635
- return message;
636
- });
637
- const resultContents = [...toolResultContents, ...toolMessage.content];
638
- return {
639
- chatMessages: chatMessages2,
640
- toolResultContents: resultContents
641
- };
642
- }
643
- const {
644
- chatMessages
645
- } = messages.reduce((obj, message) => {
646
- if (message.role === "tool") {
647
- return addToolMessageToChat({
648
- toolMessage: message,
649
- messages: obj.chatMessages,
650
- toolResultContents: obj.toolResultContents
651
- });
652
- }
653
- let textContent = "";
654
- let toolInvocations = [];
655
- if (typeof message.content === "string") {
656
- textContent = message.content;
657
- } else if (typeof message.content === "number") {
658
- textContent = String(message.content);
659
- } else if (Array.isArray(message.content)) {
660
- for (const content of message.content) {
661
- if (content.type === "text") {
662
- textContent += content.text;
663
- } else if (content.type === "tool-call") {
664
- const toolResult = obj.toolResultContents.find(tool => tool.toolCallId === content.toolCallId);
665
- toolInvocations.push({
666
- state: toolResult ? "result" : "call",
667
- toolCallId: content.toolCallId,
668
- toolName: content.toolName,
669
- args: content.args,
670
- result: toolResult?.result
671
- });
672
- }
673
- }
674
- }
675
- obj.chatMessages.push({
676
- id: message.id,
677
- role: message.role,
678
- content: textContent,
679
- toolInvocations
680
- });
681
- return obj;
682
- }, {
683
- chatMessages: [],
684
- toolResultContents: []
685
- });
686
- return chatMessages;
687
- }
688
- };
689
-
690
- // src/agent/index.ts
691
- var _Agent_decorators, _init, _a;
692
- _Agent_decorators = [InstrumentClass({
693
- prefix: "agent",
694
- excludeMethods: ["__setTools", "__setLogger", "__setTelemetry", "log"]
695
- })];
696
- var Agent = class extends (_a = MastraBase) {
697
- name;
698
- llm;
699
- instructions;
700
- model;
701
- #mastra;
702
- #memory;
703
- tools;
704
- /** @deprecated This property is deprecated. Use evals instead. */
705
- metrics;
706
- evals;
707
- voice;
708
- constructor(config) {
709
- super({
710
- component: RegisteredLogger.AGENT
711
- });
712
- this.name = config.name;
713
- this.instructions = config.instructions;
714
- if (!config.model) {
715
- throw new Error(`LanguageModel is required to create an Agent. Please provide the 'model'.`);
716
- }
717
- this.llm = new MastraLLM({
718
- model: config.model,
719
- mastra: config.mastra
720
- });
721
- this.tools = {};
722
- this.metrics = {};
723
- this.evals = {};
724
- if (config.tools) {
725
- this.tools = ensureToolProperties(config.tools);
726
- }
727
- if (config.mastra) {
728
- this.__registerMastra(config.mastra);
729
- this.__registerPrimitives({
730
- telemetry: config.mastra.getTelemetry(),
731
- logger: config.mastra.getLogger()
732
- });
733
- }
734
- if (config.metrics) {
735
- this.logger.warn("The metrics property is deprecated. Please use evals instead to add evaluation metrics.");
736
- this.metrics = config.metrics;
737
- this.evals = config.metrics;
738
- }
739
- if (config.evals) {
740
- this.evals = config.evals;
741
- }
742
- if (config.memory) {
743
- this.#memory = config.memory;
744
- }
745
- if (config.voice) {
746
- this.voice = config.voice;
747
- this.voice?.addTools(this.tools);
748
- this.voice?.addInstructions(config.instructions);
749
- }
750
- }
751
- hasOwnMemory() {
752
- return Boolean(this.#memory);
753
- }
754
- getMemory() {
755
- return this.#memory ?? this.#mastra?.memory;
756
- }
757
- __updateInstructions(newInstructions) {
758
- this.instructions = newInstructions;
759
- this.logger.debug(`[Agents:${this.name}] Instructions updated.`, {
760
- model: this.model,
761
- name: this.name
762
- });
763
- }
764
- __registerPrimitives(p) {
765
- if (p.telemetry) {
766
- this.__setTelemetry(p.telemetry);
767
- }
768
- if (p.logger) {
769
- this.__setLogger(p.logger);
770
- }
771
- this.llm.__registerPrimitives(p);
772
- this.logger.debug(`[Agents:${this.name}] initialized.`, {
773
- model: this.model,
774
- name: this.name
775
- });
776
- }
777
- __registerMastra(mastra) {
778
- this.#mastra = mastra;
779
- this.llm.__registerMastra(mastra);
780
- }
781
- /**
782
- * Set the concrete tools for the agent
783
- * @param tools
784
- */
785
- __setTools(tools) {
786
- this.tools = tools;
787
- this.logger.debug(`[Agents:${this.name}] Tools set for agent ${this.name}`, {
788
- model: this.model,
789
- name: this.name
790
- });
791
- }
792
- async generateTitleFromUserMessage({
793
- message
794
- }) {
795
- const {
796
- text
797
- } = await this.llm.__text({
798
- messages: [{
799
- role: "system",
800
- content: `
801
-
802
- - you will generate a short title based on the first message a user begins a conversation with
803
- - ensure it is not more than 80 characters long
804
- - the title should be a summary of the user's message
805
- - do not use quotes or colons
806
- - the entire text you return will be used as the title`
807
- }, {
808
- role: "user",
809
- content: JSON.stringify(message)
810
- }]
811
- });
812
- const cleanedText = text.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
813
- return cleanedText;
814
- }
815
- getMostRecentUserMessage(messages) {
816
- const userMessages = messages.filter(message => message.role === "user");
817
- return userMessages.at(-1);
818
- }
819
- async genTitle(userMessage) {
820
- let title = `New Thread ${(/* @__PURE__ */new Date()).toISOString()}`;
821
- try {
822
- if (userMessage) {
823
- title = await this.generateTitleFromUserMessage({
824
- message: userMessage
825
- });
826
- }
827
- } catch (e) {
828
- console.error("Error generating title:", e);
829
- }
830
- return title;
831
- }
832
- async fetchMemory({
833
- threadId,
834
- memoryConfig,
835
- resourceId,
836
- userMessages,
837
- runId
838
- }) {
839
- const memory = this.getMemory();
840
- if (memory) {
841
- const thread = await memory.getThreadById({
842
- threadId
843
- });
844
- if (!thread) {
845
- return {
846
- threadId: threadId || "",
847
- messages: userMessages
848
- };
849
- }
850
- const newMessages = ensureAllMessagesAreCoreMessages(userMessages);
851
- const messages = newMessages.map(u => {
852
- return {
853
- id: this.getMemory()?.generateId(),
854
- createdAt: /* @__PURE__ */new Date(),
855
- threadId,
856
- ...u,
857
- content: u.content,
858
- role: u.role,
859
- type: "text"
860
- };
861
- });
862
- const [memoryMessages, memorySystemMessage] = threadId && memory ? await Promise.all([memory.rememberMessages({
863
- threadId,
864
- resourceId,
865
- config: memoryConfig,
866
- vectorMessageSearch: messages.slice(-1).map(m => {
867
- if (typeof m === `string`) {
868
- return m;
869
- }
870
- return m?.content || ``;
871
- }).join(`
872
- `)
873
- }).then(r => r.messages), memory.getSystemMessage({
874
- threadId,
875
- memoryConfig
876
- })]) : [[], null];
877
- this.logger.debug("Saved messages to memory", {
878
- threadId,
879
- runId
880
- });
881
- return {
882
- threadId: thread.id,
883
- messages: [memorySystemMessage ? {
884
- role: "system",
885
- content: memorySystemMessage
886
- } : null, ...this.sanitizeResponseMessages(memoryMessages), ...newMessages].filter(message => Boolean(message))
887
- };
888
- }
889
- return {
890
- threadId: threadId || "",
891
- messages: userMessages
892
- };
893
- }
894
- async saveResponse({
895
- result,
896
- threadId,
897
- resourceId,
898
- runId,
899
- memoryConfig
900
- }) {
901
- const {
902
- response
903
- } = result;
904
- try {
905
- if (response.messages) {
906
- const ms = Array.isArray(response.messages) ? response.messages : [response.messages];
907
- const responseMessagesWithoutIncompleteToolCalls = this.sanitizeResponseMessages(ms);
908
- const memory = this.getMemory();
909
- if (memory) {
910
- this.logger.debug(`[Agent:${this.name}] - Memory persistence: store=${this.getMemory()?.constructor.name} threadId=${threadId}`, {
911
- runId,
912
- resourceId,
913
- threadId,
914
- memoryStore: this.getMemory()?.constructor.name
915
- });
916
- await memory.saveMessages({
917
- memoryConfig,
918
- messages: responseMessagesWithoutIncompleteToolCalls.map((message, index) => {
919
- const messageId = randomUUID();
920
- let toolCallIds;
921
- let toolCallArgs;
922
- let toolNames;
923
- let type = "text";
924
- if (message.role === "tool") {
925
- toolCallIds = message.content.map(content => content.toolCallId);
926
- type = "tool-result";
927
- }
928
- if (message.role === "assistant") {
929
- const assistantContent = message.content;
930
- const assistantToolCalls = assistantContent.map(content => {
931
- if (content.type === "tool-call") {
932
- return {
933
- toolCallId: content.toolCallId,
934
- toolArgs: content.args,
935
- toolName: content.toolName
936
- };
937
- }
938
- return void 0;
939
- })?.filter(Boolean);
940
- toolCallIds = assistantToolCalls?.map(toolCall => toolCall.toolCallId);
941
- toolCallArgs = assistantToolCalls?.map(toolCall => toolCall.toolArgs);
942
- toolNames = assistantToolCalls?.map(toolCall => toolCall.toolName);
943
- type = assistantContent?.[0]?.type;
944
- }
945
- return {
946
- id: messageId,
947
- threadId,
948
- role: message.role,
949
- content: message.content,
950
- createdAt: new Date(Date.now() + index),
951
- // use Date.now() + index to make sure every message is atleast one millisecond apart
952
- toolCallIds: toolCallIds?.length ? toolCallIds : void 0,
953
- toolCallArgs: toolCallArgs?.length ? toolCallArgs : void 0,
954
- toolNames: toolNames?.length ? toolNames : void 0,
955
- type
956
- };
957
- })
958
- });
959
- }
960
- }
961
- } catch (err) {
962
- this.logger.error(`[Agent:${this.name}] - Failed to save assistant response`, {
963
- error: err,
964
- runId
965
- });
966
- }
967
- }
968
- sanitizeResponseMessages(messages) {
969
- let toolResultIds = [];
970
- let toolCallIds = [];
971
- for (const message of messages) {
972
- if (!Array.isArray(message.content)) continue;
973
- if (message.role === "tool") {
974
- for (const content of message.content) {
975
- if (content.type === "tool-result") {
976
- toolResultIds.push(content.toolCallId);
977
- }
978
- }
979
- } else if (message.role === "assistant" || message.role === "user") {
980
- for (const content of message.content) {
981
- if (typeof content !== `string`) {
982
- if (content.type === `tool-call`) {
983
- toolCallIds.push(content.toolCallId);
984
- }
985
- }
986
- }
987
- }
988
- }
989
- const messagesBySanitizedContent = messages.map(message => {
990
- if (message.role !== "assistant" && message.role !== `tool` && message.role !== `user`) return message;
991
- if (!message.content || typeof message.content === "string" || typeof message.content === "number") {
992
- return message;
993
- }
994
- const sanitizedContent = message.content.filter(content => {
995
- if (content.type === `tool-call`) {
996
- return toolResultIds.includes(content.toolCallId);
997
- }
998
- if (content.type === `text`) {
999
- return content.text.trim() !== ``;
1000
- }
1001
- if (content.type === `tool-result`) {
1002
- return toolCallIds.includes(content.toolCallId);
1003
- }
1004
- return true;
1005
- });
1006
- return {
1007
- ...message,
1008
- content: sanitizedContent
1009
- };
1010
- });
1011
- return messagesBySanitizedContent.filter(message => {
1012
- if (typeof message.content === `string`) {
1013
- return message.content !== "";
1014
- }
1015
- if (Array.isArray(message.content)) {
1016
- return message.content.length && message.content.every(c => {
1017
- if (c.type === `text`) {
1018
- return c.text && c.text !== "";
1019
- }
1020
- return true;
1021
- });
1022
- }
1023
- return true;
1024
- });
1025
- }
1026
- convertTools({
1027
- toolsets,
1028
- threadId,
1029
- resourceId,
1030
- runId
1031
- }) {
1032
- this.logger.debug(`[Agents:${this.name}] - Assigning tools`, {
1033
- runId,
1034
- threadId,
1035
- resourceId
1036
- });
1037
- const memory = this.getMemory();
1038
- const memoryTools = memory?.getTools?.();
1039
- let mastraProxy = void 0;
1040
- const logger = this.logger;
1041
- if (this.#mastra) {
1042
- mastraProxy = createMastraProxy({
1043
- mastra: this.#mastra,
1044
- logger
1045
- });
1046
- }
1047
- const converted = Object.entries(this.tools || {}).reduce((memo, value) => {
1048
- const k = value[0];
1049
- const tool = this.tools[k];
1050
- if (tool) {
1051
- const options = {
1052
- name: k,
1053
- runId,
1054
- threadId,
1055
- resourceId,
1056
- logger: this.logger,
1057
- mastra: mastraProxy,
1058
- memory,
1059
- agentName: this.name
1060
- };
1061
- memo[k] = makeCoreTool(tool, options);
1062
- }
1063
- return memo;
1064
- }, {});
1065
- const convertedMemoryTools = memoryTools ? Object.entries(memoryTools).reduce((memo, [k, tool]) => {
1066
- memo[k] = {
1067
- description: tool.description,
1068
- parameters: tool.parameters,
1069
- execute: typeof tool?.execute === "function" ? async (args, options) => {
1070
- try {
1071
- this.logger.debug(`[Agent:${this.name}] - Executing memory tool ${k}`, {
1072
- name: k,
1073
- description: tool.description,
1074
- args,
1075
- runId,
1076
- threadId,
1077
- resourceId
1078
- });
1079
- return tool?.execute?.({
1080
- context: args,
1081
- mastra: mastraProxy,
1082
- memory,
1083
- runId,
1084
- threadId,
1085
- resourceId
1086
- }, options) ?? void 0;
1087
- } catch (err) {
1088
- this.logger.error(`[Agent:${this.name}] - Failed memory tool execution`, {
1089
- error: err,
1090
- runId,
1091
- threadId,
1092
- resourceId
1093
- });
1094
- throw err;
1095
- }
1096
- } : void 0
1097
- };
1098
- return memo;
1099
- }, {}) : {};
1100
- const toolsFromToolsetsConverted = {
1101
- ...converted,
1102
- ...convertedMemoryTools
1103
- };
1104
- const toolsFromToolsets = Object.values(toolsets || {});
1105
- if (toolsFromToolsets.length > 0) {
1106
- this.logger.debug(`[Agent:${this.name}] - Adding tools from toolsets ${Object.keys(toolsets || {}).join(", ")}`, {
1107
- runId
1108
- });
1109
- toolsFromToolsets.forEach(toolset => {
1110
- Object.entries(toolset).forEach(([toolName, tool]) => {
1111
- const toolObj = tool;
1112
- const options = {
1113
- name: toolName,
1114
- runId,
1115
- threadId,
1116
- resourceId,
1117
- logger: this.logger,
1118
- agentName: this.name
1119
- };
1120
- toolsFromToolsetsConverted[toolName] = makeCoreTool(toolObj, options, "toolset");
1121
- });
1122
- });
1123
- }
1124
- return toolsFromToolsetsConverted;
1125
- }
1126
- async preExecute({
1127
- resourceId,
1128
- runId,
1129
- threadId,
1130
- memoryConfig,
1131
- messages
1132
- }) {
1133
- let coreMessages = [];
1134
- let threadIdToUse = threadId;
1135
- this.logger.debug(`Saving user messages in memory for agent ${this.name}`, {
1136
- runId
1137
- });
1138
- const saveMessageResponse = await this.fetchMemory({
1139
- threadId,
1140
- resourceId,
1141
- userMessages: messages,
1142
- memoryConfig
1143
- });
1144
- coreMessages = saveMessageResponse.messages;
1145
- threadIdToUse = saveMessageResponse.threadId;
1146
- return {
1147
- coreMessages,
1148
- threadIdToUse
1149
- };
1150
- }
1151
- __primitive({
1152
- instructions,
1153
- messages,
1154
- context,
1155
- threadId,
1156
- memoryConfig,
1157
- resourceId,
1158
- runId,
1159
- toolsets
1160
- }) {
1161
- return {
1162
- before: async () => {
1163
- if (process.env.NODE_ENV !== "test") {
1164
- this.logger.debug(`[Agents:${this.name}] - Starting generation`, {
1165
- runId
1166
- });
1167
- }
1168
- const systemMessage = {
1169
- role: "system",
1170
- content: instructions || `${this.instructions}.`
1171
- };
1172
- let coreMessages = messages;
1173
- let threadIdToUse = threadId;
1174
- const memory = this.getMemory();
1175
- if (threadId && memory && !resourceId) {
1176
- throw new Error(`A resourceId must be provided when passing a threadId and using Memory. Saw threadId ${threadId} but resourceId is ${resourceId}`);
1177
- }
1178
- if (memory && resourceId) {
1179
- this.logger.debug(`[Agent:${this.name}] - Memory persistence enabled: store=${this.getMemory()?.constructor.name}, resourceId=${resourceId}`, {
1180
- runId,
1181
- resourceId,
1182
- threadId: threadIdToUse,
1183
- memoryStore: this.getMemory()?.constructor.name
1184
- });
1185
- let thread = threadIdToUse ? await memory.getThreadById({
1186
- threadId: threadIdToUse
1187
- }) : void 0;
1188
- if (!thread) {
1189
- thread = await memory.createThread({
1190
- threadId: threadIdToUse,
1191
- resourceId,
1192
- memoryConfig
1193
- });
1194
- }
1195
- threadIdToUse = thread.id;
1196
- const preExecuteResult = await this.preExecute({
1197
- resourceId,
1198
- runId,
1199
- threadId: threadIdToUse,
1200
- memoryConfig,
1201
- messages
1202
- });
1203
- coreMessages = preExecuteResult.coreMessages;
1204
- threadIdToUse = preExecuteResult.threadIdToUse;
1205
- }
1206
- let convertedTools;
1207
- if (toolsets && Object.keys(toolsets || {}).length > 0 || this.getMemory() && resourceId) {
1208
- const reasons = [];
1209
- if (toolsets && Object.keys(toolsets || {}).length > 0) {
1210
- reasons.push(`toolsets present (${Object.keys(toolsets || {}).length} tools)`);
1211
- }
1212
- if (this.getMemory() && resourceId) {
1213
- reasons.push("memory and resourceId available");
1214
- }
1215
- this.logger.debug(`[Agent:${this.name}] - Enhancing tools: ${reasons.join(", ")}`, {
1216
- runId,
1217
- toolsets: toolsets ? Object.keys(toolsets) : void 0,
1218
- hasMemory: !!this.getMemory(),
1219
- hasResourceId: !!resourceId
1220
- });
1221
- convertedTools = this.convertTools({
1222
- toolsets,
1223
- threadId: threadIdToUse,
1224
- resourceId,
1225
- runId
1226
- });
1227
- }
1228
- const messageObjects = [systemMessage, ...(context || []), ...coreMessages];
1229
- return {
1230
- messageObjects,
1231
- convertedTools,
1232
- threadId: threadIdToUse
1233
- };
1234
- },
1235
- after: async ({
1236
- result,
1237
- threadId: threadId2,
1238
- memoryConfig: memoryConfig2,
1239
- outputText,
1240
- runId: runId2
1241
- }) => {
1242
- const resToLog = {
1243
- text: result?.text,
1244
- object: result?.object,
1245
- toolResults: result?.toolResults,
1246
- toolCalls: result?.toolCalls,
1247
- usage: result?.usage,
1248
- steps: result?.steps?.map(s => {
1249
- return {
1250
- stepType: s?.stepType,
1251
- text: result?.text,
1252
- object: result?.object,
1253
- toolResults: result?.toolResults,
1254
- toolCalls: result?.toolCalls,
1255
- usage: result?.usage
1256
- };
1257
- })
1258
- };
1259
- this.logger.debug(`[Agent:${this.name}] - Post processing LLM response`, {
1260
- runId: runId2,
1261
- result: resToLog,
1262
- threadId: threadId2
1263
- });
1264
- const memory = this.getMemory();
1265
- const thread = threadId2 ? await memory?.getThreadById({
1266
- threadId: threadId2
1267
- }) : void 0;
1268
- if (memory && resourceId && thread) {
1269
- try {
1270
- const userMessage = this.getMostRecentUserMessage(messages);
1271
- const newMessages = userMessage ? [userMessage] : messages;
1272
- const threadMessages = newMessages.map(u => {
1273
- return {
1274
- id: this.getMemory()?.generateId(),
1275
- createdAt: /* @__PURE__ */new Date(),
1276
- threadId: thread.id,
1277
- ...u,
1278
- content: u.content,
1279
- role: u.role,
1280
- type: "text"
1281
- };
1282
- });
1283
- await Promise.all([(async () => {
1284
- await memory.saveMessages({
1285
- messages: threadMessages,
1286
- memoryConfig: memoryConfig2
1287
- });
1288
- await this.saveResponse({
1289
- result,
1290
- threadId: threadId2,
1291
- resourceId,
1292
- memoryConfig: memoryConfig2,
1293
- runId: runId2
1294
- });
1295
- })(), (async () => {
1296
- if (!thread.title?.startsWith("New Thread")) {
1297
- return;
1298
- }
1299
- const config = memory.getMergedThreadConfig(memoryConfig2);
1300
- const title = config?.threads?.generateTitle ? await this.genTitle(userMessage) : void 0;
1301
- if (!title) {
1302
- return;
1303
- }
1304
- return memory.createThread({
1305
- threadId: thread.id,
1306
- resourceId,
1307
- memoryConfig: memoryConfig2,
1308
- title
1309
- });
1310
- })()]);
1311
- } catch (e) {
1312
- this.logger.error("Error saving response", {
1313
- error: e,
1314
- runId: runId2,
1315
- result: resToLog,
1316
- threadId: threadId2
1317
- });
1318
- }
1319
- }
1320
- if (Object.keys(this.evals || {}).length > 0) {
1321
- const input = messages.map(message => message.content).join("\n");
1322
- const runIdToUse = runId2 || crypto.randomUUID();
1323
- for (const metric of Object.values(this.evals || {})) {
1324
- executeHook("onGeneration" /* ON_GENERATION */, {
1325
- input,
1326
- output: outputText,
1327
- runId: runIdToUse,
1328
- metric,
1329
- agentName: this.name,
1330
- instructions: instructions || this.instructions
1331
- });
1332
- }
1333
- }
1334
- }
1335
- };
1336
- }
1337
- async generate(messages, {
1338
- instructions,
1339
- context,
1340
- threadId: threadIdInFn,
1341
- memoryOptions,
1342
- resourceId,
1343
- maxSteps = 5,
1344
- onStepFinish,
1345
- runId,
1346
- output,
1347
- toolsets,
1348
- temperature,
1349
- toolChoice = "auto",
1350
- experimental_output,
1351
- telemetry,
1352
- ...rest
1353
- } = {}) {
1354
- let messagesToUse = [];
1355
- if (typeof messages === `string`) {
1356
- messagesToUse = [{
1357
- role: "user",
1358
- content: messages
1359
- }];
1360
- } else if (Array.isArray(messages)) {
1361
- messagesToUse = messages.map(message => {
1362
- if (typeof message === `string`) {
1363
- return {
1364
- role: "user",
1365
- content: message
1366
- };
1367
- }
1368
- return message;
1369
- });
1370
- } else {
1371
- messagesToUse = [messages];
1372
- }
1373
- const runIdToUse = runId || randomUUID();
1374
- const {
1375
- before,
1376
- after
1377
- } = this.__primitive({
1378
- instructions,
1379
- messages: messagesToUse,
1380
- context,
1381
- threadId: threadIdInFn,
1382
- memoryConfig: memoryOptions,
1383
- resourceId,
1384
- runId: runIdToUse,
1385
- toolsets
1386
- });
1387
- const {
1388
- threadId,
1389
- messageObjects,
1390
- convertedTools
1391
- } = await before();
1392
- if (!output && experimental_output) {
1393
- const result2 = await this.llm.__text({
1394
- messages: messageObjects,
1395
- tools: this.tools,
1396
- convertedTools,
1397
- onStepFinish: result3 => {
1398
- void onStepFinish?.(result3);
1399
- },
1400
- maxSteps: maxSteps || 5,
1401
- runId: runIdToUse,
1402
- temperature,
1403
- toolChoice: toolChoice || "auto",
1404
- experimental_output,
1405
- threadId,
1406
- resourceId,
1407
- memory: this.getMemory(),
1408
- ...rest
1409
- });
1410
- const outputText2 = result2.text;
1411
- await after({
1412
- result: result2,
1413
- threadId,
1414
- memoryConfig: memoryOptions,
1415
- outputText: outputText2,
1416
- runId: runIdToUse
1417
- });
1418
- const newResult = result2;
1419
- newResult.object = result2.experimental_output;
1420
- return newResult;
1421
- }
1422
- if (!output) {
1423
- const result2 = await this.llm.__text({
1424
- messages: messageObjects,
1425
- tools: this.tools,
1426
- convertedTools,
1427
- onStepFinish: result3 => {
1428
- void onStepFinish?.(result3);
1429
- },
1430
- maxSteps,
1431
- runId: runIdToUse,
1432
- temperature,
1433
- toolChoice,
1434
- telemetry,
1435
- threadId,
1436
- resourceId,
1437
- memory: this.getMemory(),
1438
- ...rest
1439
- });
1440
- const outputText2 = result2.text;
1441
- await after({
1442
- result: result2,
1443
- threadId,
1444
- memoryConfig: memoryOptions,
1445
- outputText: outputText2,
1446
- runId: runIdToUse
1447
- });
1448
- return result2;
1449
- }
1450
- const result = await this.llm.__textObject({
1451
- messages: messageObjects,
1452
- tools: this.tools,
1453
- structuredOutput: output,
1454
- convertedTools,
1455
- onStepFinish: result2 => {
1456
- void onStepFinish?.(result2);
1457
- },
1458
- maxSteps,
1459
- runId: runIdToUse,
1460
- temperature,
1461
- toolChoice,
1462
- telemetry,
1463
- memory: this.getMemory(),
1464
- ...rest
1465
- });
1466
- const outputText = JSON.stringify(result.object);
1467
- await after({
1468
- result,
1469
- threadId,
1470
- memoryConfig: memoryOptions,
1471
- outputText,
1472
- runId: runIdToUse
1473
- });
1474
- return result;
1475
- }
1476
- async stream(messages, {
1477
- instructions,
1478
- context,
1479
- threadId: threadIdInFn,
1480
- memoryOptions,
1481
- resourceId,
1482
- maxSteps = 5,
1483
- onFinish,
1484
- onStepFinish,
1485
- runId,
1486
- toolsets,
1487
- output,
1488
- temperature,
1489
- toolChoice = "auto",
1490
- experimental_output,
1491
- telemetry,
1492
- ...rest
1493
- } = {}) {
1494
- const runIdToUse = runId || randomUUID();
1495
- let messagesToUse = [];
1496
- if (typeof messages === `string`) {
1497
- messagesToUse = [{
1498
- role: "user",
1499
- content: messages
1500
- }];
1501
- } else {
1502
- messagesToUse = messages.map(message => {
1503
- if (typeof message === `string`) {
1504
- return {
1505
- role: "user",
1506
- content: message
1507
- };
1508
- }
1509
- return message;
1510
- });
1511
- }
1512
- const {
1513
- before,
1514
- after
1515
- } = this.__primitive({
1516
- instructions,
1517
- messages: messagesToUse,
1518
- context,
1519
- threadId: threadIdInFn,
1520
- memoryConfig: memoryOptions,
1521
- resourceId,
1522
- runId: runIdToUse,
1523
- toolsets
1524
- });
1525
- const {
1526
- threadId,
1527
- messageObjects,
1528
- convertedTools
1529
- } = await before();
1530
- if (!output && experimental_output) {
1531
- this.logger.debug(`Starting agent ${this.name} llm stream call`, {
1532
- runId
1533
- });
1534
- const streamResult = await this.llm.__stream({
1535
- messages: messageObjects,
1536
- temperature,
1537
- tools: this.tools,
1538
- convertedTools,
1539
- onStepFinish: result => {
1540
- void onStepFinish?.(result);
1541
- },
1542
- onFinish: async result => {
1543
- try {
1544
- const outputText = result.text;
1545
- await after({
1546
- result,
1547
- threadId,
1548
- memoryConfig: memoryOptions,
1549
- outputText,
1550
- runId: runIdToUse
1551
- });
1552
- } catch (e) {
1553
- this.logger.error("Error saving memory on finish", {
1554
- error: e,
1555
- runId
1556
- });
1557
- }
1558
- void onFinish?.(result);
1559
- },
1560
- maxSteps,
1561
- runId: runIdToUse,
1562
- toolChoice,
1563
- experimental_output,
1564
- memory: this.getMemory(),
1565
- ...rest
1566
- });
1567
- const newStreamResult = streamResult;
1568
- newStreamResult.partialObjectStream = streamResult.experimental_partialOutputStream;
1569
- return newStreamResult;
1570
- } else if (!output) {
1571
- this.logger.debug(`Starting agent ${this.name} llm stream call`, {
1572
- runId
1573
- });
1574
- return this.llm.__stream({
1575
- messages: messageObjects,
1576
- temperature,
1577
- tools: this.tools,
1578
- convertedTools,
1579
- onStepFinish: result => {
1580
- void onStepFinish?.(result);
1581
- },
1582
- onFinish: async result => {
1583
- try {
1584
- const outputText = result.text;
1585
- await after({
1586
- result,
1587
- threadId,
1588
- memoryConfig: memoryOptions,
1589
- outputText,
1590
- runId: runIdToUse
1591
- });
1592
- } catch (e) {
1593
- this.logger.error("Error saving memory on finish", {
1594
- error: e,
1595
- runId
1596
- });
1597
- }
1598
- void onFinish?.(result);
1599
- },
1600
- maxSteps,
1601
- runId: runIdToUse,
1602
- toolChoice,
1603
- telemetry,
1604
- memory: this.getMemory(),
1605
- ...rest
1606
- });
1607
- }
1608
- this.logger.debug(`Starting agent ${this.name} llm streamObject call`, {
1609
- runId
1610
- });
1611
- return this.llm.__streamObject({
1612
- messages: messageObjects,
1613
- tools: this.tools,
1614
- temperature,
1615
- structuredOutput: output,
1616
- convertedTools,
1617
- onStepFinish: result => {
1618
- void onStepFinish?.(result);
1619
- },
1620
- onFinish: async result => {
1621
- try {
1622
- const outputText = JSON.stringify(result.object);
1623
- await after({
1624
- result,
1625
- threadId,
1626
- memoryConfig: memoryOptions,
1627
- outputText,
1628
- runId: runIdToUse
1629
- });
1630
- } catch (e) {
1631
- this.logger.error("Error saving memory on finish", {
1632
- error: e,
1633
- runId
1634
- });
1635
- }
1636
- void onFinish?.(result);
1637
- },
1638
- runId: runIdToUse,
1639
- toolChoice,
1640
- telemetry,
1641
- memory: this.getMemory(),
1642
- ...rest
1643
- });
1644
- }
1645
- /**
1646
- * Convert text to speech using the configured voice provider
1647
- * @param input Text or text stream to convert to speech
1648
- * @param options Speech options including speaker and provider-specific options
1649
- * @returns Audio stream
1650
- * @deprecated Use agent.voice.speak() instead
1651
- */
1652
- async speak(input, options) {
1653
- if (!this.voice) {
1654
- throw new Error("No voice provider configured");
1655
- }
1656
- this.logger.warn("Warning: agent.speak() is deprecated. Please use agent.voice.speak() instead.");
1657
- try {
1658
- return this.voice.speak(input, options);
1659
- } catch (e) {
1660
- this.logger.error("Error during agent speak", {
1661
- error: e
1662
- });
1663
- throw e;
1664
- }
1665
- }
1666
- /**
1667
- * Convert speech to text using the configured voice provider
1668
- * @param audioStream Audio stream to transcribe
1669
- * @param options Provider-specific transcription options
1670
- * @returns Text or text stream
1671
- * @deprecated Use agent.voice.listen() instead
1672
- */
1673
- async listen(audioStream, options) {
1674
- if (!this.voice) {
1675
- throw new Error("No voice provider configured");
1676
- }
1677
- this.logger.warn("Warning: agent.listen() is deprecated. Please use agent.voice.listen() instead");
1678
- try {
1679
- return this.voice.listen(audioStream, options);
1680
- } catch (e) {
1681
- this.logger.error("Error during agent listen", {
1682
- error: e
1683
- });
1684
- throw e;
1685
- }
1686
- }
1687
- /**
1688
- * Get a list of available speakers from the configured voice provider
1689
- * @throws {Error} If no voice provider is configured
1690
- * @returns {Promise<Array<{voiceId: string}>>} List of available speakers
1691
- * @deprecated Use agent.voice.getSpeakers() instead
1692
- */
1693
- async getSpeakers() {
1694
- if (!this.voice) {
1695
- throw new Error("No voice provider configured");
1696
- }
1697
- this.logger.warn("Warning: agent.getSpeakers() is deprecated. Please use agent.voice.getSpeakers() instead.");
1698
- try {
1699
- return await this.voice.getSpeakers();
1700
- } catch (e) {
1701
- this.logger.error("Error during agent getSpeakers", {
1702
- error: e
1703
- });
1704
- throw e;
1705
- }
1706
- }
1707
- };
1708
- Agent = /*@__PURE__*/(_ => {
1709
- _init = __decoratorStart(_a);
1710
- Agent = __decorateElement(_init, 0, "Agent", _Agent_decorators, Agent);
1711
- __runInitializers(_init, 1, Agent);
1712
- return Agent;
1713
- })();
1714
-
1715
- export { Agent };