@statelyai/agent 0.0.8 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.vscode/launch.json +12 -1
  2. package/CHANGELOG.md +18 -0
  3. package/dist/index.d.mts +3 -0
  4. package/dist/index.d.ts +286 -44
  5. package/dist/index.js +695 -1225
  6. package/dist/index.mjs +7 -0
  7. package/examples/chatbot.ts +79 -0
  8. package/examples/cot.ts +91 -0
  9. package/examples/email.ts +118 -0
  10. package/examples/example.ts +81 -0
  11. package/examples/goal.ts +94 -0
  12. package/examples/joke.ts +98 -84
  13. package/examples/multi.ts +103 -0
  14. package/examples/newspaper.ts +324 -0
  15. package/examples/number.ts +102 -0
  16. package/examples/raffle.ts +105 -0
  17. package/examples/simple.ts +39 -0
  18. package/examples/support.ts +147 -0
  19. package/examples/ticTacToe.ts +77 -77
  20. package/examples/todo.ts +135 -0
  21. package/examples/tutor.ts +100 -0
  22. package/examples/verify.ts +120 -0
  23. package/examples/weather.ts +42 -45
  24. package/examples/wiki.ts +30 -0
  25. package/examples/word.ts +168 -0
  26. package/package.json +29 -23
  27. package/readme.md +9 -38
  28. package/src/adapters/vercel.ts +7 -0
  29. package/src/agent-experimental.ts +221 -0
  30. package/src/agent.test.ts +187 -0
  31. package/src/agent.ts +260 -6
  32. package/src/decision.test.ts +179 -0
  33. package/src/decision.ts +83 -0
  34. package/src/index.ts +3 -2
  35. package/src/memory.ts +25 -0
  36. package/src/planners/shortestPathPlanner.ts +22 -0
  37. package/src/planners/simplePlanner.ts +126 -0
  38. package/src/schemas.ts +9 -20
  39. package/src/strategies/chain-of-note.ts +155 -0
  40. package/src/templates/defaultText.ts +18 -0
  41. package/src/templates/defaultToolCall.ts +10 -0
  42. package/src/text.ts +232 -0
  43. package/src/types.ts +363 -46
  44. package/src/utils.ts +13 -72
  45. package/tsconfig.json +1 -1
  46. package/examples/multiAgentCollaboration.ts +0 -0
  47. package/examples/numberGuesser.ts +0 -101
  48. package/examples/wordGuesser.ts +0 -144
  49. package/src/adapter.test.ts +0 -217
  50. package/src/adapters/openai.ts +0 -303
@@ -7,11 +7,22 @@
7
7
  "request": "launch",
8
8
  "name": "Debug Current Test File",
9
9
  "autoAttachChildProcesses": true,
10
- "skipFiles": ["<node_internals>/**", "**/node_modules/**"],
10
+ "skipFiles": ["<node_internals>/**", "**/node_modules/**", "examples/**"],
11
11
  "program": "${workspaceRoot}/node_modules/vitest/vitest.mjs",
12
12
  "args": ["run", "${relativeFile}"],
13
13
  "smartStep": true,
14
14
  "console": "integratedTerminal"
15
+ },
16
+ {
17
+ "type": "node",
18
+ "request": "launch",
19
+ "name": "Debug Current File",
20
+ "program": "${file}",
21
+ "cwd": "${workspaceFolder}",
22
+ "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/ts-node",
23
+ "outFiles": ["${workspaceFolder}/dist/**/*.js"],
24
+ "sourceMaps": true,
25
+ "console": "integratedTerminal"
15
26
  }
16
27
  ]
17
28
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @statelyai/agent
2
2
 
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#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:
8
+
9
+ - `createAgent({ … })` creates an agent
10
+ - `agent.decide({ … })` decides on a plan to achieve the goal
11
+ - `agent.generateText({ … })` generates text based on a prompt
12
+ - `agent.streamText({ … })` streams text based on a prompt
13
+ - `agent.addObservation(observation)` adds an observation and returns a full observation object
14
+ - `agent.addFeedback(feedback)` adds a feedback and returns a full feedback object
15
+ - `agent.addMessage(message)` adds a message and returns a full message object
16
+ - `agent.addPlan(plan)` adds a plan and returns a full plan object
17
+ - `agent.onMessage(cb)` listens to messages
18
+ - `agent.select(selector)` selects data from the agent context
19
+ - `agent.interact(actorRef, getInput)` interacts with an actor and makes decisions to accomplish a goal
20
+
3
21
  ## 0.0.8
4
22
 
5
23
  ### Patch Changes
@@ -0,0 +1,3 @@
1
+ declare function helloWorld(): string;
2
+
3
+ export { helloWorld };
package/dist/index.d.ts CHANGED
@@ -1,62 +1,304 @@
1
- import * as xstate from 'xstate';
2
- import { Values, AnyStateMachine, createActor, PromiseActorLogic, AnyEventObject, ObservableActorLogic } from 'xstate';
1
+ import { EventObject, AnyStateMachine, AnyEventObject, AnyActorRef, SnapshotFrom, EventFrom, PromiseActorLogic, ActorLogic, TransitionSnapshot, Values, ActorRefFrom, Subscription, StateValue, ObservableActorLogic } from 'xstate';
3
2
  import { TypeOf, SomeZodObject } from 'zod';
4
- import OpenAI from 'openai';
5
- import { ChatCompletionCreateParamsBase } from 'openai/resources/chat/completions';
6
- import { ChatCompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming } from 'openai/resources';
3
+ import { generateText, streamText, LanguageModel, CoreMessage, GenerateTextResult, StreamTextResult, CoreTool } from 'ai';
7
4
 
8
- type ZodEventTypes = {
9
- [eventType: string]: SomeZodObject;
5
+ type GenerateTextOptions = Parameters<typeof generateText>[0];
6
+ type StreamTextOptions = Parameters<typeof streamText>[0];
7
+ type AgentPlanInput<TEvent extends EventObject> = {
8
+ model: LanguageModel;
9
+ state: ObservedState;
10
+ goal: string;
11
+ events: ZodEventMapping;
12
+ machine?: AnyStateMachine;
13
+ /**
14
+ * The previous plan
15
+ */
16
+ previousPlan?: AgentPlan<TEvent>;
10
17
  };
11
- declare function defineEvents<const TEventSchemas extends ZodEventTypes>(events: TEventSchemas): {
12
- types: Values<{
13
- [K in keyof TEventSchemas]: {
14
- type: K;
15
- } & TypeOf<TEventSchemas[K]>;
18
+ type AgentPlan<TEvent extends EventObject> = {
19
+ goal: string;
20
+ state: ObservedState;
21
+ content?: string;
22
+ steps?: Array<{
23
+ event: TEvent;
24
+ state?: ObservedState;
16
25
  }>;
17
- schemas: {
18
- [K in keyof TEventSchemas]: unknown;
26
+ nextEvent: TEvent | undefined;
27
+ sessionId: string;
28
+ timestamp: number;
29
+ };
30
+ interface TransitionData {
31
+ eventType: string;
32
+ description?: string;
33
+ guard?: {
34
+ type: string;
19
35
  };
36
+ target?: any;
37
+ }
38
+ type PromptTemplate<TEvents extends EventObject> = (data: {
39
+ goal: string;
40
+ /**
41
+ * The observed state
42
+ */
43
+ state?: ObservedState;
44
+ /**
45
+ * The context to provide.
46
+ * This overrides the observed state.context, if provided.
47
+ */
48
+ context?: any;
49
+ /**
50
+ * The state machine model of the observed environment
51
+ */
52
+ machine?: unknown;
53
+ /**
54
+ * The potential next transitions that can be taken
55
+ * in the state machine
56
+ */
57
+ transitions?: TransitionData[];
58
+ /**
59
+ * Past observations
60
+ */
61
+ observations?: AgentObservation<any>[];
62
+ feedback?: AgentFeedback[];
63
+ messages?: AgentMessageHistory[];
64
+ plans?: AgentPlan<TEvents>[];
65
+ }) => string;
66
+ type AgentPlanner<T extends Agent<any>> = (agent: T['eventTypes'], options: AgentPlanInput<T['eventTypes']>) => Promise<AgentPlan<T['eventTypes']> | undefined>;
67
+ type AgentDecideOptions = {
68
+ goal: string;
69
+ model?: LanguageModel;
70
+ context?: any;
71
+ state: ObservedState;
72
+ machine: AnyStateMachine;
73
+ execute?: (event: AnyEventObject) => Promise<void>;
74
+ planner?: AgentPlanner<any>;
75
+ events?: ZodEventMapping;
76
+ } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt' | 'messages'>;
77
+ interface AgentFeedback {
78
+ goal: string;
79
+ observationId: string;
80
+ attributes: Record<string, any>;
81
+ timestamp: number;
82
+ sessionId: string;
83
+ }
84
+ interface AgentFeedbackInput {
85
+ goal: string;
86
+ observationId: string;
87
+ attributes: Record<string, any>;
88
+ timestamp?: number;
89
+ }
90
+ type AgentMessageHistory = CoreMessage & {
91
+ timestamp: number;
92
+ id: string;
93
+ /**
94
+ * The response ID of the message, which references
95
+ * which message this message is responding to, if any.
96
+ */
97
+ responseId?: string;
98
+ result?: GenerateTextResult<any>;
99
+ sessionId: string;
20
100
  };
21
-
22
- declare function createAgent<T extends AnyStateMachine>(...args: Parameters<typeof createActor<T>>): xstate.Actor<T>;
23
-
24
- interface StatelyAgentAdapter {
25
- model: string;
101
+ type AgentMessageHistoryInput = CoreMessage & {
102
+ timestamp?: number;
103
+ id?: string;
104
+ /**
105
+ * The response ID of the message, which references
106
+ * which message this message is responding to, if any.
107
+ */
108
+ responseId?: string;
109
+ result?: GenerateTextResult<any>;
110
+ };
111
+ interface AgentObservation<TActor extends AnyActorRef> {
112
+ id: string;
113
+ prevState: SnapshotFrom<TActor> | undefined;
114
+ event: EventFrom<TActor>;
115
+ state: SnapshotFrom<TActor>;
116
+ sessionId: string;
117
+ timestamp: number;
118
+ }
119
+ interface AgentObservationInput {
120
+ id?: string;
121
+ prevState: ObservedState | undefined;
122
+ event: AnyEventObject;
123
+ state: ObservedState;
124
+ timestamp?: number;
125
+ }
126
+ type AgentDecisionInput = {
127
+ goal: string;
128
+ model?: LanguageModel;
129
+ context?: any;
130
+ } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt'>;
131
+ type AgentDecisionLogic<TEvents extends EventObject> = PromiseActorLogic<AgentPlan<TEvents> | undefined, AgentDecisionInput | string>;
132
+ type AgentEmitted<TEvents extends EventObject> = {
133
+ type: 'feedback';
134
+ feedback: AgentFeedback;
135
+ } | {
136
+ type: 'observation';
137
+ observation: AgentObservation<any>;
138
+ } | {
139
+ type: 'message';
140
+ message: AgentMessageHistory;
141
+ } | {
142
+ type: 'plan';
143
+ plan: AgentPlan<TEvents>;
144
+ };
145
+ type AgentLogic<TEvents extends EventObject> = ActorLogic<TransitionSnapshot<AgentMemoryContext>, {
146
+ type: 'agent.feedback';
147
+ feedback: AgentFeedback;
148
+ } | {
149
+ type: 'agent.observe';
150
+ observation: AgentObservation<any>;
151
+ } | {
152
+ type: 'agent.message';
153
+ message: AgentMessageHistory;
154
+ } | {
155
+ type: 'agent.plan';
156
+ plan: AgentPlan<TEvents>;
157
+ }, any, // TODO: input
158
+ any, AgentEmitted<TEvents>>;
159
+ type EventsFromZodEventMapping<TEventSchemas extends ZodEventMapping> = Values<{
160
+ [K in keyof TEventSchemas & string]: {
161
+ type: K;
162
+ } & TypeOf<TEventSchemas[K]>;
163
+ }>;
164
+ type Agent<TEvents extends EventObject> = ActorRefFrom<AgentLogic<TEvents>> & {
165
+ /**
166
+ * The general name of the agent. All agents with the same name are related and
167
+ * able to share experiences (observations, feedback) with each other.
168
+ */
169
+ name: string;
26
170
  /**
27
- * Creates actor logic that chooses an event from all of the
28
- * possible next events of the parent state machine
29
- * and sends it to the parent actor.
171
+ * The unique id of the agent. This is used to partition message history.
30
172
  */
31
- fromEvent: <TInput>(inputFn: (input: TInput) => string | ChatCompletionCreateParamsNonStreaming) => PromiseActorLogic<AnyEventObject[] | undefined, TInput>;
173
+ id?: string;
174
+ description?: string;
175
+ events: ZodEventMapping;
176
+ eventTypes: TEvents;
177
+ model: LanguageModel;
178
+ defaultOptions: GenerateTextOptions;
179
+ memory: AgentLongTermMemory | undefined;
32
180
  /**
33
- * Creates actor logic that resolves with a chat completion.
181
+ * The adapter used to perform LLM actions such as
182
+ * `.generateText(…)` and `.streamText(…)`.
183
+ *
184
+ * Defaults to the Vercel AI SDK.
34
185
  */
35
- fromChat: <TInput>(inputFn: (input: TInput) => string | ChatCompletionCreateParamsNonStreaming) => PromiseActorLogic<OpenAI.Chat.Completions.ChatCompletion, TInput>;
186
+ adapter: AIAdapter;
36
187
  /**
37
- * Creates actor logic that emits a chat completion stream.
188
+ * Resolves with an `AgentPlan` based on the information provided in the `options`, including:
189
+ *
190
+ * - The `goal` for the agent to achieve
191
+ * - The observed current `state`
192
+ * - The `logic` (e.g. a state machine) that specifies what can happen next
193
+ * - Additional `context`
38
194
  */
39
- fromChatStream: <TInput>(inputFn: (input: TInput) => string | ChatCompletionCreateParamsStreaming) => ObservableActorLogic<OpenAI.Chat.Completions.ChatCompletionChunk, TInput>;
195
+ decide: (options: AgentDecideOptions) => Promise<AgentPlan<TEvents> | undefined>;
196
+ generateText: (options: AgentGenerateTextOptions) => Promise<GenerateTextResult<Record<string, any>>>;
197
+ streamText: (options: AgentStreamTextOptions) => Promise<StreamTextResult<Record<string, CoreTool<any, any>>>>;
198
+ addObservation: (observation: AgentObservationInput) => AgentObservation<any>;
199
+ addMessage: (history: AgentMessageHistoryInput) => AgentMessageHistory;
200
+ addFeedback: (feedbackItem: AgentFeedbackInput) => AgentFeedback;
201
+ addPlan: (plan: AgentPlan<TEvents>) => void;
40
202
  /**
41
- * Creates actor logic that chooses a tool from the provided
42
- * tools and runs that tool.
203
+ * Called whenever the agent (LLM assistant) receives or sends a message.
43
204
  */
44
- fromTool: <TInput>(inputFn: (input: TInput) => string | ChatCompletionCreateParamsNonStreaming, tools: {
45
- [key: string]: Tool<any, any>;
46
- }) => PromiseActorLogic<{
47
- result: any;
48
- tool: string;
49
- toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall;
50
- } | undefined, TInput>;
205
+ onMessage: (callback: (message: AgentMessageHistory) => void) => void;
206
+ /**
207
+ * Selects agent data from its context.
208
+ */
209
+ select: <T>(selector: (context: AgentMemoryContext) => T) => T;
210
+ /**
211
+ * Inspects state machine actor transitions and automatically observes
212
+ * (prevState, event, state) tuples.
213
+ */
214
+ interact: <TActor extends AnyActorRef>(actorRef: TActor, getInput?: (observation: AgentObservation<TActor>) => AgentDecisionInput | undefined) => Subscription;
215
+ };
216
+ type AnyAgent = Agent<any>;
217
+ type FromAgent<T> = T | ((self: AnyAgent) => T | Promise<T>);
218
+ interface CommonTextOptions {
219
+ prompt: FromAgent<string>;
220
+ model?: LanguageModel;
221
+ context?: Record<string, any>;
222
+ messages?: FromAgent<CoreMessage[]> | true;
223
+ template?: PromptTemplate<any>;
224
+ }
225
+ type AgentGenerateTextOptions = Omit<GenerateTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
226
+ type AgentStreamTextOptions = Omit<StreamTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
227
+ interface ObservedState {
228
+ /**
229
+ * The current state value of the state machine, e.g.
230
+ * `"loading"` or `"processing"` or `"ready"`
231
+ */
232
+ value: StateValue;
233
+ /**
234
+ * Additional contextual data related to the current state
235
+ */
236
+ context: Record<string, unknown>;
51
237
  }
52
- interface Tool<TInput, TOutput> {
53
- description: string;
54
- inputSchema: any;
55
- run: (input: TInput) => TOutput;
238
+ type ObservedStateFrom<TActor extends AnyActorRef> = Pick<SnapshotFrom<TActor>, 'value' | 'context'>;
239
+ type AgentMemoryContext = {
240
+ observations: AgentObservation<any>[];
241
+ messages: AgentMessageHistory[];
242
+ plans: AgentPlan<any>[];
243
+ feedback: AgentFeedback[];
244
+ };
245
+ type AgentMemory = AppendOnlyStorage<AgentMemoryContext>;
246
+ interface AppendOnlyStorage<T extends Record<string, any[]>> {
247
+ append<K extends keyof T>(sessionId: string, key: K, item: T[K][0]): Promise<void>;
248
+ getAll<K extends keyof T>(sessionId: string, key: K): Promise<T[K] | undefined>;
56
249
  }
250
+ interface AgentLongTermMemory {
251
+ get<K extends keyof AgentMemoryContext>(key: K): Promise<AgentMemoryContext[K]>;
252
+ append<K extends keyof AgentMemoryContext>(key: K, item: AgentMemoryContext[K][0]): Promise<void>;
253
+ set<K extends keyof AgentMemoryContext>(key: K, items: AgentMemoryContext[K]): Promise<void>;
254
+ }
255
+ interface AIAdapter {
256
+ generateText: typeof generateText;
257
+ streamText: typeof streamText;
258
+ }
259
+
260
+ type ZodEventMapping = {
261
+ [eventType: string]: SomeZodObject;
262
+ };
263
+
264
+ declare function createAgent<const TEventSchemas extends ZodEventMapping, TEvents extends EventObject = EventsFromZodEventMapping<TEventSchemas>>({ name, description, model, events, planner, stringify, getMemory, logic, adapter, ...generateTextOptions }: {
265
+ /**
266
+ * The name of the agent
267
+ */
268
+ name: string;
269
+ /**
270
+ * A description of the role of the agent
271
+ */
272
+ description?: string;
273
+ /**
274
+ * Events that the agent can cause (send) in an environment
275
+ * that the agent knows about.
276
+ */
277
+ events: TEventSchemas;
278
+ planner?: AgentPlanner<Agent<TEvents>>;
279
+ stringify?: typeof JSON.stringify;
280
+ /**
281
+ * A function that retrieves the agent's long term memory
282
+ */
283
+ getMemory?: (agent: Agent<any>) => AgentLongTermMemory;
284
+ /**
285
+ * Agent logic
286
+ */
287
+ logic?: AgentLogic<TEvents>;
288
+ adapter?: AIAdapter;
289
+ } & GenerateTextOptions): Agent<TEvents>;
290
+
291
+ declare function agentGenerateText<T extends Agent<any>>(agent: T, options: AgentGenerateTextOptions): Promise<GenerateTextResult<Record<string, CoreTool<any, any>>>>;
292
+ declare function fromTextStream<T extends Agent<any>>(agent: T, defaultOptions?: AgentStreamTextOptions): ObservableActorLogic<{
293
+ textDelta: string;
294
+ }, Omit<AgentStreamTextOptions, 'context'> & {
295
+ context?: AgentStreamTextOptions['context'] | boolean;
296
+ }>;
297
+ declare function fromText<T extends Agent<any>>(agent: T, defaultOptions?: AgentGenerateTextOptions): PromiseActorLogic<GenerateTextResult<Record<string, CoreTool<any, any>>>, Omit<AgentGenerateTextOptions, 'context'> & {
298
+ context?: AgentGenerateTextOptions['context'] | boolean;
299
+ }>;
57
300
 
58
- declare function createOpenAIAdapter<T extends {
59
- model: ChatCompletionCreateParamsBase['model'];
60
- }>(openai: OpenAI, settings: T): StatelyAgentAdapter;
301
+ declare function agentDecide<T extends Agent<any>>(agent: T, options: AgentDecideOptions): Promise<AgentPlan<any> | undefined>;
302
+ declare function fromDecision(agent: Agent<any>, defaultInput?: AgentDecisionInput): AgentDecisionLogic<any>;
61
303
 
62
- export { createAgent, createOpenAIAdapter, defineEvents };
304
+ export { type AIAdapter, type Agent, type AgentDecideOptions, type AgentDecisionInput, type AgentDecisionLogic, type AgentEmitted, type AgentFeedback, type AgentFeedbackInput, type AgentGenerateTextOptions, type AgentLogic, type AgentLongTermMemory, type AgentMemory, type AgentMemoryContext, type AgentMessageHistory, type AgentMessageHistoryInput, type AgentObservation, type AgentObservationInput, type AgentPlan, type AgentPlanInput, type AgentPlanner, type AgentStreamTextOptions, type AnyAgent, type AppendOnlyStorage, type CommonTextOptions, type EventsFromZodEventMapping, type FromAgent, type GenerateTextOptions, type ObservedState, type ObservedStateFrom, type PromptTemplate, type StreamTextOptions, type TransitionData, agentDecide, agentGenerateText, createAgent, fromDecision, fromText, fromTextStream };