@statelyai/agent 1.1.5 → 2.0.0-next.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 (54) hide show
  1. package/.changeset/light-hats-drive.md +9 -0
  2. package/.changeset/pre.json +10 -0
  3. package/.vscode/launch.json +6 -0
  4. package/CHANGELOG.md +17 -0
  5. package/dist/index.d.mts +262 -165
  6. package/dist/index.d.ts +262 -165
  7. package/dist/index.js +368 -258
  8. package/dist/index.mjs +371 -256
  9. package/examples/chatbot-alt.ts +57 -0
  10. package/examples/chatbot.ts +11 -16
  11. package/examples/cot.ts +25 -22
  12. package/examples/customer-service-sim.ts +107 -0
  13. package/examples/email.ts +14 -14
  14. package/examples/example.ts +5 -5
  15. package/examples/executor.ts +66 -0
  16. package/examples/goal.ts +11 -11
  17. package/examples/helpers/helpers.ts +26 -14
  18. package/examples/joke.ts +78 -75
  19. package/examples/jugs.ts +125 -0
  20. package/examples/multi.ts +4 -4
  21. package/examples/newspaper.ts +98 -104
  22. package/examples/number.ts +5 -4
  23. package/examples/raffle.ts +10 -11
  24. package/examples/river-crossing.ts +140 -0
  25. package/examples/sandbox.ts +1 -1
  26. package/examples/simple.ts +4 -2
  27. package/examples/summary.ts +121 -0
  28. package/examples/support.ts +5 -5
  29. package/examples/ticTacToe.ts +86 -45
  30. package/examples/todo.ts +6 -6
  31. package/examples/tutor.ts +13 -13
  32. package/examples/verify.ts +2 -2
  33. package/examples/weather.ts +5 -8
  34. package/examples/wiki.ts +26 -7
  35. package/examples/word.ts +15 -10
  36. package/package.json +15 -12
  37. package/readme.md +1 -1
  38. package/src/agent-experimental.ts +1 -1
  39. package/src/agent.test.ts +117 -228
  40. package/src/agent.ts +469 -81
  41. package/src/{decision.test.ts → decide.test.ts} +26 -50
  42. package/src/decide.ts +153 -0
  43. package/src/index.ts +1 -1
  44. package/src/middleware.ts +103 -0
  45. package/src/mockModel.ts +47 -0
  46. package/src/planners/shortestPathPlanner.ts +151 -13
  47. package/src/planners/simplePlanner.ts +57 -85
  48. package/src/strategies/chain-of-note.ts +6 -55
  49. package/src/text.ts +51 -139
  50. package/src/types.ts +172 -204
  51. package/src/utils.ts +37 -4
  52. package/src/adapters/vercel.ts +0 -7
  53. package/src/decision.ts +0 -84
  54. package/src/memory.ts +0 -25
package/src/types.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  ActorLogic,
3
- ActorRefFrom,
4
- AnyActorRef,
3
+ ActorRefLike,
5
4
  AnyEventObject,
6
5
  AnyStateMachine,
7
6
  EventFrom,
@@ -9,29 +8,32 @@ import {
9
8
  PromiseActorLogic,
10
9
  SnapshotFrom,
11
10
  StateValue,
12
- Subscription,
13
11
  TransitionSnapshot,
14
12
  Values,
15
13
  } from 'xstate';
16
14
  import {
17
15
  CoreMessage,
18
- CoreTool,
16
+ GenerateObjectResult,
19
17
  generateText,
20
18
  GenerateTextResult,
21
19
  LanguageModel,
22
20
  streamText,
23
- StreamTextResult,
24
21
  } from 'ai';
25
22
  import { ZodContextMapping, ZodEventMapping } from './schemas';
26
23
  import { TypeOf } from 'zod';
24
+ import { Agent } from './agent';
27
25
 
28
26
  export type GenerateTextOptions = Parameters<typeof generateText>[0];
29
27
 
30
28
  export type StreamTextOptions = Parameters<typeof streamText>[0];
31
29
 
30
+ export type CostFunction<TEvent extends EventObject> = (
31
+ path: AgentPath<TEvent>
32
+ ) => number;
33
+
32
34
  export type AgentPlanInput<TEvent extends EventObject> = Omit<
33
35
  GenerateTextOptions,
34
- 'prompt' | 'messages' | 'tools'
36
+ 'prompt' | 'tools'
35
37
  > & {
36
38
  /**
37
39
  * The currently observed state.
@@ -56,20 +58,51 @@ export type AgentPlanInput<TEvent extends EventObject> = Omit<
56
58
  * The previous plan.
57
59
  */
58
60
  previousPlan?: AgentPlan<TEvent>;
61
+
62
+ /**
63
+ * The total cost of the path to the goal state.
64
+ */
65
+ costFunction?: CostFunction<TEvent>;
66
+ };
67
+
68
+ export type AgentStep<TEvent extends EventObject> = {
69
+ /** The event to take */
70
+ event: TEvent;
71
+ /** The next expected state after taking the event */
72
+ state: ObservedState | undefined;
73
+ };
74
+
75
+ export type AgentPath<TEvent extends EventObject> = {
76
+ /** The expected ending state of the path */
77
+ state: ObservedState | undefined;
78
+ /** The steps to reach the ending state */
79
+ steps: Array<AgentStep<TEvent>>;
80
+ weight?: number;
59
81
  };
60
82
 
61
83
  export type AgentPlan<TEvent extends EventObject> = {
84
+ /**
85
+ * The planner used to generate the plan
86
+ */
87
+ planner: string;
62
88
  goal: string;
63
- state: ObservedState;
64
- content?: string;
65
89
  /**
66
- * Executes the plan based on the given `state` and resolves with
67
- * a potential next `event` to trigger to achieve the `goal`.
90
+ * The ending state of the plan.
91
+ */
92
+ goalState: ObservedState | undefined;
93
+ /**
94
+ * The next event that the agent decided needs to occur to achieve the `goal`.
95
+ *
96
+ * This next event is chosen from the
68
97
  */
69
- execute: (state: ObservedState) => Promise<TEvent | undefined>;
70
98
  nextEvent: TEvent | undefined;
71
- sessionId: string;
99
+ /**
100
+ * The paths that the agent can take to achieve the goal.
101
+ */
102
+ paths: AgentPath<TEvent>[];
103
+ episodeId: string;
72
104
  timestamp: number;
105
+ // result: GenerateObjectResult<any>;
73
106
  };
74
107
 
75
108
  export interface TransitionData {
@@ -116,16 +149,12 @@ export type AgentPlanner<T extends AnyAgent> = (
116
149
  export type AgentDecideOptions = {
117
150
  goal: string;
118
151
  model?: LanguageModel;
119
- context?: any;
120
152
  state: ObservedState;
121
- machine: AnyStateMachine;
153
+ machine?: AnyStateMachine;
122
154
  execute?: (event: AnyEventObject) => Promise<void>;
123
155
  planner?: AgentPlanner<any>;
124
156
  events?: ZodEventMapping;
125
- } & Omit<
126
- Parameters<typeof generateText>[0],
127
- 'model' | 'tools' | 'prompt' | 'messages'
128
- >;
157
+ } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt'>;
129
158
 
130
159
  export interface AgentFeedback {
131
160
  goal?: string;
@@ -137,7 +166,7 @@ export interface AgentFeedback {
137
166
  attributes: Record<string, any>;
138
167
  reward: number;
139
168
  timestamp: number;
140
- sessionId: string;
169
+ episodeId: string;
141
170
  }
142
171
 
143
172
  export interface AgentFeedbackInput {
@@ -158,9 +187,122 @@ export type AgentMessage = CoreMessage & {
158
187
  */
159
188
  responseId?: string;
160
189
  result?: GenerateTextResult<any>;
161
- sessionId: string;
162
- correlationId: string;
163
- parentCorrelationId?: string;
190
+ episodeId: string;
191
+ };
192
+
193
+ type JSONObject = {
194
+ [key: string]: JSONValue;
195
+ };
196
+ type JSONArray = JSONValue[];
197
+ type JSONValue = null | string | number | boolean | JSONObject | JSONArray;
198
+
199
+ type LanguageModelV1ProviderMetadata = Record<
200
+ string,
201
+ Record<string, JSONValue>
202
+ >;
203
+
204
+ interface LanguageModelV1ImagePart {
205
+ type: 'image';
206
+ /**
207
+ Image data as a Uint8Array (e.g. from a Blob or Buffer) or a URL.
208
+ */
209
+ image: Uint8Array | URL;
210
+ /**
211
+ Optional mime type of the image.
212
+ */
213
+ mimeType?: string;
214
+ /**
215
+ * Additional provider-specific metadata. They are passed through
216
+ * to the provider from the AI SDK and enable provider-specific
217
+ * functionality that can be fully encapsulated in the provider.
218
+ */
219
+ providerMetadata?: LanguageModelV1ProviderMetadata;
220
+ }
221
+
222
+ export interface LanguageModelV1TextPart {
223
+ type: 'text';
224
+ /**
225
+ The text content.
226
+ */
227
+ text: string;
228
+ /**
229
+ * Additional provider-specific metadata. They are passed through
230
+ * to the provider from the AI SDK and enable provider-specific
231
+ * functionality that can be fully encapsulated in the provider.
232
+ */
233
+ providerMetadata?: LanguageModelV1ProviderMetadata;
234
+ }
235
+
236
+ export interface LanguageModelV1ToolCallPart {
237
+ type: 'tool-call';
238
+ /**
239
+ ID of the tool call. This ID is used to match the tool call with the tool result.
240
+ */
241
+ toolCallId: string;
242
+ /**
243
+ Name of the tool that is being called.
244
+ */
245
+ toolName: string;
246
+ /**
247
+ Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
248
+ */
249
+ args: unknown;
250
+ /**
251
+ * Additional provider-specific metadata. They are passed through
252
+ * to the provider from the AI SDK and enable provider-specific
253
+ * functionality that can be fully encapsulated in the provider.
254
+ */
255
+ providerMetadata?: LanguageModelV1ProviderMetadata;
256
+ }
257
+ interface LanguageModelV1ToolResultPart {
258
+ type: 'tool-result';
259
+ /**
260
+ ID of the tool call that this result is associated with.
261
+ */
262
+ toolCallId: string;
263
+ /**
264
+ Name of the tool that generated this result.
265
+ */
266
+ toolName: string;
267
+ /**
268
+ Result of the tool call. This is a JSON-serializable object.
269
+ */
270
+ result: unknown;
271
+ /**
272
+ Optional flag if the result is an error or an error message.
273
+ */
274
+ isError?: boolean;
275
+ /**
276
+ * Additional provider-specific metadata. They are passed through
277
+ * to the provider from the AI SDK and enable provider-specific
278
+ * functionality that can be fully encapsulated in the provider.
279
+ */
280
+ providerMetadata?: LanguageModelV1ProviderMetadata;
281
+ }
282
+ type LanguageModelV1Message = (
283
+ | {
284
+ role: 'system';
285
+ content: string;
286
+ }
287
+ | {
288
+ role: 'user';
289
+ content: Array<LanguageModelV1TextPart | LanguageModelV1ImagePart>;
290
+ }
291
+ | {
292
+ role: 'assistant';
293
+ content: Array<LanguageModelV1TextPart | LanguageModelV1ToolCallPart>;
294
+ }
295
+ | {
296
+ role: 'tool';
297
+ content: Array<LanguageModelV1ToolResultPart>;
298
+ }
299
+ ) & {
300
+ /**
301
+ * Additional provider-specific metadata. They are passed through
302
+ * to the provider from the AI SDK and enable provider-specific
303
+ * functionality that can be fully encapsulated in the provider.
304
+ */
305
+ providerMetadata?: LanguageModelV1ProviderMetadata;
164
306
  };
165
307
 
166
308
  export type AgentMessageInput = CoreMessage & {
@@ -176,20 +318,20 @@ export type AgentMessageInput = CoreMessage & {
176
318
  result?: GenerateTextResult<any>;
177
319
  };
178
320
 
179
- export interface AgentObservation<TActor extends AnyActorRef> {
321
+ export interface AgentObservation<TActor extends ActorRefLike> {
180
322
  id: string;
181
323
  prevState: SnapshotFrom<TActor> | undefined;
182
- event: EventFrom<TActor>;
324
+ event: EventFrom<TActor> | undefined;
183
325
  state: SnapshotFrom<TActor>;
184
326
  machineHash: string | undefined;
185
- sessionId: string;
327
+ episodeId: string;
186
328
  timestamp: number;
187
329
  }
188
330
 
189
331
  export interface AgentObservationInput {
190
332
  id?: string;
191
- prevState: ObservedState | undefined;
192
- event: AnyEventObject;
333
+ prevState?: ObservedState;
334
+ event?: AnyEventObject;
193
335
  state: ObservedState;
194
336
  machine?: AnyStateMachine;
195
337
  timestamp?: number;
@@ -198,7 +340,7 @@ export interface AgentObservationInput {
198
340
  export type AgentDecisionInput = {
199
341
  goal: string;
200
342
  model?: LanguageModel;
201
- context?: any;
343
+ context?: Record<string, any>;
202
344
  } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt'>;
203
345
 
204
346
  export type AgentDecisionLogic<TEvents extends EventObject> = PromiseActorLogic<
@@ -260,150 +402,6 @@ export type ContextFromZodContextMapping<
260
402
  [K in keyof TContextSchema & string]: TypeOf<TContextSchema[K]>;
261
403
  };
262
404
 
263
- export type Agent<TContext, TEvents extends EventObject> = ActorRefFrom<
264
- AgentLogic<TEvents>
265
- > & {
266
- /**
267
- * The name of the agent. All agents with the same name are related and
268
- * able to share experiences (observations, feedback) with each other.
269
- */
270
- name?: string;
271
- /**
272
- * The unique identifier for the agent.
273
- */
274
- id?: string;
275
- description?: string;
276
- events: ZodEventMapping;
277
- types: {
278
- events: TEvents;
279
- context: Compute<TContext>;
280
- };
281
- model: LanguageModel;
282
- defaultOptions: GenerateTextOptions;
283
- memory: AgentLongTermMemory | undefined;
284
- /**
285
- * The adapter used to perform LLM actions such as
286
- * `.generateText(…)` and `.streamText(…)`.
287
- *
288
- * Defaults to the Vercel AI SDK.
289
- */
290
- adapter: AIAdapter;
291
-
292
- /**
293
- * Resolves with an `AgentPlan` based on the information provided in the `options`, including:
294
- *
295
- * - The `goal` for the agent to achieve
296
- * - The observed current `state`
297
- * - The `machine` (e.g. a state machine) that specifies what can happen next
298
- * - Additional `context`
299
- */
300
- decide: (
301
- options: AgentDecideOptions
302
- ) => Promise<AgentPlan<TEvents> | undefined>;
303
-
304
- // Generate text
305
- generateText: (
306
- options: AgentGenerateTextOptions
307
- ) => Promise<AgentGenerateTextResult>;
308
-
309
- // Stream text
310
- streamText: (
311
- options: AgentStreamTextOptions
312
- ) => Promise<AgentStreamTextResult>;
313
-
314
- addObservation: (
315
- observationInput: AgentObservationInput
316
- ) => AgentObservation<any>; // TODO
317
- addMessage: (messageInput: AgentMessageInput) => AgentMessage;
318
- addFeedback: (feedbackInput: AgentFeedbackInput) => AgentFeedback;
319
- addPlan: (plan: AgentPlan<TEvents>) => void;
320
- /**
321
- * Called whenever the agent (LLM assistant) receives or sends a message.
322
- */
323
- onMessage: (callback: (message: AgentMessage) => void) => void;
324
- /**
325
- * Selects agent data from its context.
326
- *
327
- * @deprecated Select from `agent.getSnapshot().context` directly or:
328
- * - `agent.getMessages()`
329
- * - `agent.getObservations()`
330
- * - `agent.getFeedback()`
331
- * - `agent.getPlans()`
332
- */
333
- select: <T>(selector: (context: AgentMemoryContext) => T) => T;
334
-
335
- /**
336
- * Retrieves messages from the agent's short-term (local) memory.
337
- */
338
- getMessages: () => AgentMessage[];
339
-
340
- /**
341
- * Retrieves observations from the agent's short-term (local) memory.
342
- */
343
- getObservations: () => AgentObservation<Agent<TContext, TEvents>>[];
344
-
345
- /**
346
- * Retrieves feedback from the agent's short-term (local) memory.
347
- */
348
- getFeedback: () => AgentFeedback[];
349
-
350
- /**
351
- * Retrieves strategies from the agent's short-term (local) memory.
352
- */
353
- getPlans: () => AgentPlan<TEvents>[];
354
-
355
- /**
356
- * Interacts with this state machine actor by inspecting state transitions and storing them as observations.
357
- *
358
- * Observations contain the `prevState`, `event`, and current `state` of this
359
- * actor, as well as other properties that are useful when recalled.
360
- * These observations are stored in the `agent`'s short-term (local) memory
361
- * and can be retrieved via `agent.getObservations()`.
362
- *
363
- * @example
364
- * ```ts
365
- * // Only observes the actor's state transitions
366
- * agent.interact(actor);
367
- *
368
- * actor.start();
369
- * ```
370
- */
371
- interact<TActor extends AnyActorRef>(actorRef: TActor): Subscription;
372
- /**
373
- * Interacts with this state machine actor by:
374
- * 1. Inspecting state transitions and storing them as observations
375
- * 2. Deciding what to do next (which event to send the actor) based on
376
- * the agent input returned from `getInput(observation)`, if `getInput(…)` is provided as the 2nd argument.
377
- *
378
- * Observations contain the `prevState`, `event`, and current `state` of this
379
- * actor, as well as other properties that are useful when recalled.
380
- * These observations are stored in the `agent`'s short-term (local) memory
381
- * and can be retrieved via `agent.getObservations()`.
382
- *
383
- * @example
384
- * ```ts
385
- * // Observes the actor's state transitions and
386
- * // makes a decision if on the "summarize" state
387
- * agent.interact(actor, observed => {
388
- * if (observed.state.matches('summarize')) {
389
- * return {
390
- * context: observed.state.context,
391
- * goal: 'Summarize the message'
392
- * }
393
- * }
394
- * });
395
- *
396
- * actor.start();
397
- * ```
398
- */
399
- interact<TActor extends AnyActorRef>(
400
- actorRef: TActor,
401
- getInput: (
402
- observation: AgentObservation<TActor>
403
- ) => AgentDecisionInput | undefined
404
- ): Subscription;
405
- };
406
-
407
405
  export type AnyAgent = Agent<any, any>;
408
406
 
409
407
  export type FromAgent<T> = T | ((agent: AnyAgent) => T | Promise<T>);
@@ -414,13 +412,6 @@ export type CommonTextOptions = {
414
412
  context?: Record<string, any>;
415
413
  messages?: FromAgent<CoreMessage[]>;
416
414
  template?: PromptTemplate<any>;
417
- correlationId?: string;
418
- parentCorrelationId?: string;
419
- };
420
-
421
- export type TextResultMeta = {
422
- correlationId: string;
423
- parentCorrelationId?: string;
424
415
  };
425
416
 
426
417
  export type AgentGenerateTextOptions = Omit<
@@ -429,16 +420,12 @@ export type AgentGenerateTextOptions = Omit<
429
420
  > &
430
421
  CommonTextOptions;
431
422
 
432
- export type AgentGenerateTextResult = GenerateTextResult<any> & TextResultMeta;
433
-
434
423
  export type AgentStreamTextOptions = Omit<
435
424
  StreamTextOptions,
436
425
  'model' | 'prompt' | 'messages'
437
426
  > &
438
427
  CommonTextOptions;
439
428
 
440
- export type AgentStreamTextResult = StreamTextResult<any> & TextResultMeta;
441
-
442
429
  export interface ObservedState {
443
430
  /**
444
431
  * The current state value of the state machine, e.g.
@@ -448,10 +435,10 @@ export interface ObservedState {
448
435
  /**
449
436
  * Additional contextual data related to the current state
450
437
  */
451
- context: Record<string, unknown>;
438
+ context?: Record<string, unknown>;
452
439
  }
453
440
 
454
- export type ObservedStateFrom<TActor extends AnyActorRef> = Pick<
441
+ export type ObservedStateFrom<TActor extends ActorRefLike> = Pick<
455
442
  SnapshotFrom<TActor>,
456
443
  'value' | 'context'
457
444
  >;
@@ -463,20 +450,6 @@ export type AgentMemoryContext = {
463
450
  feedback: AgentFeedback[];
464
451
  };
465
452
 
466
- export type AgentMemory = AppendOnlyStorage<AgentMemoryContext>;
467
-
468
- export interface AppendOnlyStorage<T extends Record<string, any[]>> {
469
- append<K extends keyof T>(
470
- sessionId: string,
471
- key: K,
472
- item: T[K][0]
473
- ): Promise<void>;
474
- getAll<K extends keyof T>(
475
- sessionId: string,
476
- key: K
477
- ): Promise<T[K] | undefined>;
478
- }
479
-
480
453
  export interface AgentLongTermMemory {
481
454
  get<K extends keyof AgentMemoryContext>(
482
455
  key: K
@@ -491,9 +464,4 @@ export interface AgentLongTermMemory {
491
464
  ): Promise<void>;
492
465
  }
493
466
 
494
- export interface AIAdapter {
495
- generateText: typeof generateText;
496
- streamText: typeof streamText;
497
- }
498
-
499
467
  export type Compute<A extends any> = { [K in keyof A]: A[K] } & unknown;
package/src/utils.ts CHANGED
@@ -1,6 +1,12 @@
1
- import { AnyMachineSnapshot, AnyStateMachine, AnyStateNode } from 'xstate';
1
+ import {
2
+ ActorRefLike,
3
+ AnyActorRef,
4
+ AnyMachineSnapshot,
5
+ AnyStateMachine,
6
+ AnyStateNode,
7
+ } from 'xstate';
2
8
  import hash from 'object-hash';
3
- import { TransitionData } from './types';
9
+ import { ObservedState, TransitionData } from './types';
4
10
 
5
11
  export function getAllTransitions(state: AnyMachineSnapshot): TransitionData[] {
6
12
  const nodes = state._nodes;
@@ -53,10 +59,11 @@ export function wrapInXml(tagName: string, content: string): string {
53
59
  return `<${tagName}>${content}</${tagName}>`;
54
60
  }
55
61
 
56
- export function randomId() {
62
+ export function randomId(prefix?: string): string {
57
63
  const timestamp = Date.now().toString(36);
58
64
  const random = Math.random().toString(36).substring(2, 9);
59
- return timestamp + random;
65
+ // return timestamp + random;
66
+ return `${prefix || ''}${timestamp}${random}`;
60
67
  }
61
68
 
62
69
  const machineHashes: WeakMap<AnyStateMachine, string> = new WeakMap();
@@ -70,3 +77,29 @@ export function getMachineHash(machine: AnyStateMachine): string {
70
77
  machineHashes.set(machine, machineHash);
71
78
  return machineHash;
72
79
  }
80
+
81
+ export function isActorRef(
82
+ actorRefLike: ActorRefLike
83
+ ): actorRefLike is AnyActorRef {
84
+ return (
85
+ 'src' in actorRefLike &&
86
+ 'system' in actorRefLike &&
87
+ 'sessionId' in actorRefLike
88
+ );
89
+ }
90
+
91
+ export function getTransitions(
92
+ state: ObservedState,
93
+ machine: AnyStateMachine
94
+ ): TransitionData[] {
95
+ if (!machine) {
96
+ return [];
97
+ }
98
+
99
+ const resolvedState = machine.resolveState({
100
+ ...state,
101
+ // Need this property defined to make TS happy
102
+ context: state.context,
103
+ });
104
+ return getAllTransitions(resolvedState);
105
+ }
@@ -1,7 +0,0 @@
1
- import { generateText, streamText } from 'ai';
2
- import { AIAdapter } from '../types';
3
-
4
- export const vercelAdapter: AIAdapter = {
5
- generateText,
6
- streamText,
7
- };
package/src/decision.ts DELETED
@@ -1,84 +0,0 @@
1
- import { AnyActor, AnyMachineSnapshot, fromPromise } from 'xstate';
2
- import {
3
- AnyAgent,
4
- AgentDecideOptions,
5
- AgentDecisionLogic,
6
- AgentDecisionInput,
7
- AgentPlanner,
8
- AgentPlan,
9
- } from './types';
10
- import { simplePlanner } from './planners/simplePlanner';
11
-
12
- export async function agentDecide<T extends AnyAgent>(
13
- agent: T,
14
- options: AgentDecideOptions
15
- ): Promise<AgentPlan<any> | undefined> {
16
- const resolvedOptions = {
17
- ...agent.defaultOptions,
18
- ...options,
19
- };
20
- const {
21
- planner = simplePlanner as AgentPlanner<any>,
22
- goal,
23
- events = agent.events,
24
- state,
25
- machine,
26
- model = agent.model,
27
- ...otherPlanInput
28
- } = resolvedOptions;
29
-
30
- const plan = await planner(agent, {
31
- model,
32
- goal,
33
- events,
34
- state,
35
- machine,
36
- ...otherPlanInput,
37
- });
38
-
39
- if (plan?.nextEvent) {
40
- agent.addPlan(plan);
41
- await resolvedOptions.execute?.(plan.nextEvent);
42
- }
43
-
44
- return plan;
45
- }
46
-
47
- export function fromDecision(
48
- agent: AnyAgent,
49
- defaultInput?: AgentDecisionInput
50
- ): AgentDecisionLogic<any> {
51
- return fromPromise(async ({ input, self }) => {
52
- const parentRef = self._parent;
53
- if (!parentRef) {
54
- return;
55
- }
56
-
57
- const snapshot = parentRef.getSnapshot() as AnyMachineSnapshot;
58
- const inputObject = typeof input === 'string' ? { goal: input } : input;
59
- const resolvedInput = {
60
- ...defaultInput,
61
- ...inputObject,
62
- };
63
- const contextToInclude =
64
- resolvedInput.context === true
65
- ? // include entire context
66
- parentRef.getSnapshot().context
67
- : resolvedInput.context;
68
- const state = {
69
- value: snapshot.value,
70
- context: contextToInclude,
71
- };
72
-
73
- const plan = await agentDecide(agent, {
74
- machine: (parentRef as AnyActor).logic,
75
- state,
76
- execute: async (event) => {
77
- parentRef.send(event);
78
- },
79
- ...resolvedInput,
80
- });
81
-
82
- return plan;
83
- }) as AgentDecisionLogic<any>;
84
- }
package/src/memory.ts DELETED
@@ -1,25 +0,0 @@
1
- import { AgentMemory, AgentMemoryContext } from './types';
2
-
3
- export function createAgentMemory(): AgentMemory {
4
- const storage = {
5
- sessions: {} as Record<string, AgentMemoryContext>,
6
- };
7
-
8
- return {
9
- append: async (sessionId, key, item) => {
10
- storage.sessions[sessionId] =
11
- storage.sessions[sessionId] ||
12
- ({
13
- observations: [],
14
- messages: [],
15
- plans: [],
16
- feedback: [],
17
- } satisfies AgentMemoryContext);
18
-
19
- storage.sessions[sessionId]![key].push(item as any);
20
- },
21
- getAll: async (sessionId, key) => {
22
- return storage.sessions[sessionId]?.[key];
23
- },
24
- };
25
- }