@statelyai/agent 1.1.6 → 2.0.0-alpha.10

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 (88) hide show
  1. package/LICENSE +21 -0
  2. package/dist/ai-sdk.cjs +342 -0
  3. package/dist/ai-sdk.d.cts +206 -0
  4. package/dist/ai-sdk.d.mts +206 -0
  5. package/dist/ai-sdk.mjs +331 -0
  6. package/dist/cli.cjs +64 -0
  7. package/dist/cli.d.cts +1 -0
  8. package/dist/cli.d.mts +1 -0
  9. package/dist/cli.mjs +65 -0
  10. package/dist/decision-CQdrKc8k.mjs +978 -0
  11. package/dist/decision-b-lkcs4L.cjs +1295 -0
  12. package/dist/index.cjs +59 -0
  13. package/dist/index.d.cts +212 -0
  14. package/dist/index.d.mts +201 -417
  15. package/dist/index.mjs +4 -588
  16. package/dist/openai-compat.cjs +319 -0
  17. package/dist/openai-compat.d.cts +98 -0
  18. package/dist/openai-compat.d.mts +98 -0
  19. package/dist/openai-compat.mjs +312 -0
  20. package/dist/run-agent-BFMkuI1F.cjs +1599 -0
  21. package/dist/run-agent-BVMd--1l.d.cts +1103 -0
  22. package/dist/run-agent-BoAOq_0Z.mjs +1540 -0
  23. package/dist/run-agent-DzYJb3CK.d.mts +1103 -0
  24. package/dist/src-D-77Ha5p.cjs +1087 -0
  25. package/dist/src-DUeIFjv-.mjs +1016 -0
  26. package/dist/text-logic-C7WJpCIc.d.mts +710 -0
  27. package/dist/text-logic-CZjyACzQ.d.cts +710 -0
  28. package/dist/types-C9QiMjre.d.cts +219 -0
  29. package/dist/types-qm00QF91.d.mts +219 -0
  30. package/dist/utils-Dri7aeEG.d.cts +108 -0
  31. package/dist/utils-Y6GDRGGE.d.mts +108 -0
  32. package/dist/zod.cjs +31 -0
  33. package/dist/zod.d.cts +30 -0
  34. package/dist/zod.d.mts +30 -0
  35. package/dist/zod.mjs +30 -0
  36. package/package.json +109 -28
  37. package/readme.md +143 -6
  38. package/schemas/agent-workflow.json +527 -0
  39. package/.changeset/README.md +0 -8
  40. package/.changeset/config.json +0 -11
  41. package/.env.template +0 -3
  42. package/.github/actions/ci-setup/action.yml +0 -24
  43. package/.github/workflows/release.yml +0 -46
  44. package/.vscode/launch.json +0 -28
  45. package/CHANGELOG.md +0 -222
  46. package/dist/index.d.ts +0 -428
  47. package/dist/index.js +0 -621
  48. package/examples/chatbot.ts +0 -71
  49. package/examples/cot.ts +0 -89
  50. package/examples/email.ts +0 -118
  51. package/examples/example.ts +0 -81
  52. package/examples/goal.ts +0 -94
  53. package/examples/helpers/helpers.ts +0 -17
  54. package/examples/helpers/loader.ts +0 -32
  55. package/examples/helpers/runner.ts +0 -27
  56. package/examples/joke.ts +0 -225
  57. package/examples/multi.ts +0 -103
  58. package/examples/newspaper.ts +0 -324
  59. package/examples/number.ts +0 -102
  60. package/examples/raffle.ts +0 -105
  61. package/examples/sandbox.ts +0 -28
  62. package/examples/simple.ts +0 -39
  63. package/examples/support.ts +0 -147
  64. package/examples/ticTacToe.ts +0 -224
  65. package/examples/todo.ts +0 -137
  66. package/examples/tutor.ts +0 -100
  67. package/examples/verify.ts +0 -120
  68. package/examples/weather.ts +0 -178
  69. package/examples/wiki.ts +0 -30
  70. package/examples/word.ts +0 -171
  71. package/src/adapters/vercel.ts +0 -7
  72. package/src/agent-experimental.ts +0 -221
  73. package/src/agent.test.ts +0 -506
  74. package/src/agent.ts +0 -300
  75. package/src/decision.test.ts +0 -179
  76. package/src/decision.ts +0 -84
  77. package/src/index.ts +0 -4
  78. package/src/memory.ts +0 -25
  79. package/src/planners/shortestPathPlanner.ts +0 -22
  80. package/src/planners/simplePlanner.ts +0 -139
  81. package/src/schemas.ts +0 -11
  82. package/src/strategies/chain-of-note.ts +0 -155
  83. package/src/templates/defaultText.ts +0 -18
  84. package/src/text.ts +0 -241
  85. package/src/types.ts +0 -499
  86. package/src/utils.ts +0 -72
  87. package/tsconfig.json +0 -109
  88. package/vitest.config.ts +0 -9
package/dist/index.js DELETED
@@ -1,621 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- createAgent: () => createAgent,
34
- fromDecision: () => fromDecision,
35
- fromText: () => fromText,
36
- fromTextStream: () => fromTextStream
37
- });
38
- module.exports = __toCommonJS(src_exports);
39
-
40
- // src/agent.ts
41
- var import_xstate3 = require("xstate");
42
-
43
- // src/planners/simplePlanner.ts
44
- var import_ai = require("ai");
45
-
46
- // src/utils.ts
47
- var import_object_hash = __toESM(require("object-hash"));
48
- function getAllTransitions(state) {
49
- const nodes = state._nodes;
50
- const transitions = nodes.map((node) => [...node.transitions.values()]).map((nodeTransitions) => {
51
- return nodeTransitions.map((nodeEventTransitions) => {
52
- return nodeEventTransitions.map((transition) => {
53
- return {
54
- ...transition,
55
- guard: typeof transition.guard === "string" ? { type: transition.guard } : transition.guard
56
- // TODO: fix
57
- };
58
- });
59
- });
60
- }).flat(2);
61
- return transitions;
62
- }
63
- function getAllMachineTransitions(stateNode) {
64
- const transitions = [...stateNode.transitions.values()].map((nodeTransitions) => {
65
- return nodeTransitions.map((transition) => {
66
- return {
67
- ...transition,
68
- guard: typeof transition.guard === "string" ? { type: transition.guard } : transition.guard
69
- // TODO: fix
70
- };
71
- });
72
- }).flat(2);
73
- for (const s of Object.values(stateNode.states)) {
74
- const stateTransitions = getAllMachineTransitions(s);
75
- transitions.push(...stateTransitions);
76
- }
77
- return transitions;
78
- }
79
- function wrapInXml(tagName, content) {
80
- return `<${tagName}>${content}</${tagName}>`;
81
- }
82
- function randomId() {
83
- const timestamp = Date.now().toString(36);
84
- const random = Math.random().toString(36).substring(2, 9);
85
- return timestamp + random;
86
- }
87
- var machineHashes = /* @__PURE__ */ new WeakMap();
88
- function getMachineHash(machine) {
89
- if (machineHashes.has(machine)) return machineHashes.get(machine);
90
- const transitions = getAllMachineTransitions(machine.root);
91
- const machineHash = (0, import_object_hash.default)(transitions);
92
- machineHashes.set(machine, machineHash);
93
- return machineHash;
94
- }
95
-
96
- // src/templates/defaultText.ts
97
- var defaultTextTemplate = (data) => {
98
- const preamble = [
99
- data.context ? wrapInXml("context", JSON.stringify(data.context)) : void 0
100
- ].filter(Boolean).join("\n");
101
- return `
102
- ${preamble}
103
-
104
- ${data.goal}
105
- `.trim();
106
- };
107
-
108
- // src/text.ts
109
- var import_xstate = require("xstate");
110
- async function getMessages(agent, prompt, options) {
111
- let messages = [];
112
- if (typeof options.messages === "function") {
113
- messages = await options.messages(agent);
114
- } else if (options.messages) {
115
- messages = options.messages;
116
- }
117
- messages = messages.concat({
118
- role: "user",
119
- content: prompt
120
- });
121
- return messages;
122
- }
123
- async function agentGenerateText(agent, options) {
124
- const resolvedOptions = {
125
- ...agent.defaultOptions,
126
- ...options,
127
- correlationId: options.correlationId ?? randomId()
128
- };
129
- const template = resolvedOptions.template ?? defaultTextTemplate;
130
- const id = randomId();
131
- const goal = typeof resolvedOptions.prompt === "string" ? resolvedOptions.prompt : await resolvedOptions.prompt(agent);
132
- const promptWithContext = template({
133
- goal,
134
- context: resolvedOptions.context
135
- });
136
- const messages = await getMessages(agent, promptWithContext, resolvedOptions);
137
- agent.addMessage({
138
- id,
139
- role: "user",
140
- content: promptWithContext,
141
- timestamp: Date.now(),
142
- correlationId: resolvedOptions.correlationId,
143
- parentCorrelationId: resolvedOptions.parentCorrelationId
144
- });
145
- const result = await agent.adapter.generateText({
146
- ...resolvedOptions,
147
- prompt: void 0,
148
- messages
149
- });
150
- agent.addMessage({
151
- content: result.text,
152
- id,
153
- role: "assistant",
154
- timestamp: Date.now(),
155
- responseId: id,
156
- result,
157
- correlationId: resolvedOptions.correlationId,
158
- parentCorrelationId: resolvedOptions.parentCorrelationId
159
- });
160
- return {
161
- ...result,
162
- parentCorrelationId: resolvedOptions.parentCorrelationId,
163
- correlationId: resolvedOptions.correlationId
164
- };
165
- }
166
- async function agentStreamText(agent, options) {
167
- const resolvedOptions = {
168
- ...agent.defaultOptions,
169
- ...options,
170
- correlationId: options.correlationId ?? randomId()
171
- };
172
- const template = resolvedOptions.template ?? defaultTextTemplate;
173
- const id = randomId();
174
- const goal = typeof resolvedOptions.prompt === "string" ? resolvedOptions.prompt : await resolvedOptions.prompt(agent);
175
- const promptWithContext = template({
176
- goal,
177
- context: resolvedOptions.context
178
- });
179
- const messages = await getMessages(agent, promptWithContext, resolvedOptions);
180
- agent.addMessage({
181
- role: "user",
182
- content: promptWithContext,
183
- id,
184
- timestamp: Date.now(),
185
- correlationId: resolvedOptions.correlationId,
186
- parentCorrelationId: resolvedOptions.parentCorrelationId
187
- });
188
- const result = await agent.adapter.streamText({
189
- ...resolvedOptions,
190
- prompt: void 0,
191
- messages,
192
- onFinish: async (res) => {
193
- agent.addMessage({
194
- role: "assistant",
195
- result: {
196
- text: res.text,
197
- finishReason: res.finishReason,
198
- logprobs: void 0,
199
- responseMessages: [],
200
- toolCalls: [],
201
- toolResults: [],
202
- usage: res.usage,
203
- warnings: res.warnings,
204
- rawResponse: res.rawResponse,
205
- roundtrips: [],
206
- // TODO: how do we get this information?,
207
- steps: res.steps,
208
- response: res.response,
209
- experimental_providerMetadata: res.experimental_providerMetadata
210
- },
211
- content: res.text,
212
- id: randomId(),
213
- timestamp: Date.now(),
214
- responseId: id,
215
- correlationId: resolvedOptions.correlationId,
216
- parentCorrelationId: resolvedOptions.parentCorrelationId
217
- });
218
- }
219
- });
220
- return {
221
- ...result,
222
- textStream: result.textStream,
223
- fullStream: result.fullStream,
224
- parentCorrelationId: resolvedOptions.parentCorrelationId,
225
- correlationId: resolvedOptions.correlationId
226
- };
227
- }
228
- function fromTextStream(agent, defaultOptions) {
229
- return (0, import_xstate.fromObservable)(({ input }) => {
230
- const observers = /* @__PURE__ */ new Set();
231
- (async () => {
232
- const result = await agentStreamText(agent, {
233
- ...defaultOptions,
234
- ...input,
235
- context: input.context
236
- });
237
- for await (const part of result.fullStream) {
238
- if (part.type === "text-delta") {
239
- observers.forEach((observer) => {
240
- observer.next?.(part);
241
- });
242
- }
243
- }
244
- })();
245
- return {
246
- subscribe: (...args) => {
247
- const observer = (0, import_xstate.toObserver)(...args);
248
- observers.add(observer);
249
- return {
250
- unsubscribe: () => {
251
- observers.delete(observer);
252
- }
253
- };
254
- }
255
- };
256
- });
257
- }
258
- function fromText(agent, defaultOptions) {
259
- return (0, import_xstate.fromPromise)(async ({ input }) => {
260
- return await agentGenerateText(agent, {
261
- ...input,
262
- ...defaultOptions,
263
- context: input.context
264
- });
265
- });
266
- }
267
-
268
- // src/planners/simplePlanner.ts
269
- function getTransitions(state, machine) {
270
- if (!machine) {
271
- return [];
272
- }
273
- const resolvedState = machine.resolveState(state);
274
- return getAllTransitions(resolvedState);
275
- }
276
- var simplePlannerPromptTemplate = (data) => {
277
- return `
278
- ${defaultTextTemplate(data)}
279
-
280
- Make at most one tool call to achieve the above goal. If the goal cannot be achieved with any tool calls, do not make any tool call.
281
- `.trim();
282
- };
283
- async function simplePlanner(agent, input) {
284
- const transitions = input.machine ? getTransitions(input.state, input.machine) : Object.entries(input.events).map(([eventType, { description }]) => ({
285
- eventType,
286
- description
287
- }));
288
- const filter = (eventType) => Object.keys(input.events).includes(eventType);
289
- const functionNameMapping = {};
290
- const toolTransitions = transitions.filter((t) => {
291
- return filter(t.eventType);
292
- }).map((t) => {
293
- const name = t.eventType.replace(/\./g, "_");
294
- functionNameMapping[name] = t.eventType;
295
- return {
296
- type: "function",
297
- eventType: t.eventType,
298
- description: t.description,
299
- name
300
- };
301
- });
302
- const toolMap = {};
303
- for (const toolTransitionData of toolTransitions) {
304
- const toolZodType = input.events?.[toolTransitionData.eventType];
305
- if (!toolZodType) {
306
- continue;
307
- }
308
- toolMap[toolTransitionData.name] = (0, import_ai.tool)({
309
- description: toolZodType?.description ?? toolTransitionData.description,
310
- parameters: toolZodType,
311
- execute: async (params) => {
312
- const event = {
313
- type: toolTransitionData.eventType,
314
- ...params
315
- };
316
- return event;
317
- }
318
- });
319
- }
320
- if (!Object.keys(toolMap).length) {
321
- return void 0;
322
- }
323
- const prompt = simplePlannerPromptTemplate({
324
- context: input.state.context,
325
- goal: input.goal
326
- });
327
- const messages = await getMessages(agent, prompt, input);
328
- const result = await agent.generateText({
329
- toolChoice: "required",
330
- ...input,
331
- prompt,
332
- messages,
333
- tools: toolMap
334
- });
335
- const singleResult = result.toolResults[0];
336
- if (!singleResult) {
337
- console.warn("No tool call results returned");
338
- return void 0;
339
- }
340
- return {
341
- goal: input.goal,
342
- state: input.state,
343
- execute: async (state) => {
344
- if (JSON.stringify(state) === JSON.stringify(input.state)) {
345
- return singleResult.result;
346
- }
347
- return void 0;
348
- },
349
- nextEvent: singleResult.result,
350
- sessionId: agent.sessionId,
351
- timestamp: Date.now()
352
- };
353
- }
354
-
355
- // src/decision.ts
356
- var import_xstate2 = require("xstate");
357
- async function agentDecide(agent, options) {
358
- const resolvedOptions = {
359
- ...agent.defaultOptions,
360
- ...options
361
- };
362
- const {
363
- planner = simplePlanner,
364
- goal,
365
- events = agent.events,
366
- state,
367
- machine,
368
- model = agent.model,
369
- ...otherPlanInput
370
- } = resolvedOptions;
371
- const plan = await planner(agent, {
372
- model,
373
- goal,
374
- events,
375
- state,
376
- machine,
377
- ...otherPlanInput
378
- });
379
- if (plan?.nextEvent) {
380
- agent.addPlan(plan);
381
- await resolvedOptions.execute?.(plan.nextEvent);
382
- }
383
- return plan;
384
- }
385
- function fromDecision(agent, defaultInput) {
386
- return (0, import_xstate2.fromPromise)(async ({ input, self }) => {
387
- const parentRef = self._parent;
388
- if (!parentRef) {
389
- return;
390
- }
391
- const snapshot = parentRef.getSnapshot();
392
- const inputObject = typeof input === "string" ? { goal: input } : input;
393
- const resolvedInput = {
394
- ...defaultInput,
395
- ...inputObject
396
- };
397
- const contextToInclude = resolvedInput.context === true ? (
398
- // include entire context
399
- parentRef.getSnapshot().context
400
- ) : resolvedInput.context;
401
- const state = {
402
- value: snapshot.value,
403
- context: contextToInclude
404
- };
405
- const plan = await agentDecide(agent, {
406
- machine: parentRef.logic,
407
- state,
408
- execute: async (event) => {
409
- parentRef.send(event);
410
- },
411
- ...resolvedInput
412
- });
413
- return plan;
414
- });
415
- }
416
-
417
- // src/adapters/vercel.ts
418
- var import_ai2 = require("ai");
419
- var vercelAdapter = {
420
- generateText: import_ai2.generateText,
421
- streamText: import_ai2.streamText
422
- };
423
-
424
- // src/agent.ts
425
- var agentLogic = (0, import_xstate3.fromTransition)(
426
- (state, event, { emit }) => {
427
- switch (event.type) {
428
- case "agent.feedback": {
429
- state.feedback.push(event.feedback);
430
- emit({
431
- type: "feedback",
432
- // @ts-ignore TODO: fix types in XState
433
- feedback: event.feedback
434
- });
435
- break;
436
- }
437
- case "agent.observe": {
438
- state.observations.push(event.observation);
439
- emit({
440
- type: "observation",
441
- // @ts-ignore TODO: fix types in XState
442
- observation: event.observation
443
- });
444
- break;
445
- }
446
- case "agent.message": {
447
- state.messages.push(event.message);
448
- emit({
449
- type: "message",
450
- // @ts-ignore TODO: fix types in XState
451
- message: event.message
452
- });
453
- break;
454
- }
455
- case "agent.plan": {
456
- state.plans.push(event.plan);
457
- emit({
458
- type: "plan",
459
- // @ts-ignore TODO: fix types in XState
460
- plan: event.plan
461
- });
462
- break;
463
- }
464
- default:
465
- break;
466
- }
467
- return state;
468
- },
469
- () => ({
470
- feedback: [],
471
- messages: [],
472
- observations: [],
473
- plans: []
474
- })
475
- );
476
- function createAgent({
477
- name,
478
- description,
479
- model,
480
- events,
481
- context,
482
- planner = simplePlanner,
483
- stringify = JSON.stringify,
484
- getMemory,
485
- logic = agentLogic,
486
- adapter = vercelAdapter,
487
- ...generateTextOptions
488
- }) {
489
- const agent = (0, import_xstate3.createActor)(logic);
490
- agent.events = events;
491
- agent.model = model;
492
- agent.name = name;
493
- agent.description = description;
494
- agent.adapter = adapter;
495
- agent.defaultOptions = { ...generateTextOptions, model };
496
- agent.select = (selector) => {
497
- return selector(agent.getSnapshot().context);
498
- };
499
- agent.memory = getMemory ? getMemory(agent) : void 0;
500
- agent.onMessage = (callback) => {
501
- agent.on("message", (ev) => callback(ev.message));
502
- };
503
- agent.decide = (opts) => {
504
- return agentDecide(agent, opts);
505
- };
506
- agent.addMessage = (messageInput) => {
507
- const message = {
508
- ...messageInput,
509
- id: messageInput.id ?? randomId(),
510
- timestamp: messageInput.timestamp ?? Date.now(),
511
- sessionId: agent.sessionId,
512
- correlationId: messageInput.correlationId ?? randomId()
513
- };
514
- agent.send({
515
- type: "agent.message",
516
- message
517
- });
518
- return message;
519
- };
520
- agent.getMessages = () => agent.getSnapshot().context.messages;
521
- agent.generateText = (opts) => agentGenerateText(agent, opts);
522
- agent.streamText = (opts) => agentStreamText(agent, opts);
523
- agent.addFeedback = (feedbackInput) => {
524
- const feedback = {
525
- ...feedbackInput,
526
- attributes: { ...feedbackInput.attributes },
527
- reward: feedbackInput.reward ?? 0,
528
- timestamp: feedbackInput.timestamp ?? Date.now(),
529
- sessionId: agent.sessionId
530
- };
531
- agent.send({
532
- type: "agent.feedback",
533
- feedback
534
- });
535
- return feedback;
536
- };
537
- agent.getFeedback = () => agent.getSnapshot().context.feedback;
538
- agent.addObservation = (observationInput) => {
539
- const { prevState, event, state } = observationInput;
540
- const observation = {
541
- prevState,
542
- event,
543
- state,
544
- id: observationInput.id ?? randomId(),
545
- sessionId: agent.sessionId,
546
- timestamp: observationInput.timestamp ?? Date.now(),
547
- machineHash: observationInput.machine ? getMachineHash(observationInput.machine) : void 0
548
- };
549
- agent.send({
550
- type: "agent.observe",
551
- observation
552
- });
553
- return observation;
554
- };
555
- agent.getObservations = () => agent.getSnapshot().context.observations;
556
- agent.addPlan = (plan) => {
557
- agent.send({
558
- type: "agent.plan",
559
- plan
560
- });
561
- };
562
- agent.getPlans = () => agent.getSnapshot().context.plans;
563
- agent.interact = (actorRef, getInput) => {
564
- let prevState = void 0;
565
- let subscribed = true;
566
- async function handleObservation(observationInput) {
567
- const observation = agent.addObservation(observationInput);
568
- const input = getInput?.(observation);
569
- if (input) {
570
- await agentDecide(agent, {
571
- machine: actorRef.src,
572
- state: observation.state,
573
- execute: async (event) => {
574
- actorRef.send(event);
575
- },
576
- ...input
577
- });
578
- }
579
- prevState = observationInput.state;
580
- }
581
- actorRef.system.inspect({
582
- next: async (inspEvent) => {
583
- if (!subscribed || inspEvent.actorRef !== actorRef || inspEvent.type !== "@xstate.snapshot") {
584
- return;
585
- }
586
- const observationInput = {
587
- event: inspEvent.event,
588
- prevState,
589
- state: inspEvent.snapshot,
590
- machine: actorRef.src
591
- };
592
- await handleObservation(observationInput);
593
- }
594
- });
595
- if (actorRef._processingStatus === 1) {
596
- handleObservation({
597
- prevState: void 0,
598
- event: { type: "" },
599
- // TODO: unknown events?
600
- state: actorRef.getSnapshot(),
601
- machine: actorRef.src
602
- });
603
- }
604
- return {
605
- unsubscribe: () => {
606
- subscribed = false;
607
- }
608
- // TODO: make this actually unsubscribe
609
- };
610
- };
611
- agent.types = {};
612
- agent.start();
613
- return agent;
614
- }
615
- // Annotate the CommonJS export names for ESM import in node:
616
- 0 && (module.exports = {
617
- createAgent,
618
- fromDecision,
619
- fromText,
620
- fromTextStream
621
- });
@@ -1,71 +0,0 @@
1
- import { z } from 'zod';
2
- import { createAgent, fromDecision } from '../src';
3
- import { openai } from '@ai-sdk/openai';
4
- import { assign, createActor, log, setup } from 'xstate';
5
- import { getFromTerminal } from './helpers/helpers';
6
-
7
- const agent = createAgent({
8
- name: 'chatbot',
9
- model: openai('gpt-4-turbo'),
10
- events: {
11
- 'agent.respond': z.object({
12
- response: z.string().describe('The response from the agent'),
13
- }),
14
- 'agent.endConversation': z.object({}).describe('Stop the conversation'),
15
- },
16
- context: {
17
- userMessage: z.string(),
18
- },
19
- });
20
-
21
- const machine = setup({
22
- types: agent.types,
23
- actors: { agent: fromDecision(agent), getFromTerminal },
24
- }).createMachine({
25
- initial: 'listening',
26
- context: {
27
- userMessage: '',
28
- },
29
- states: {
30
- listening: {
31
- invoke: {
32
- src: 'getFromTerminal',
33
- input: 'User:',
34
- onDone: {
35
- actions: assign({
36
- userMessage: (x) => x.event.output,
37
- }),
38
- target: 'responding',
39
- },
40
- },
41
- },
42
- responding: {
43
- invoke: {
44
- src: 'agent',
45
- input: (x) => ({
46
- context: {
47
- userMessage: 'User says: ' + x.context.userMessage,
48
- },
49
- messages: agent.getMessages(),
50
- goal: 'Respond to the user, unless they want to end the conversation.',
51
- }),
52
- },
53
- on: {
54
- 'agent.respond': {
55
- actions: [log((x) => `Agent: ${x.event.response}`)],
56
- target: 'listening',
57
- },
58
- 'agent.endConversation': 'finished',
59
- },
60
- },
61
- finished: {
62
- type: 'final',
63
- },
64
- },
65
- exit: () => {
66
- console.log('End of conversation.');
67
- process.exit();
68
- },
69
- });
70
-
71
- createActor(machine).start();