@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/CHANGELOG.md DELETED
@@ -1,222 +0,0 @@
1
- # @statelyai/agent
2
-
3
- ## 1.1.6
4
-
5
- ### Patch Changes
6
-
7
- - [#54](https://github.com/statelyai/agent/pull/54) [`140fdce`](https://github.com/statelyai/agent/commit/140fdceb879dea5a32f243e89a8d87a9c524e454) Thanks [@XavierDK](https://github.com/XavierDK)! - - Addressing an issue where the fullStream property was not properly copied when using the spread operator (...). The problem occurred because fullStream is an iterator, and as such, it was not included in the shallow copy of the result object.
8
- - Update all packages
9
-
10
- ## 1.1.5
11
-
12
- ### Patch Changes
13
-
14
- - [#49](https://github.com/statelyai/agent/pull/49) [`ae505d5`](https://github.com/statelyai/agent/commit/ae505d56b432a92875699507fb694628ef4d773d) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Update `ai` package
15
-
16
- ## 1.1.4
17
-
18
- ### Patch Changes
19
-
20
- - [#47](https://github.com/statelyai/agent/pull/47) [`185c149`](https://github.com/statelyai/agent/commit/185c1498f63aef15a3194032df3dcdcb2b33d752) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Update `ai` and `xstate` packages
21
-
22
- ## 1.1.3
23
-
24
- ### Patch Changes
25
-
26
- - [#45](https://github.com/statelyai/agent/pull/45) [`3c271f3`](https://github.com/statelyai/agent/commit/3c271f306c4ed9553c155e66cec8aa4284e9c813) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix reading the actor logic
27
-
28
- ## 1.1.2
29
-
30
- ### Patch Changes
31
-
32
- - [#43](https://github.com/statelyai/agent/pull/43) [`8e7629c`](https://github.com/statelyai/agent/commit/8e7629c347b29b704ae9576aa1af97e6cd693bc7) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Update dependencies
33
-
34
- ## 1.1.1
35
-
36
- ### Patch Changes
37
-
38
- - [#41](https://github.com/statelyai/agent/pull/41) [`b2f2b73`](https://github.com/statelyai/agent/commit/b2f2b7307e96d7722968769aae9db2572ede8ce7) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Update dependencies
39
-
40
- ## 1.1.0
41
-
42
- ### Minor Changes
43
-
44
- - [#39](https://github.com/statelyai/agent/pull/39) [`3cce30f`](https://github.com/statelyai/agent/commit/3cce30fc77d36dbed0abad805248de9f64bf8086) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added four new methods for easily retrieving agent messages, observations, feedback, and plans:
45
-
46
- - `agent.getMessages()`
47
- - `agent.getObservations()`
48
- - `agent.getFeedback()`
49
- - `agent.getPlans()`
50
-
51
- The `agent.select(…)` method is deprecated in favor of these methods.
52
-
53
- - [#40](https://github.com/statelyai/agent/pull/40) [`8b7c374`](https://github.com/statelyai/agent/commit/8b7c37482d5c35b2b3addc2f88e198526f203da7) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Correlation IDs are now provided as part of the result from `agent.generateText(…)` and `agent.streamText(…)`:
54
-
55
- ```ts
56
- const result = await agent.generateText({
57
- prompt: "Write me a song",
58
- correlationId: "my-correlation-id",
59
- // ...
60
- });
61
-
62
- result.correlationId; // 'my-correlation-id'
63
- ```
64
-
65
- These correlation IDs can be passed to feedback:
66
-
67
- ```ts
68
- // ...
69
-
70
- agent.addFeedback({
71
- reward: -1,
72
- correlationId: result.correlationId,
73
- });
74
- ```
75
-
76
- - [#40](https://github.com/statelyai/agent/pull/40) [`8b7c374`](https://github.com/statelyai/agent/commit/8b7c37482d5c35b2b3addc2f88e198526f203da7) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Changes to agent feedback (the `AgentFeedback` interface):
77
-
78
- - `goal` is now optional
79
- - `observationId` is now optional
80
- - `correlationId` has been added (optional)
81
- - `reward` has been added (optional)
82
- - `attributes` are now optional
83
-
84
- - [#38](https://github.com/statelyai/agent/pull/38) [`21fb17c`](https://github.com/statelyai/agent/commit/21fb17c65fac1cbb4a8b08a04a58480a6930a0a9) Thanks [@davidkpiano](https://github.com/davidkpiano)! - You can now add `context` Zod schema to your agent. For now, this is meant to be passed directly to the state machine, but in the future, the schema can be shared with the LLM agent to better understand the state machine and its context for decision making.
85
-
86
- Breaking: The `context` and `events` types are now in `agent.types` instead of ~~`agent.eventTypes`.
87
-
88
- ```ts
89
- const agent = createAgent({
90
- // ...
91
- context: {
92
- score: z.number().describe("The score of the game"),
93
- // ...
94
- },
95
- });
96
-
97
- const machine = setup({
98
- types: agent.types,
99
- }).createMachine({
100
- context: {
101
- score: 0,
102
- },
103
- // ...
104
- });
105
- ```
106
-
107
- ### Patch Changes
108
-
109
- - [`5f863bb`](https://github.com/statelyai/agent/commit/5f863bb0d89d90f30d0a9aa1f0dd2a35f0eeb45b) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Use nanoid
110
-
111
- - [#37](https://github.com/statelyai/agent/pull/37) [`dafa815`](https://github.com/statelyai/agent/commit/dafa8157cc1b5adbfb222c146dbc84ab2eed8894) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Messages are now properly included in `agent.decide(…)`, when specified.
112
-
113
- ## 0.1.0
114
-
115
- ### Minor Changes
116
-
117
- - [#32](https://github.com/statelyai/agent/pull/32) [`537f501`](https://github.com/statelyai/agent/commit/537f50111b5f8edc1a309d1abb8fffcdddddbc03) Thanks [@davidkpiano](https://github.com/davidkpiano)! - First minor release of `@statelyai/agent`! The API has been simplified from experimental earlier versions. Here are the main methods:
118
-
119
- - `createAgent({ … })` creates an agent
120
- - `agent.decide({ … })` decides on a plan to achieve the goal
121
- - `agent.generateText({ … })` generates text based on a prompt
122
- - `agent.streamText({ … })` streams text based on a prompt
123
- - `agent.addObservation(observation)` adds an observation and returns a full observation object
124
- - `agent.addFeedback(feedback)` adds a feedback and returns a full feedback object
125
- - `agent.addMessage(message)` adds a message and returns a full message object
126
- - `agent.addPlan(plan)` adds a plan and returns a full plan object
127
- - `agent.onMessage(cb)` listens to messages
128
- - `agent.select(selector)` selects data from the agent context
129
- - `agent.interact(actorRef, getInput)` interacts with an actor and makes decisions to accomplish a goal
130
-
131
- ## 0.0.8
132
-
133
- ### Patch Changes
134
-
135
- - [#22](https://github.com/statelyai/agent/pull/22) [`8a2c34b`](https://github.com/statelyai/agent/commit/8a2c34b8a99161bf47c72df8eed3f5d3b6a19f5f) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `createSchemas(…)` function has been removed. The `defineEvents(…)` function should be used instead, as it is a simpler way of defining events and event schemas using Zod:
136
-
137
- ```ts
138
- import { defineEvents } from "@statelyai/agent";
139
- import { z } from "zod";
140
- import { setup } from "xstate";
141
-
142
- const events = defineEvents({
143
- inc: z.object({
144
- by: z.number().describe("Increment amount"),
145
- }),
146
- });
147
-
148
- const machine = setup({
149
- types: {
150
- events: events.types,
151
- },
152
- schema: {
153
- events: events.schemas,
154
- },
155
- }).createMachine({
156
- // ...
157
- });
158
- ```
159
-
160
- ## 0.0.7
161
-
162
- ### Patch Changes
163
-
164
- - [#18](https://github.com/statelyai/agent/pull/18) [`dcaabab`](https://github.com/statelyai/agent/commit/dcaababe69255b7eaff3347d0cf09469d3e6cc78) Thanks [@davidkpiano](https://github.com/davidkpiano)! - `context` is now optional for `createSchemas(…)`
165
-
166
- ## 0.0.6
167
-
168
- ### Patch Changes
169
-
170
- - [#16](https://github.com/statelyai/agent/pull/16) [`3ba5fb2`](https://github.com/statelyai/agent/commit/3ba5fb2392b51dee71f2585ed662b4ee9ecd6c41) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Update to XState 5.8.0
171
-
172
- ## 0.0.5
173
-
174
- ### Patch Changes
175
-
176
- - [#9](https://github.com/statelyai/agent/pull/9) [`d8e7b67`](https://github.com/statelyai/agent/commit/d8e7b673f6d265f37b2096b25d75310845860271) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `adapter.fromTool(…)`, which creates an actor that chooses agent logic based on a input.
177
-
178
- ```ts
179
- const actor = adapter.fromTool(() => "Draw me a picture of a donut", {
180
- // tools
181
- makeIllustration: {
182
- description: "Makes an illustration",
183
- run: async (input) => {
184
- /* ... */
185
- },
186
- inputSchema: {
187
- /* ... */
188
- },
189
- },
190
- getWeather: {
191
- description: "Gets the weather",
192
- run: async (input) => {
193
- /* ... */
194
- },
195
- inputSchema: {
196
- /* ... */
197
- },
198
- },
199
- });
200
-
201
- //...
202
- ```
203
-
204
- ## 0.0.4
205
-
206
- ### Patch Changes
207
-
208
- - [#5](https://github.com/statelyai/agent/pull/5) [`ae473d7`](https://github.com/statelyai/agent/commit/ae473d73399a15ac3199d77d00eb44a0ea5626db) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Simplify API (WIP)
209
-
210
- - [#5](https://github.com/statelyai/agent/pull/5) [`687bed8`](https://github.com/statelyai/agent/commit/687bed87f29bd1d13447cc53b5154da0fe6fdcab) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `createSchemas`, `createOpenAIAdapter`, and change `createAgent`
211
-
212
- ## 0.0.3
213
-
214
- ### Patch Changes
215
-
216
- - [#1](https://github.com/statelyai/agent/pull/1) [`3dc2880`](https://github.com/statelyai/agent/commit/3dc28809a7ffd915a69d9f3374531c31fc1ee357) Thanks [@mellson](https://github.com/mellson)! - Adds a convenient way to run the examples with `pnpm example ${exampleName}`. If no example name is provided, the script will print the available examples. Also, adds a fun little loading animation to the joke example.
217
-
218
- ## 0.0.2
219
-
220
- ### Patch Changes
221
-
222
- - e125728: Added `createAgent(...)`
package/dist/index.d.ts DELETED
@@ -1,428 +0,0 @@
1
- import { EventObject, AnyStateMachine, AnyEventObject, AnyActorRef, SnapshotFrom, EventFrom, PromiseActorLogic, ActorLogic, TransitionSnapshot, Values, ActorRefFrom, Subscription, StateValue, ObservableActorLogic } from 'xstate';
2
- import { SomeZodObject, ZodType, TypeOf } from 'zod';
3
- import { generateText, streamText, LanguageModel, CoreMessage, GenerateTextResult, StreamTextResult, CoreTool } from 'ai';
4
-
5
- type ZodEventMapping = {
6
- [eventType: string]: SomeZodObject;
7
- };
8
- type ZodContextMapping = {
9
- [contextKey: string]: ZodType;
10
- };
11
-
12
- type GenerateTextOptions = Parameters<typeof generateText>[0];
13
- type StreamTextOptions = Parameters<typeof streamText>[0];
14
- type AgentPlanInput<TEvent extends EventObject> = Omit<GenerateTextOptions, 'prompt' | 'messages' | 'tools'> & {
15
- /**
16
- * The currently observed state.
17
- */
18
- state: ObservedState;
19
- /**
20
- * The goal for the agent to accomplish.
21
- * The agent will create a plan based on this goal.
22
- */
23
- goal: string;
24
- /**
25
- * The events that the agent can trigger. This is a mapping of
26
- * event types to Zod event schemas.
27
- */
28
- events: ZodEventMapping;
29
- /**
30
- * The state machine that represents the environment the agent
31
- * is interacting with.
32
- */
33
- machine?: AnyStateMachine;
34
- /**
35
- * The previous plan.
36
- */
37
- previousPlan?: AgentPlan<TEvent>;
38
- };
39
- type AgentPlan<TEvent extends EventObject> = {
40
- goal: string;
41
- state: ObservedState;
42
- content?: string;
43
- /**
44
- * Executes the plan based on the given `state` and resolves with
45
- * a potential next `event` to trigger to achieve the `goal`.
46
- */
47
- execute: (state: ObservedState) => Promise<TEvent | undefined>;
48
- nextEvent: TEvent | undefined;
49
- sessionId: string;
50
- timestamp: number;
51
- };
52
- interface TransitionData {
53
- eventType: string;
54
- description?: string;
55
- guard?: {
56
- type: string;
57
- };
58
- target?: any;
59
- }
60
- type PromptTemplate<TEvents extends EventObject> = (data: {
61
- goal: string;
62
- /**
63
- * The observed state
64
- */
65
- state?: ObservedState;
66
- /**
67
- * The context to provide.
68
- * This overrides the observed state.context, if provided.
69
- */
70
- context?: any;
71
- /**
72
- * The state machine model of the observed environment
73
- */
74
- machine?: unknown;
75
- /**
76
- * The potential next transitions that can be taken
77
- * in the state machine
78
- */
79
- transitions?: TransitionData[];
80
- /**
81
- * Past observations
82
- */
83
- observations?: AgentObservation<any>[];
84
- feedback?: AgentFeedback[];
85
- messages?: AgentMessage[];
86
- plans?: AgentPlan<TEvents>[];
87
- }) => string;
88
- type AgentPlanner<T extends AnyAgent> = (agent: T, input: AgentPlanInput<T['types']['events']>) => Promise<AgentPlan<T['types']['events']> | undefined>;
89
- type AgentDecideOptions = {
90
- goal: string;
91
- model?: LanguageModel;
92
- context?: any;
93
- state: ObservedState;
94
- machine: AnyStateMachine;
95
- execute?: (event: AnyEventObject) => Promise<void>;
96
- planner?: AgentPlanner<any>;
97
- events?: ZodEventMapping;
98
- } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt' | 'messages'>;
99
- interface AgentFeedback {
100
- goal?: string;
101
- observationId?: string;
102
- /**
103
- * The message correlation that the feedback is relevant for
104
- */
105
- correlationId?: string;
106
- attributes: Record<string, any>;
107
- reward: number;
108
- timestamp: number;
109
- sessionId: string;
110
- }
111
- interface AgentFeedbackInput {
112
- goal?: string;
113
- observationId?: string;
114
- correlationId?: string;
115
- attributes?: Record<string, any>;
116
- timestamp?: number;
117
- reward?: number;
118
- }
119
- type AgentMessage = CoreMessage & {
120
- timestamp: number;
121
- id: string;
122
- /**
123
- * The response ID of the message, which references
124
- * which message this message is responding to, if any.
125
- */
126
- responseId?: string;
127
- result?: GenerateTextResult<any>;
128
- sessionId: string;
129
- correlationId: string;
130
- parentCorrelationId?: string;
131
- };
132
- type AgentMessageInput = CoreMessage & {
133
- timestamp?: number;
134
- id?: string;
135
- /**
136
- * The response ID of the message, which references
137
- * which message this message is responding to, if any.
138
- */
139
- responseId?: string;
140
- correlationId?: string;
141
- parentCorrelationId?: string;
142
- result?: GenerateTextResult<any>;
143
- };
144
- interface AgentObservation<TActor extends AnyActorRef> {
145
- id: string;
146
- prevState: SnapshotFrom<TActor> | undefined;
147
- event: EventFrom<TActor>;
148
- state: SnapshotFrom<TActor>;
149
- machineHash: string | undefined;
150
- sessionId: string;
151
- timestamp: number;
152
- }
153
- interface AgentObservationInput {
154
- id?: string;
155
- prevState: ObservedState | undefined;
156
- event: AnyEventObject;
157
- state: ObservedState;
158
- machine?: AnyStateMachine;
159
- timestamp?: number;
160
- }
161
- type AgentDecisionInput = {
162
- goal: string;
163
- model?: LanguageModel;
164
- context?: any;
165
- } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt'>;
166
- type AgentDecisionLogic<TEvents extends EventObject> = PromiseActorLogic<AgentPlan<TEvents> | undefined, AgentDecisionInput | string>;
167
- type AgentEmitted<TEvents extends EventObject> = {
168
- type: 'feedback';
169
- feedback: AgentFeedback;
170
- } | {
171
- type: 'observation';
172
- observation: AgentObservation<any>;
173
- } | {
174
- type: 'message';
175
- message: AgentMessage;
176
- } | {
177
- type: 'plan';
178
- plan: AgentPlan<TEvents>;
179
- };
180
- type AgentLogic<TEvents extends EventObject> = ActorLogic<TransitionSnapshot<AgentMemoryContext>, {
181
- type: 'agent.feedback';
182
- feedback: AgentFeedback;
183
- } | {
184
- type: 'agent.observe';
185
- observation: AgentObservation<any>;
186
- } | {
187
- type: 'agent.message';
188
- message: AgentMessage;
189
- } | {
190
- type: 'agent.plan';
191
- plan: AgentPlan<TEvents>;
192
- }, any, // TODO: input
193
- any, AgentEmitted<TEvents>>;
194
- type EventsFromZodEventMapping<TEventSchemas extends ZodEventMapping> = Values<{
195
- [K in keyof TEventSchemas & string]: {
196
- type: K;
197
- } & TypeOf<TEventSchemas[K]>;
198
- }>;
199
- type ContextFromZodContextMapping<TContextSchema extends ZodContextMapping> = {
200
- [K in keyof TContextSchema & string]: TypeOf<TContextSchema[K]>;
201
- };
202
- type Agent<TContext, TEvents extends EventObject> = ActorRefFrom<AgentLogic<TEvents>> & {
203
- /**
204
- * The name of the agent. All agents with the same name are related and
205
- * able to share experiences (observations, feedback) with each other.
206
- */
207
- name?: string;
208
- /**
209
- * The unique identifier for the agent.
210
- */
211
- id?: string;
212
- description?: string;
213
- events: ZodEventMapping;
214
- types: {
215
- events: TEvents;
216
- context: Compute<TContext>;
217
- };
218
- model: LanguageModel;
219
- defaultOptions: GenerateTextOptions;
220
- 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;
243
- /**
244
- * Called whenever the agent (LLM assistant) receives or sends a message.
245
- */
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;
257
- /**
258
- * Retrieves messages from the agent's short-term (local) memory.
259
- */
260
- getMessages: () => AgentMessage[];
261
- /**
262
- * Retrieves observations from the agent's short-term (local) memory.
263
- */
264
- getObservations: () => AgentObservation<Agent<TContext, TEvents>>[];
265
- /**
266
- * Retrieves feedback from the agent's short-term (local) memory.
267
- */
268
- getFeedback: () => AgentFeedback[];
269
- /**
270
- * Retrieves strategies from the agent's short-term (local) memory.
271
- */
272
- getPlans: () => AgentPlan<TEvents>[];
273
- /**
274
- * Interacts with this state machine actor by inspecting state transitions and storing them as observations.
275
- *
276
- * Observations contain the `prevState`, `event`, and current `state` of this
277
- * actor, as well as other properties that are useful when recalled.
278
- * These observations are stored in the `agent`'s short-term (local) memory
279
- * and can be retrieved via `agent.getObservations()`.
280
- *
281
- * @example
282
- * ```ts
283
- * // Only observes the actor's state transitions
284
- * agent.interact(actor);
285
- *
286
- * actor.start();
287
- * ```
288
- */
289
- interact<TActor extends AnyActorRef>(actorRef: TActor): Subscription;
290
- /**
291
- * Interacts with this state machine actor by:
292
- * 1. Inspecting state transitions and storing them as observations
293
- * 2. Deciding what to do next (which event to send the actor) based on
294
- * the agent input returned from `getInput(observation)`, if `getInput(…)` is provided as the 2nd argument.
295
- *
296
- * Observations contain the `prevState`, `event`, and current `state` of this
297
- * actor, as well as other properties that are useful when recalled.
298
- * These observations are stored in the `agent`'s short-term (local) memory
299
- * and can be retrieved via `agent.getObservations()`.
300
- *
301
- * @example
302
- * ```ts
303
- * // Observes the actor's state transitions and
304
- * // makes a decision if on the "summarize" state
305
- * agent.interact(actor, observed => {
306
- * if (observed.state.matches('summarize')) {
307
- * return {
308
- * context: observed.state.context,
309
- * goal: 'Summarize the message'
310
- * }
311
- * }
312
- * });
313
- *
314
- * actor.start();
315
- * ```
316
- */
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;
344
- /**
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.
380
- *
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
412
- */
413
- logic?: AgentLogic<TEvents>;
414
- adapter?: AIAdapter;
415
- } & GenerateTextOptions): Agent<TContext, TEvents>;
416
-
417
- declare function fromTextStream<T extends AnyAgent>(agent: T, defaultOptions?: AgentStreamTextOptions): ObservableActorLogic<{
418
- textDelta: string;
419
- }, Omit<AgentStreamTextOptions, 'context'> & {
420
- context?: AgentStreamTextOptions['context'];
421
- }>;
422
- declare function fromText<T extends AnyAgent>(agent: T, defaultOptions?: AgentGenerateTextOptions): PromiseActorLogic<GenerateTextResult<Record<string, CoreTool<any, any>>>, Omit<AgentGenerateTextOptions, 'context'> & {
423
- context?: AgentGenerateTextOptions['context'];
424
- }>;
425
-
426
- declare function fromDecision(agent: AnyAgent, defaultInput?: AgentDecisionInput): AgentDecisionLogic<any>;
427
-
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 };