@statelyai/agent 1.1.6 → 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 +10 -0
  5. package/dist/index.d.mts +262 -165
  6. package/dist/index.d.ts +262 -165
  7. package/dist/index.js +368 -263
  8. package/dist/index.mjs +371 -261
  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 +13 -10
  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 -144
  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
@@ -0,0 +1,9 @@
1
+ ---
2
+ '@statelyai/agent': major
3
+ ---
4
+
5
+ - `agent.generateText(…)` is removed in favor of using the AI SDK's `generateText(…)` function with a wrapped model.
6
+ - `agent.streamText(…)` is removed in favor of using the AI SDK's `streamText(…)` function with a wrapped model.
7
+ - Custom adapters are removed for now, but may be re-added in future releases. Using the AI SDK is recommended for now.
8
+ - Correlation IDs are removed in favor of using [OpenTelemetry with the AI SDK](https://sdk.vercel.ai/docs/ai-sdk-core/telemetry#telemetry).
9
+ - The `createAgentMiddleware(…)` function was introduced to facilitate agent message history. You can also use `agent.wrap(model)` to wrap a model with Stately Agent middleware.
@@ -0,0 +1,10 @@
1
+ {
2
+ "mode": "pre",
3
+ "tag": "next",
4
+ "initialVersions": {
5
+ "@statelyai/agent": "1.1.6"
6
+ },
7
+ "changesets": [
8
+ "light-hats-drive"
9
+ ]
10
+ }
@@ -20,8 +20,14 @@
20
20
  "program": "${file}",
21
21
  "cwd": "${workspaceFolder}",
22
22
  "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/ts-node",
23
+ "runtimeArgs": ["--transpile-only", "-r", "dotenv/config"],
23
24
  "outFiles": ["${workspaceFolder}/dist/**/*.js"],
24
25
  "sourceMaps": true,
26
+ "smartStep": true,
27
+ "resolveSourceMapLocations": [
28
+ "${workspaceFolder}/**",
29
+ "!**/node_modules/**"
30
+ ],
25
31
  "console": "integratedTerminal"
26
32
  }
27
33
  ]
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @statelyai/agent
2
2
 
3
+ ## 2.0.0-next.0
4
+
5
+ ### Major Changes
6
+
7
+ - [#51](https://github.com/statelyai/agent/pull/51) [`574b6fd`](https://github.com/statelyai/agent/commit/574b6fd62e8a41df311aa1ea00fae60c32ad595e) Thanks [@davidkpiano](https://github.com/davidkpiano)! - - `agent.generateText(…)` is removed in favor of using the AI SDK's `generateText(…)` function with a wrapped model.
8
+ - `agent.streamText(…)` is removed in favor of using the AI SDK's `streamText(…)` function with a wrapped model.
9
+ - Custom adapters are removed for now, but may be re-added in future releases. Using the AI SDK is recommended for now.
10
+ - Correlation IDs are removed in favor of using [OpenTelemetry with the AI SDK](https://sdk.vercel.ai/docs/ai-sdk-core/telemetry#telemetry).
11
+ - The `createAgentMiddleware(…)` function was introduced to facilitate agent message history. You can also use `agent.wrap(model)` to wrap a model with Stately Agent middleware.
12
+
3
13
  ## 1.1.6
4
14
 
5
15
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -1,6 +1,7 @@
1
- import { EventObject, AnyStateMachine, AnyEventObject, AnyActorRef, SnapshotFrom, EventFrom, PromiseActorLogic, ActorLogic, TransitionSnapshot, Values, ActorRefFrom, Subscription, StateValue, ObservableActorLogic } from 'xstate';
1
+ import * as ai from 'ai';
2
+ import { generateText, streamText, LanguageModel, CoreMessage, GenerateTextResult, LanguageModelV1, CoreTool } from 'ai';
3
+ import { EventObject, AnyStateMachine, AnyEventObject, ActorRefLike, SnapshotFrom, EventFrom, PromiseActorLogic, ActorLogic, TransitionSnapshot, Values, StateValue, Actor, Subscription, ObservableActorLogic } from 'xstate';
2
4
  import { SomeZodObject, ZodType, TypeOf } from 'zod';
3
- import { generateText, streamText, LanguageModel, CoreMessage, GenerateTextResult, StreamTextResult, CoreTool } from 'ai';
4
5
 
5
6
  type ZodEventMapping = {
6
7
  [eventType: string]: SomeZodObject;
@@ -11,7 +12,8 @@ type ZodContextMapping = {
11
12
 
12
13
  type GenerateTextOptions = Parameters<typeof generateText>[0];
13
14
  type StreamTextOptions = Parameters<typeof streamText>[0];
14
- type AgentPlanInput<TEvent extends EventObject> = Omit<GenerateTextOptions, 'prompt' | 'messages' | 'tools'> & {
15
+ type CostFunction<TEvent extends EventObject> = (path: AgentPath<TEvent>) => number;
16
+ type AgentPlanInput<TEvent extends EventObject> = Omit<GenerateTextOptions, 'prompt' | 'tools'> & {
15
17
  /**
16
18
  * The currently observed state.
17
19
  */
@@ -35,18 +37,45 @@ type AgentPlanInput<TEvent extends EventObject> = Omit<GenerateTextOptions, 'pro
35
37
  * The previous plan.
36
38
  */
37
39
  previousPlan?: AgentPlan<TEvent>;
40
+ /**
41
+ * The total cost of the path to the goal state.
42
+ */
43
+ costFunction?: CostFunction<TEvent>;
44
+ };
45
+ type AgentStep<TEvent extends EventObject> = {
46
+ /** The event to take */
47
+ event: TEvent;
48
+ /** The next expected state after taking the event */
49
+ state: ObservedState | undefined;
50
+ };
51
+ type AgentPath<TEvent extends EventObject> = {
52
+ /** The expected ending state of the path */
53
+ state: ObservedState | undefined;
54
+ /** The steps to reach the ending state */
55
+ steps: Array<AgentStep<TEvent>>;
56
+ weight?: number;
38
57
  };
39
58
  type AgentPlan<TEvent extends EventObject> = {
59
+ /**
60
+ * The planner used to generate the plan
61
+ */
62
+ planner: string;
40
63
  goal: string;
41
- state: ObservedState;
42
- content?: string;
43
64
  /**
44
- * Executes the plan based on the given `state` and resolves with
45
- * a potential next `event` to trigger to achieve the `goal`.
65
+ * The ending state of the plan.
66
+ */
67
+ goalState: ObservedState | undefined;
68
+ /**
69
+ * The next event that the agent decided needs to occur to achieve the `goal`.
70
+ *
71
+ * This next event is chosen from the
46
72
  */
47
- execute: (state: ObservedState) => Promise<TEvent | undefined>;
48
73
  nextEvent: TEvent | undefined;
49
- sessionId: string;
74
+ /**
75
+ * The paths that the agent can take to achieve the goal.
76
+ */
77
+ paths: AgentPath<TEvent>[];
78
+ episodeId: string;
50
79
  timestamp: number;
51
80
  };
52
81
  interface TransitionData {
@@ -89,13 +118,12 @@ type AgentPlanner<T extends AnyAgent> = (agent: T, input: AgentPlanInput<T['type
89
118
  type AgentDecideOptions = {
90
119
  goal: string;
91
120
  model?: LanguageModel;
92
- context?: any;
93
121
  state: ObservedState;
94
- machine: AnyStateMachine;
122
+ machine?: AnyStateMachine;
95
123
  execute?: (event: AnyEventObject) => Promise<void>;
96
124
  planner?: AgentPlanner<any>;
97
125
  events?: ZodEventMapping;
98
- } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt' | 'messages'>;
126
+ } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt'>;
99
127
  interface AgentFeedback {
100
128
  goal?: string;
101
129
  observationId?: string;
@@ -106,7 +134,7 @@ interface AgentFeedback {
106
134
  attributes: Record<string, any>;
107
135
  reward: number;
108
136
  timestamp: number;
109
- sessionId: string;
137
+ episodeId: string;
110
138
  }
111
139
  interface AgentFeedbackInput {
112
140
  goal?: string;
@@ -125,10 +153,48 @@ type AgentMessage = CoreMessage & {
125
153
  */
126
154
  responseId?: string;
127
155
  result?: GenerateTextResult<any>;
128
- sessionId: string;
129
- correlationId: string;
130
- parentCorrelationId?: string;
156
+ episodeId: string;
131
157
  };
158
+ type JSONObject = {
159
+ [key: string]: JSONValue;
160
+ };
161
+ type JSONArray = JSONValue[];
162
+ type JSONValue = null | string | number | boolean | JSONObject | JSONArray;
163
+ type LanguageModelV1ProviderMetadata = Record<string, Record<string, JSONValue>>;
164
+ interface LanguageModelV1TextPart {
165
+ type: 'text';
166
+ /**
167
+ The text content.
168
+ */
169
+ text: string;
170
+ /**
171
+ * Additional provider-specific metadata. They are passed through
172
+ * to the provider from the AI SDK and enable provider-specific
173
+ * functionality that can be fully encapsulated in the provider.
174
+ */
175
+ providerMetadata?: LanguageModelV1ProviderMetadata;
176
+ }
177
+ interface LanguageModelV1ToolCallPart {
178
+ type: 'tool-call';
179
+ /**
180
+ ID of the tool call. This ID is used to match the tool call with the tool result.
181
+ */
182
+ toolCallId: string;
183
+ /**
184
+ Name of the tool that is being called.
185
+ */
186
+ toolName: string;
187
+ /**
188
+ Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
189
+ */
190
+ args: unknown;
191
+ /**
192
+ * Additional provider-specific metadata. They are passed through
193
+ * to the provider from the AI SDK and enable provider-specific
194
+ * functionality that can be fully encapsulated in the provider.
195
+ */
196
+ providerMetadata?: LanguageModelV1ProviderMetadata;
197
+ }
132
198
  type AgentMessageInput = CoreMessage & {
133
199
  timestamp?: number;
134
200
  id?: string;
@@ -141,19 +207,19 @@ type AgentMessageInput = CoreMessage & {
141
207
  parentCorrelationId?: string;
142
208
  result?: GenerateTextResult<any>;
143
209
  };
144
- interface AgentObservation<TActor extends AnyActorRef> {
210
+ interface AgentObservation<TActor extends ActorRefLike> {
145
211
  id: string;
146
212
  prevState: SnapshotFrom<TActor> | undefined;
147
- event: EventFrom<TActor>;
213
+ event: EventFrom<TActor> | undefined;
148
214
  state: SnapshotFrom<TActor>;
149
215
  machineHash: string | undefined;
150
- sessionId: string;
216
+ episodeId: string;
151
217
  timestamp: number;
152
218
  }
153
219
  interface AgentObservationInput {
154
220
  id?: string;
155
- prevState: ObservedState | undefined;
156
- event: AnyEventObject;
221
+ prevState?: ObservedState;
222
+ event?: AnyEventObject;
157
223
  state: ObservedState;
158
224
  machine?: AnyStateMachine;
159
225
  timestamp?: number;
@@ -161,7 +227,7 @@ interface AgentObservationInput {
161
227
  type AgentDecisionInput = {
162
228
  goal: string;
163
229
  model?: LanguageModel;
164
- context?: any;
230
+ context?: Record<string, any>;
165
231
  } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt'>;
166
232
  type AgentDecisionLogic<TEvents extends EventObject> = PromiseActorLogic<AgentPlan<TEvents> | undefined, AgentDecisionInput | string>;
167
233
  type AgentEmitted<TEvents extends EventObject> = {
@@ -199,7 +265,86 @@ type EventsFromZodEventMapping<TEventSchemas extends ZodEventMapping> = Values<{
199
265
  type ContextFromZodContextMapping<TContextSchema extends ZodContextMapping> = {
200
266
  [K in keyof TContextSchema & string]: TypeOf<TContextSchema[K]>;
201
267
  };
202
- type Agent<TContext, TEvents extends EventObject> = ActorRefFrom<AgentLogic<TEvents>> & {
268
+ type AnyAgent = Agent<any, any>;
269
+ type FromAgent<T> = T | ((agent: AnyAgent) => T | Promise<T>);
270
+ type CommonTextOptions = {
271
+ prompt: FromAgent<string>;
272
+ model?: LanguageModel;
273
+ context?: Record<string, any>;
274
+ messages?: FromAgent<CoreMessage[]>;
275
+ template?: PromptTemplate<any>;
276
+ };
277
+ type AgentGenerateTextOptions = Omit<GenerateTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
278
+ type AgentStreamTextOptions = Omit<StreamTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
279
+ interface ObservedState {
280
+ /**
281
+ * The current state value of the state machine, e.g.
282
+ * `"loading"` or `"processing"` or `"ready"`
283
+ */
284
+ value: StateValue;
285
+ /**
286
+ * Additional contextual data related to the current state
287
+ */
288
+ context?: Record<string, unknown>;
289
+ }
290
+ type ObservedStateFrom<TActor extends ActorRefLike> = Pick<SnapshotFrom<TActor>, 'value' | 'context'>;
291
+ type AgentMemoryContext = {
292
+ observations: AgentObservation<any>[];
293
+ messages: AgentMessage[];
294
+ plans: AgentPlan<any>[];
295
+ feedback: AgentFeedback[];
296
+ };
297
+ interface AgentLongTermMemory {
298
+ get<K extends keyof AgentMemoryContext>(key: K): Promise<AgentMemoryContext[K]>;
299
+ append<K extends keyof AgentMemoryContext>(key: K, item: AgentMemoryContext[K][0]): Promise<void>;
300
+ set<K extends keyof AgentMemoryContext>(key: K, items: AgentMemoryContext[K]): Promise<void>;
301
+ }
302
+ type Compute<A extends any> = {
303
+ [K in keyof A]: A[K];
304
+ } & unknown;
305
+
306
+ declare function createAgent<const TContextSchema extends ZodContextMapping, const TEventSchemas extends ZodEventMapping, TEvents extends EventObject = EventsFromZodEventMapping<TEventSchemas>, TContext = ContextFromZodContextMapping<TContextSchema>>({ id, name, description, model, events, context, planner, stringify, getMemory, logic, ...generateTextOptions }: {
307
+ /**
308
+ * The unique identifier for the agent.
309
+ *
310
+ * This should be the same across all sessions of a specific agent, as it can be
311
+ * used to retrieve memory for this agent.
312
+ *
313
+ * @example
314
+ * ```ts
315
+ * const agent = createAgent({
316
+ * id: 'recipe-assistant',
317
+ * // ...
318
+ * });
319
+ * ```
320
+ */
321
+ id?: string;
322
+ /**
323
+ * The name of the agent
324
+ */
325
+ name?: string;
326
+ /**
327
+ * A description of the role of the agent
328
+ */
329
+ description?: string;
330
+ /**
331
+ * Events that the agent can cause (send) in an environment
332
+ * that the agent knows about.
333
+ */
334
+ events: TEventSchemas;
335
+ context?: TContextSchema;
336
+ planner?: AgentPlanner<Agent<TContextSchema, TEventSchemas>>;
337
+ stringify?: typeof JSON.stringify;
338
+ /**
339
+ * A function that retrieves the agent's long term memory
340
+ */
341
+ getMemory?: (agent: Agent<TContextSchema, TEventSchemas>) => AgentLongTermMemory;
342
+ /**
343
+ * Agent logic
344
+ */
345
+ logic?: AgentLogic<TEvents>;
346
+ } & GenerateTextOptions): Agent<TContextSchema, TEventSchemas>;
347
+ declare class Agent<const TContextSchema extends ZodContextMapping, const TEventSchemas extends ZodEventMapping, TEvents extends EventObject = EventsFromZodEventMapping<TEventSchemas>, TContext = ContextFromZodContextMapping<TContextSchema>> extends Actor<AgentLogic<TEvents>> {
203
348
  /**
204
349
  * The name of the agent. All agents with the same name are related and
205
350
  * able to share experiences (observations, feedback) with each other.
@@ -208,68 +353,106 @@ type Agent<TContext, TEvents extends EventObject> = ActorRefFrom<AgentLogic<TEve
208
353
  /**
209
354
  * The unique identifier for the agent.
210
355
  */
211
- id?: string;
356
+ episodeId: string;
212
357
  description?: string;
213
- events: ZodEventMapping;
358
+ events: TEventSchemas;
359
+ context?: TContextSchema;
360
+ planner?: AgentPlanner<Agent<TContextSchema, TEventSchemas>>;
214
361
  types: {
215
362
  events: TEvents;
216
363
  context: Compute<TContext>;
217
364
  };
218
365
  model: LanguageModel;
219
- defaultOptions: GenerateTextOptions;
220
366
  memory: AgentLongTermMemory | undefined;
221
- /**
222
- * The adapter used to perform LLM actions such as
223
- * `.generateText(…)` and `.streamText(…)`.
224
- *
225
- * Defaults to the Vercel AI SDK.
226
- */
227
- adapter: AIAdapter;
228
- /**
229
- * Resolves with an `AgentPlan` based on the information provided in the `options`, including:
230
- *
231
- * - The `goal` for the agent to achieve
232
- * - The observed current `state`
233
- * - The `machine` (e.g. a state machine) that specifies what can happen next
234
- * - Additional `context`
235
- */
236
- decide: (options: AgentDecideOptions) => Promise<AgentPlan<TEvents> | undefined>;
237
- generateText: (options: AgentGenerateTextOptions) => Promise<AgentGenerateTextResult>;
238
- streamText: (options: AgentStreamTextOptions) => Promise<AgentStreamTextResult>;
239
- addObservation: (observationInput: AgentObservationInput) => AgentObservation<any>;
240
- addMessage: (messageInput: AgentMessageInput) => AgentMessage;
241
- addFeedback: (feedbackInput: AgentFeedbackInput) => AgentFeedback;
242
- addPlan: (plan: AgentPlan<TEvents>) => void;
367
+ defaultOptions: any;
368
+ constructor({ logic, id, name, description, model, events, context, planner, }: {
369
+ logic: AgentLogic<TEvents>;
370
+ id?: string;
371
+ name?: string;
372
+ description?: string;
373
+ model: GenerateTextOptions['model'];
374
+ events: TEventSchemas;
375
+ context?: TContextSchema;
376
+ planner?: AgentPlanner<Agent<TContextSchema, TEventSchemas>>;
377
+ });
243
378
  /**
244
379
  * Called whenever the agent (LLM assistant) receives or sends a message.
245
380
  */
246
- onMessage: (callback: (message: AgentMessage) => void) => void;
247
- /**
248
- * Selects agent data from its context.
249
- *
250
- * @deprecated Select from `agent.getSnapshot().context` directly or:
251
- * - `agent.getMessages()`
252
- * - `agent.getObservations()`
253
- * - `agent.getFeedback()`
254
- * - `agent.getPlans()`
255
- */
256
- select: <T>(selector: (context: AgentMemoryContext) => T) => T;
381
+ onMessage(fn: (message: AgentMessage) => void): Subscription;
257
382
  /**
258
383
  * Retrieves messages from the agent's short-term (local) memory.
259
384
  */
260
- getMessages: () => AgentMessage[];
385
+ addMessage(messageInput: AgentMessageInput): {
386
+ id: string;
387
+ timestamp: number;
388
+ episodeId: string;
389
+ role: "assistant";
390
+ content: ai.AssistantContent;
391
+ experimental_providerMetadata?: ai.ProviderMetadata;
392
+ responseId?: string;
393
+ correlationId?: string;
394
+ parentCorrelationId?: string;
395
+ result?: ai.GenerateTextResult<any>;
396
+ } | {
397
+ id: string;
398
+ timestamp: number;
399
+ episodeId: string;
400
+ role: "tool";
401
+ content: ai.ToolContent;
402
+ experimental_providerMetadata?: ai.ProviderMetadata;
403
+ responseId?: string;
404
+ correlationId?: string;
405
+ parentCorrelationId?: string;
406
+ result?: ai.GenerateTextResult<any>;
407
+ } | {
408
+ id: string;
409
+ timestamp: number;
410
+ episodeId: string;
411
+ role: "system";
412
+ content: string;
413
+ experimental_providerMetadata?: ai.ProviderMetadata;
414
+ responseId?: string;
415
+ correlationId?: string;
416
+ parentCorrelationId?: string;
417
+ result?: ai.GenerateTextResult<any>;
418
+ } | {
419
+ id: string;
420
+ timestamp: number;
421
+ episodeId: string;
422
+ role: "user";
423
+ content: ai.UserContent;
424
+ experimental_providerMetadata?: ai.ProviderMetadata;
425
+ responseId?: string;
426
+ correlationId?: string;
427
+ parentCorrelationId?: string;
428
+ result?: ai.GenerateTextResult<any>;
429
+ };
430
+ getMessages(): AgentMessage[];
431
+ addFeedback(feedbackInput: AgentFeedbackInput): {
432
+ attributes: {
433
+ [x: string]: any;
434
+ };
435
+ reward: number;
436
+ timestamp: number;
437
+ episodeId: string;
438
+ goal?: string;
439
+ observationId?: string;
440
+ correlationId?: string;
441
+ };
261
442
  /**
262
- * Retrieves observations from the agent's short-term (local) memory.
443
+ * Retrieves feedback from the agent's short-term (local) memory.
263
444
  */
264
- getObservations: () => AgentObservation<Agent<TContext, TEvents>>[];
445
+ getFeedback(): AgentFeedback[];
446
+ addObservation(observationInput: AgentObservationInput): AgentObservation<any>;
265
447
  /**
266
- * Retrieves feedback from the agent's short-term (local) memory.
448
+ * Retrieves observations from the agent's short-term (local) memory.
267
449
  */
268
- getFeedback: () => AgentFeedback[];
450
+ getObservations(): AgentObservation<any>[];
451
+ addPlan(plan: AgentPlan<TEvents>): void;
269
452
  /**
270
453
  * Retrieves strategies from the agent's short-term (local) memory.
271
454
  */
272
- getPlans: () => AgentPlan<TEvents>[];
455
+ getPlans(): AgentPlan<any>[];
273
456
  /**
274
457
  * Interacts with this state machine actor by inspecting state transitions and storing them as observations.
275
458
  *
@@ -286,7 +469,7 @@ type Agent<TContext, TEvents extends EventObject> = ActorRefFrom<AgentLogic<TEve
286
469
  * actor.start();
287
470
  * ```
288
471
  */
289
- interact<TActor extends AnyActorRef>(actorRef: TActor): Subscription;
472
+ interact<TActor extends ActorRefLike>(actorRef: TActor): Subscription;
290
473
  /**
291
474
  * Interacts with this state machine actor by:
292
475
  * 1. Inspecting state transitions and storing them as observations
@@ -314,115 +497,29 @@ type Agent<TContext, TEvents extends EventObject> = ActorRefFrom<AgentLogic<TEve
314
497
  * actor.start();
315
498
  * ```
316
499
  */
317
- interact<TActor extends AnyActorRef>(actorRef: TActor, getInput: (observation: AgentObservation<TActor>) => AgentDecisionInput | undefined): Subscription;
318
- };
319
- type AnyAgent = Agent<any, any>;
320
- type FromAgent<T> = T | ((agent: AnyAgent) => T | Promise<T>);
321
- type CommonTextOptions = {
322
- prompt: FromAgent<string>;
323
- model?: LanguageModel;
324
- context?: Record<string, any>;
325
- messages?: FromAgent<CoreMessage[]>;
326
- template?: PromptTemplate<any>;
327
- correlationId?: string;
328
- parentCorrelationId?: string;
329
- };
330
- type TextResultMeta = {
331
- correlationId: string;
332
- parentCorrelationId?: string;
333
- };
334
- type AgentGenerateTextOptions = Omit<GenerateTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
335
- type AgentGenerateTextResult = GenerateTextResult<any> & TextResultMeta;
336
- type AgentStreamTextOptions = Omit<StreamTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
337
- type AgentStreamTextResult = StreamTextResult<any> & TextResultMeta;
338
- interface ObservedState {
339
- /**
340
- * The current state value of the state machine, e.g.
341
- * `"loading"` or `"processing"` or `"ready"`
342
- */
343
- value: StateValue;
500
+ interact<TActor extends ActorRefLike>(actorRef: TActor, getInput: (observation: AgentObservation<TActor>) => AgentDecisionInput | undefined): Subscription;
501
+ observe<TActor extends ActorRefLike>(actorRef: TActor): Subscription;
502
+ wrap(modelToWrap: LanguageModelV1): LanguageModelV1;
344
503
  /**
345
- * Additional contextual data related to the current state
346
- */
347
- context: Record<string, unknown>;
348
- }
349
- type ObservedStateFrom<TActor extends AnyActorRef> = Pick<SnapshotFrom<TActor>, 'value' | 'context'>;
350
- type AgentMemoryContext = {
351
- observations: AgentObservation<any>[];
352
- messages: AgentMessage[];
353
- plans: AgentPlan<any>[];
354
- feedback: AgentFeedback[];
355
- };
356
- type AgentMemory = AppendOnlyStorage<AgentMemoryContext>;
357
- interface AppendOnlyStorage<T extends Record<string, any[]>> {
358
- append<K extends keyof T>(sessionId: string, key: K, item: T[K][0]): Promise<void>;
359
- getAll<K extends keyof T>(sessionId: string, key: K): Promise<T[K] | undefined>;
360
- }
361
- interface AgentLongTermMemory {
362
- get<K extends keyof AgentMemoryContext>(key: K): Promise<AgentMemoryContext[K]>;
363
- append<K extends keyof AgentMemoryContext>(key: K, item: AgentMemoryContext[K][0]): Promise<void>;
364
- set<K extends keyof AgentMemoryContext>(key: K, items: AgentMemoryContext[K]): Promise<void>;
365
- }
366
- interface AIAdapter {
367
- generateText: typeof generateText;
368
- streamText: typeof streamText;
369
- }
370
- type Compute<A extends any> = {
371
- [K in keyof A]: A[K];
372
- } & unknown;
373
-
374
- declare function createAgent<const TContextSchema extends ZodContextMapping, const TEventSchemas extends ZodEventMapping, TEvents extends EventObject = EventsFromZodEventMapping<TEventSchemas>, TContext = ContextFromZodContextMapping<TContextSchema>>({ name, description, model, events, context, planner, stringify, getMemory, logic, adapter, ...generateTextOptions }: {
375
- /**
376
- * The unique identifier for the agent.
377
- *
378
- * This should be the same across all sessions of a specific agent, as it can be
379
- * used to retrieve memory for this agent.
504
+ * Resolves with an `AgentPlan` based on the information provided in the `options`, including:
380
505
  *
381
- * @example
382
- * ```ts
383
- * const agent = createAgent({
384
- * id: 'recipe-assistant',
385
- * // ...
386
- * });
387
- * ```
388
- */
389
- id?: string;
390
- /**
391
- * The name of the agent
392
- */
393
- name?: string;
394
- /**
395
- * A description of the role of the agent
396
- */
397
- description?: string;
398
- /**
399
- * Events that the agent can cause (send) in an environment
400
- * that the agent knows about.
401
- */
402
- events: TEventSchemas;
403
- context?: TContextSchema;
404
- planner?: AgentPlanner<Agent<TContext, TEvents>>;
405
- stringify?: typeof JSON.stringify;
406
- /**
407
- * A function that retrieves the agent's long term memory
408
- */
409
- getMemory?: (agent: Agent<TContext, TEvents>) => AgentLongTermMemory;
410
- /**
411
- * Agent logic
506
+ * - The `goal` for the agent to achieve
507
+ * - The observed current `state`
508
+ * - The `machine` (e.g. a state machine) that specifies what can happen next
509
+ * - Additional `context`
412
510
  */
413
- logic?: AgentLogic<TEvents>;
414
- adapter?: AIAdapter;
415
- } & GenerateTextOptions): Agent<TContext, TEvents>;
511
+ decide(opts: AgentDecideOptions): Promise<AgentPlan<EventsFromZodEventMapping<this["events"]>> | undefined>;
512
+ }
416
513
 
417
- declare function fromTextStream<T extends AnyAgent>(agent: T, defaultOptions?: AgentStreamTextOptions): ObservableActorLogic<{
514
+ declare function fromTextStream<T extends AnyAgent>(agent: T, options?: AgentStreamTextOptions): ObservableActorLogic<{
418
515
  textDelta: string;
419
516
  }, Omit<AgentStreamTextOptions, 'context'> & {
420
517
  context?: AgentStreamTextOptions['context'];
421
518
  }>;
422
- declare function fromText<T extends AnyAgent>(agent: T, defaultOptions?: AgentGenerateTextOptions): PromiseActorLogic<GenerateTextResult<Record<string, CoreTool<any, any>>>, Omit<AgentGenerateTextOptions, 'context'> & {
519
+ declare function fromText<T extends AnyAgent>(agent: T, options?: AgentGenerateTextOptions): PromiseActorLogic<GenerateTextResult<Record<string, CoreTool<any, any>>>, Omit<AgentGenerateTextOptions, 'context'> & {
423
520
  context?: AgentGenerateTextOptions['context'];
424
521
  }>;
425
522
 
426
523
  declare function fromDecision(agent: AnyAgent, defaultInput?: AgentDecisionInput): AgentDecisionLogic<any>;
427
524
 
428
- export { type AIAdapter, type Agent, type AgentDecideOptions, type AgentDecisionInput, type AgentDecisionLogic, type AgentEmitted, type AgentFeedback, type AgentFeedbackInput, type AgentGenerateTextOptions, type AgentGenerateTextResult, type AgentLogic, type AgentLongTermMemory, type AgentMemory, type AgentMemoryContext, type AgentMessage, type AgentMessageInput, type AgentObservation, type AgentObservationInput, type AgentPlan, type AgentPlanInput, type AgentPlanner, type AgentStreamTextOptions, type AgentStreamTextResult, type AnyAgent, type AppendOnlyStorage, type CommonTextOptions, type Compute, type ContextFromZodContextMapping, type EventsFromZodEventMapping, type FromAgent, type GenerateTextOptions, type ObservedState, type ObservedStateFrom, type PromptTemplate, type StreamTextOptions, type TextResultMeta, type TransitionData, createAgent, fromDecision, fromText, fromTextStream };
525
+ export { type AgentDecideOptions, type AgentDecisionInput, type AgentDecisionLogic, type AgentEmitted, type AgentFeedback, type AgentFeedbackInput, type AgentGenerateTextOptions, type AgentLogic, type AgentLongTermMemory, type AgentMemoryContext, type AgentMessage, type AgentMessageInput, type AgentObservation, type AgentObservationInput, type AgentPath, type AgentPlan, type AgentPlanInput, type AgentPlanner, type AgentStep, type AgentStreamTextOptions, type AnyAgent, type CommonTextOptions, type Compute, type ContextFromZodContextMapping, type CostFunction, type EventsFromZodEventMapping, type FromAgent, type GenerateTextOptions, type LanguageModelV1TextPart, type LanguageModelV1ToolCallPart, type ObservedState, type ObservedStateFrom, type PromptTemplate, type StreamTextOptions, type TransitionData, createAgent, fromDecision, fromText, fromTextStream };