@ai.ntellect/core 0.7.14 → 0.8.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 (98) hide show
  1. package/dist/graph/event-manager.d.ts +9 -1
  2. package/dist/graph/event-manager.d.ts.map +1 -1
  3. package/dist/graph/event-manager.js +115 -37
  4. package/dist/graph/event-manager.js.map +1 -1
  5. package/dist/graph/index.d.ts +20 -1
  6. package/dist/graph/index.d.ts.map +1 -1
  7. package/dist/graph/index.js +59 -10
  8. package/dist/graph/index.js.map +1 -1
  9. package/dist/graph/node.d.ts +0 -24
  10. package/dist/graph/node.d.ts.map +1 -1
  11. package/dist/graph/node.js +2 -71
  12. package/dist/graph/node.js.map +1 -1
  13. package/dist/graph/observer.d.ts +6 -87
  14. package/dist/graph/observer.d.ts.map +1 -1
  15. package/dist/graph/observer.js +3 -116
  16. package/dist/graph/observer.js.map +1 -1
  17. package/dist/index.d.ts +1 -6
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -6
  20. package/dist/index.js.map +1 -1
  21. package/dist/interfaces/index.d.ts +10 -1
  22. package/dist/interfaces/index.d.ts.map +1 -1
  23. package/dist/interfaces/index.js.map +1 -1
  24. package/dist/modules/agent/agent.d.ts +35 -0
  25. package/dist/modules/agent/agent.d.ts.map +1 -0
  26. package/dist/modules/agent/agent.js +106 -0
  27. package/dist/modules/agent/agent.js.map +1 -0
  28. package/dist/modules/agent/base/executor.d.ts +51 -0
  29. package/dist/modules/agent/base/executor.d.ts.map +1 -0
  30. package/dist/modules/agent/base/executor.js +66 -0
  31. package/dist/modules/agent/base/executor.js.map +1 -0
  32. package/dist/modules/agent/base/index.d.ts +30 -0
  33. package/dist/modules/agent/base/index.d.ts.map +1 -0
  34. package/dist/modules/agent/base/index.js +100 -0
  35. package/dist/modules/agent/base/index.js.map +1 -0
  36. package/dist/modules/agent/generic-assistant.d.ts +20 -0
  37. package/dist/modules/agent/generic-assistant.d.ts.map +1 -0
  38. package/dist/modules/agent/generic-assistant.js +89 -0
  39. package/dist/modules/agent/generic-assistant.js.map +1 -0
  40. package/dist/modules/agent/generic-executor.d.ts +57 -0
  41. package/dist/modules/agent/generic-executor.d.ts.map +1 -0
  42. package/dist/modules/agent/generic-executor.js +200 -0
  43. package/dist/modules/agent/generic-executor.js.map +1 -0
  44. package/dist/modules/agent/llm-factory.d.ts +19 -0
  45. package/dist/modules/agent/llm-factory.d.ts.map +1 -0
  46. package/dist/modules/agent/llm-factory.js +56 -0
  47. package/dist/modules/agent/llm-factory.js.map +1 -0
  48. package/dist/modules/agent/prompt-builder.d.ts +35 -0
  49. package/dist/modules/agent/prompt-builder.d.ts.map +1 -0
  50. package/dist/modules/agent/prompt-builder.js +76 -0
  51. package/dist/modules/agent/prompt-builder.js.map +1 -0
  52. package/dist/modules/memory/adapters/in-memory/index.d.ts.map +1 -1
  53. package/dist/modules/memory/adapters/in-memory/index.js +4 -3
  54. package/dist/modules/memory/adapters/in-memory/index.js.map +1 -1
  55. package/dist/modules/memory/adapters/meilisearch/index.d.ts.map +1 -1
  56. package/dist/modules/memory/adapters/meilisearch/index.js +7 -4
  57. package/dist/modules/memory/adapters/meilisearch/index.js.map +1 -1
  58. package/dist/modules/memory/adapters/redis/index.d.ts.map +1 -1
  59. package/dist/modules/memory/adapters/redis/index.js +2 -1
  60. package/dist/modules/memory/adapters/redis/index.js.map +1 -1
  61. package/dist/modules/nlp/engine.d.ts +126 -0
  62. package/dist/modules/nlp/engine.d.ts.map +1 -0
  63. package/dist/modules/nlp/engine.js +300 -0
  64. package/dist/modules/nlp/engine.js.map +1 -0
  65. package/dist/modules/nlp/index.d.ts +27 -0
  66. package/dist/modules/nlp/index.d.ts.map +1 -0
  67. package/dist/modules/nlp/index.js +56 -0
  68. package/dist/modules/nlp/index.js.map +1 -0
  69. package/dist/types/agent.d.ts +233 -0
  70. package/dist/types/agent.d.ts.map +1 -0
  71. package/dist/types/agent.js +29 -0
  72. package/dist/types/agent.js.map +1 -0
  73. package/dist/types/index.d.ts +72 -18
  74. package/dist/types/index.d.ts.map +1 -1
  75. package/dist/utils/generate-action-schema.d.ts.map +1 -1
  76. package/graph/event-manager.ts +135 -42
  77. package/graph/index.ts +57 -4
  78. package/graph/node.ts +2 -104
  79. package/graph/observer.ts +9 -215
  80. package/index.ts +2 -7
  81. package/interfaces/index.ts +12 -0
  82. package/modules/agent/agent.ts +108 -0
  83. package/modules/agent/base/executor.ts +100 -0
  84. package/modules/agent/base/index.ts +99 -0
  85. package/modules/agent/generic-assistant.ts +90 -0
  86. package/modules/agent/generic-executor.ts +259 -0
  87. package/modules/agent/llm-factory.ts +47 -0
  88. package/modules/agent/prompt-builder.ts +78 -0
  89. package/modules/memory/adapters/in-memory/index.ts +4 -3
  90. package/modules/memory/adapters/meilisearch/index.ts +7 -4
  91. package/modules/memory/adapters/redis/index.ts +2 -1
  92. package/modules/nlp/engine.ts +325 -0
  93. package/modules/nlp/index.ts +45 -0
  94. package/package.json +5 -2
  95. package/test/graph/index.test.ts +6 -4
  96. package/test/graph/node.test.ts +18 -14
  97. package/types/agent.ts +174 -0
  98. package/types/index.ts +74 -18
package/graph/observer.ts CHANGED
@@ -11,25 +11,15 @@ import {
11
11
  filter,
12
12
  map,
13
13
  share,
14
- startWith,
15
14
  take,
16
15
  takeUntil,
17
- timeout,
18
16
  } from "rxjs/operators";
19
17
  import { ZodSchema } from "zod";
20
18
  import { GraphObservable } from "../interfaces";
21
- import { GraphContext, GraphEvent } from "../types";
19
+ import { GraphContext, GraphEvent, ObserverOptions } from "../types";
20
+ import { GraphEventManager } from "./event-manager";
22
21
  import { GraphFlow } from "./index";
23
22
 
24
- interface ObserverOptions {
25
- debounce?: number;
26
- delay?: number;
27
- stream?: boolean;
28
- properties?: (string | number)[]; // Accepte uniquement string ou number comme clés
29
- onStreamLetter?: (data: { letter: string; property: string }) => void;
30
- onStreamComplete?: () => void;
31
- }
32
-
33
23
  /**
34
24
  * GraphObserver class provides reactive observation capabilities for a GraphFlow instance
35
25
  * It allows monitoring state changes, node updates, and specific events in the graph
@@ -40,18 +30,13 @@ export class GraphObserver<T extends ZodSchema> {
40
30
  private graph: GraphFlow<T>,
41
31
  private eventSubject: Subject<GraphEvent<T>>,
42
32
  private stateSubject: BehaviorSubject<GraphContext<T>>,
43
- private destroySubject: Subject<void>
33
+ private destroySubject: Subject<void>,
34
+ private eventManager: GraphEventManager<T>
44
35
  ) {}
45
36
 
46
37
  /**
47
38
  * Observes the entire graph state changes
48
39
  * @param options Configuration options for the observation
49
- * @param options.debounce Debounce time in milliseconds
50
- * @param options.delay Delay between emissions in milliseconds
51
- * @param options.stream If true, streams the specified properties letter by letter
52
- * @param options.properties List of properties to stream
53
- * @param options.onStreamLetter Callback for each letter emitted during streaming
54
- * @param options.onStreamComplete Callback when streaming is complete
55
40
  * @returns An Observable that emits the complete graph context whenever it changes
56
41
  */
57
42
  state(options: ObserverOptions = {}): GraphObservable<T> {
@@ -78,7 +63,6 @@ export class GraphObserver<T extends ZodSchema> {
78
63
  )
79
64
  .subscribe(subscriber);
80
65
 
81
- // Stream the specified properties if specified
82
66
  if (options.stream && options.properties) {
83
67
  const context = this.stateSubject.getValue();
84
68
  options.properties.forEach((property) => {
@@ -99,7 +83,6 @@ export class GraphObserver<T extends ZodSchema> {
99
83
  return () => subscription.unsubscribe();
100
84
  });
101
85
 
102
- // Extend the observable with our custom methods
103
86
  return Object.assign(baseObservable, {
104
87
  state: () => this.stateSubject.asObservable(),
105
88
  node: (nodeName: string) =>
@@ -140,214 +123,25 @@ export class GraphObserver<T extends ZodSchema> {
140
123
  }) as GraphObservable<T>;
141
124
  }
142
125
 
143
- /**
144
- * Observes state changes for a specific node
145
- * @param name - The name of the node to observe
146
- * @returns An Observable that emits the graph context when the specified node changes
147
- */
148
- node(name: string): Observable<GraphContext<T>> {
149
- return this.eventSubject.pipe(
150
- filter(
151
- (event) =>
152
- event.type === "nodeStateChanged" && event.payload?.name === name
153
- ),
154
- map((event) => event.payload.context),
155
- distinctUntilChanged(
156
- (prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)
157
- ),
158
- takeUntil(this.destroySubject),
159
- share()
160
- );
161
- }
162
-
163
- /**
164
- * Observes state changes for multiple nodes
165
- * @param names - Array of node names to observe
166
- * @returns An Observable that emits the graph context when any of the specified nodes change
167
- */
168
- nodes(names: string[]): Observable<GraphContext<T>> {
169
- return this.eventSubject.pipe(
170
- filter(
171
- (event) =>
172
- names.includes(event.payload?.name ?? "") &&
173
- event.type === "nodeStateChanged"
174
- ),
175
- map(() => this.graph.getContext()),
176
- distinctUntilChanged(
177
- (prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)
178
- ),
179
- takeUntil(this.destroySubject),
180
- share()
181
- );
182
- }
183
-
184
- /**
185
- * Observes specific properties of the graph context
186
- * @param keys - Single or multiple property keys to observe
187
- * @returns An Observable that emits an object containing only the specified properties
188
- * @template K - The key of the property to observe from GraphContext<T>
189
- */
190
- property<K extends keyof GraphContext<T>>(
191
- keys: K | K[]
192
- ): Observable<{ [P in K]: GraphContext<T>[P] } & { name: string }> {
193
- const properties = Array.isArray(keys) ? keys : [keys];
194
-
195
- return this.eventSubject.pipe(
196
- filter(
197
- (event) =>
198
- event.type === "nodeStateChanged" &&
199
- properties.some((key) => event.payload?.property === key)
200
- ),
201
- map((event) => ({
202
- ...properties.reduce(
203
- (obj, key) => ({
204
- ...obj,
205
- [key]: event.payload.context[key],
206
- }),
207
- {} as { [P in K]: GraphContext<T>[P] }
208
- ),
209
- name: event.payload.name as string,
210
- })),
211
- startWith({
212
- ...properties.reduce(
213
- (obj, key) => ({
214
- ...obj,
215
- [key]: this.stateSubject.value[key],
216
- }),
217
- {}
218
- ),
219
- name: "initial",
220
- } as { [P in K]: GraphContext<T>[P] } & { name: string }),
221
- distinctUntilChanged(
222
- (prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)
223
- ),
224
- share()
225
- );
226
- }
227
-
228
- /**
229
- * Observes specific events in the graph
230
- * @param type - The type of event to observe
231
- * @returns An Observable that emits events of the specified type
232
- */
233
- event(type: string): Observable<GraphEvent<T>> {
234
- return this.eventSubject.pipe(
235
- filter((event) => event.type === type),
236
- map((event) => event),
237
- takeUntil(this.destroySubject),
238
- share()
239
- );
240
- }
241
-
242
- /**
243
- * Waits for a specific condition to be met on an observable
244
- * @param observable - The Observable to watch
245
- * @param predicate - A function that returns true when the desired condition is met
246
- * @returns A Promise that resolves with the value when the predicate returns true
247
- * @template R - The type of value emitted by the observable
248
- */
249
- until<R>(
250
- observable: Observable<R>,
251
- predicate: (value: R) => boolean
252
- ): Promise<R> {
253
- return new Promise((resolve) => {
254
- const subscription = observable.subscribe({
255
- next: (value) => {
256
- if (predicate(value)) {
257
- subscription.unsubscribe();
258
- resolve(value);
259
- }
260
- },
261
- });
262
- });
263
- }
264
-
265
126
  /**
266
127
  * Waits for correlated events to occur and validates them using a correlation function
267
- * @param eventTypes - Array of event types to wait for
268
- * @param timeoutMs - Timeout duration in milliseconds
269
- * @param correlationFn - Function to validate the correlation between events
270
- * @returns Promise that resolves when all correlated events are received
271
128
  */
272
129
  waitForCorrelatedEvents(
273
130
  eventTypes: string[],
274
131
  timeoutMs: number,
275
132
  correlationFn: (events: GraphEvent<T>[]) => boolean
276
133
  ): Promise<GraphEvent<T>[]> {
277
- return new Promise((resolve, reject) => {
278
- const eventObservables = eventTypes.map((eventType) =>
279
- this.eventSubject.pipe(
280
- filter((event): event is GraphEvent<T> => {
281
- return event.type === eventType && "timestamp" in event;
282
- }),
283
- take(1)
284
- )
285
- );
286
-
287
- combineLatest(eventObservables)
288
- .pipe(timeout(timeoutMs), take(1))
289
- .subscribe({
290
- next: (events) => {
291
- if (correlationFn(events)) {
292
- resolve(events);
293
- } else {
294
- reject(new Error(`Correlation validation failed`));
295
- }
296
- },
297
- error: (error) => reject(error),
298
- });
299
- });
300
- }
301
-
302
- /**
303
- * Observes the current state of the graph
304
- * @returns Observable that emits the current graph context
305
- */
306
- observeState(): Observable<GraphContext<T>> {
307
- return this.stateSubject.asObservable().pipe(
308
- takeUntil(this.destroySubject),
309
- distinctUntilChanged(
310
- (prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)
311
- )
312
- );
313
- }
314
-
315
- /**
316
- * Observes specific event types in the graph
317
- * @param eventType - The type of event to observe
318
- * @returns Observable that emits events of the specified type
319
- */
320
- observeEvents(eventType: string): Observable<GraphEvent<T>> {
321
- return this.eventSubject.asObservable().pipe(
322
- takeUntil(this.destroySubject),
323
- filter((event) => event.type === eventType)
324
- );
325
- }
326
-
327
- /**
328
- * Observes state changes for a specific node
329
- * @param nodeName - The name of the node to observe
330
- * @returns Observable that emits the graph context when the specified node changes
331
- */
332
- observeNodeState(nodeName: string): Observable<GraphContext<T>> {
333
- return this.eventSubject.asObservable().pipe(
334
- takeUntil(this.destroySubject),
335
- filter(
336
- (event) =>
337
- event.type === "nodeStateChanged" && event.payload?.name === nodeName
338
- ),
339
- map(() => this.stateSubject.value)
134
+ return this.eventManager.waitForCorrelatedEvents(
135
+ eventTypes,
136
+ timeoutMs,
137
+ correlationFn
340
138
  );
341
139
  }
342
140
 
343
141
  /**
344
142
  * Streams a message letter by letter with a specified delay
345
- * @param message - The message to stream
346
- * @param delayMs - The delay in milliseconds between each letter
347
- * @param property - The property name being streamed
348
- * @returns An Observable that emits each letter of the message along with its property
349
143
  */
350
- streamMessage(
144
+ private streamMessage(
351
145
  message: string,
352
146
  delayMs: number,
353
147
  property: string
package/index.ts CHANGED
@@ -11,6 +11,8 @@
11
11
  * - Utility functions for action schema generation and header building
12
12
  */
13
13
 
14
+ export * from "./modules/agent/agent";
15
+
14
16
  export * from "./graph/controller";
15
17
  export * from "./graph/event-manager";
16
18
  export * from "./graph/index";
@@ -18,16 +20,9 @@ export * from "./graph/node";
18
20
  export * from "./graph/observer";
19
21
  export * from "./graph/visualizer";
20
22
 
21
- export * from "./modules/memory";
22
- export * from "./modules/memory/adapters/in-memory";
23
- export * from "./modules/memory/adapters/meilisearch";
24
- export * from "./modules/memory/adapters/redis";
25
-
26
23
  export * from "./interfaces";
27
24
  export * from "./modules/agenda";
28
- export * from "./modules/agenda/adapters/node-cron";
29
25
  export * from "./modules/embedding";
30
- export * from "./modules/embedding/adapters/ai";
31
26
 
32
27
  export * from "./types";
33
28
 
@@ -5,6 +5,7 @@ import {
5
5
  CreateMemoryInput,
6
6
  GraphContext,
7
7
  GraphEvent,
8
+ GraphNodeConfig,
8
9
  ScheduledRequest,
9
10
  SchemaType,
10
11
  } from "../types";
@@ -546,3 +547,14 @@ export interface GraphObservable<T extends ZodSchema> extends Observable<any> {
546
547
  predicate: (state: any) => boolean
547
548
  ): Promise<any>;
548
549
  }
550
+
551
+ export interface NLPNodeConfig<T extends ZodSchema>
552
+ extends Omit<GraphNodeConfig<T>, "execute"> {
553
+ nlpConfig: {
554
+ corpus?: any;
555
+ responses?: Record<string, any>;
556
+ entities?: Record<string, any>;
557
+ language?: string;
558
+ };
559
+ intentHandlers?: Record<string, (data: any) => Promise<any>>;
560
+ }
@@ -0,0 +1,108 @@
1
+ import { GraphFlow } from "../../graph/index";
2
+ import {
3
+ AgentConfig,
4
+ AgentContext,
5
+ AgentContextSchema,
6
+ } from "../../types/agent";
7
+ import { BaseAgent } from "./base";
8
+ import { GenericExecutor } from "./generic-executor";
9
+
10
+ /**
11
+ * A generic assistant that can be configured with different roles, goals, and personalities
12
+ * @class Agent
13
+ * @example
14
+ * const assistant = new Agent({
15
+ * role: "Email Assistant",
16
+ * goal: "Help users send emails efficiently",
17
+ * backstory: "I am a professional and friendly assistant who specializes in email communication",
18
+ * llmConfig: { provider: "openai", model: "gpt-4" }
19
+ * tools: []
20
+ * });
21
+ */
22
+ export class Agent {
23
+ private executor: GenericExecutor;
24
+ private workflow: GraphFlow<typeof AgentContextSchema>;
25
+
26
+ /**
27
+ * Creates an instance of Agent
28
+ * @param {AgentConfig} config - Configuration for the agent
29
+ */
30
+ constructor(config: AgentConfig) {
31
+ const agent = new BaseAgent({
32
+ role: config.role,
33
+ goal: config.goal,
34
+ backstory: config.backstory,
35
+ tools: config.tools,
36
+ memory: config.memory,
37
+ llmConfig: config.llmConfig,
38
+ });
39
+
40
+ this.executor = new GenericExecutor(agent, config.tools, {
41
+ llmConfig: config.llmConfig,
42
+ verbose: config.verbose,
43
+ });
44
+
45
+ this.workflow = this.setupWorkflow();
46
+ }
47
+
48
+ /**
49
+ * Sets up the workflow for processing inputs and executing actions
50
+ * @private
51
+ * @returns {GraphFlow<typeof AgentContextSchema>} The configured workflow
52
+ */
53
+ private setupWorkflow(): GraphFlow<typeof AgentContextSchema> {
54
+ return new GraphFlow("assistant", {
55
+ name: "assistant",
56
+ schema: AgentContextSchema,
57
+ context: {
58
+ input: { raw: "" },
59
+ actions: [],
60
+ response: "",
61
+ executedActions: [],
62
+ },
63
+ nodes: [
64
+ {
65
+ name: "process",
66
+ execute: async (context) => {
67
+ const agentContext = context as unknown as AgentContext;
68
+ const decision = await this.executor.makeDecision(agentContext);
69
+ context.actions = decision.actions;
70
+ context.response = decision.response;
71
+ },
72
+ next: (context) => (context.actions.length > 0 ? ["execute"] : []),
73
+ },
74
+ {
75
+ name: "execute",
76
+ execute: async (context) => {
77
+ console.log(`Executing actions:`);
78
+ console.log(context.actions);
79
+ const timestamp = new Date().toISOString();
80
+ context.knowledge = `Date: ${timestamp}\n${JSON.stringify(
81
+ context.actions
82
+ )}`;
83
+ await this.executor.executeActions(
84
+ context.actions,
85
+ context as unknown as AgentContext
86
+ );
87
+ },
88
+ next: ["process"],
89
+ },
90
+ ],
91
+ });
92
+ }
93
+
94
+ /**
95
+ * Processes an input string through the agent's workflow
96
+ * @param {string} input - The input string to process
97
+ * @returns {Promise<AgentContext>} The resulting context after processing
98
+ */
99
+ public async process(input: string): Promise<AgentContext> {
100
+ await this.workflow.execute("process", undefined, {
101
+ input: { raw: input },
102
+ actions: [],
103
+ response: "",
104
+ });
105
+
106
+ return this.workflow.getContext() as unknown as AgentContext;
107
+ }
108
+ }
@@ -0,0 +1,100 @@
1
+ import { BaseAgent } from ".";
2
+ import { GraphFlow } from "../../../graph";
3
+ import {
4
+ ActionSchema,
5
+ AgentContext,
6
+ DecisionOutput,
7
+ } from "../../../types/agent";
8
+
9
+ /**
10
+ * Abstract base class for agent executors that handle action execution
11
+ * @abstract
12
+ * @class AgentExecutor
13
+ */
14
+ export abstract class AgentExecutor {
15
+ protected agent: BaseAgent;
16
+ protected availableGraphs: Map<string, GraphFlow<any>>;
17
+
18
+ /**
19
+ * Creates an instance of AgentExecutor
20
+ * @param {BaseAgent} agent - The agent instance this executor is tied to
21
+ * @param {GraphFlow<any>[]} graphs - Array of available graph flows that can be executed
22
+ */
23
+ constructor(agent: BaseAgent, graphs: GraphFlow<any>[]) {
24
+ this.agent = agent;
25
+ this.availableGraphs = new Map(graphs.map((g) => [g.name, g]));
26
+ }
27
+
28
+ /**
29
+ * Makes a decision based on the current context
30
+ * @abstract
31
+ * @param {any} context - The context to base the decision on
32
+ * @returns {Promise<DecisionOutput>} The decision output containing actions and response
33
+ */
34
+ abstract makeDecision(context: any): Promise<DecisionOutput>;
35
+
36
+ /**
37
+ * Executes a list of actions in the given context
38
+ * @param {ActionSchema[]} actions - Array of actions to execute
39
+ * @param {AgentContext} context - The context in which to execute the actions
40
+ * @returns {Promise<void>}
41
+ */
42
+ async executeActions(
43
+ actions: ActionSchema[],
44
+ context: AgentContext
45
+ ): Promise<void> {
46
+ const workflowsToExecute: GraphFlow<any>[] = [];
47
+ const startNodes: string[] = [];
48
+ const inputs: any[] = [];
49
+
50
+ for (const action of actions) {
51
+ const workflow = this.availableGraphs.get(action.name);
52
+ if (!workflow) continue;
53
+
54
+ workflowsToExecute.push(workflow);
55
+ startNodes.push(workflow.getNodes()[0].name);
56
+ inputs.push(this.prepareActionInputs(action.parameters));
57
+ }
58
+
59
+ if (workflowsToExecute.length > 0) {
60
+ await this.executeWorkflows(
61
+ workflowsToExecute,
62
+ startNodes,
63
+ inputs,
64
+ context
65
+ );
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Prepares the input parameters for an action
71
+ * @private
72
+ * @param {Array<{name: string, value: any}>} parameters - Array of parameter objects
73
+ * @returns {Record<string, any>} Object with parameter names as keys and their values
74
+ */
75
+ private prepareActionInputs(
76
+ parameters: Array<{ name: string; value: any }>
77
+ ): Record<string, any> {
78
+ return parameters.reduce((acc, param) => {
79
+ acc[param.name] = param.value;
80
+ return acc;
81
+ }, {} as Record<string, any>);
82
+ }
83
+
84
+ /**
85
+ * Executes multiple workflows with their respective inputs
86
+ * @protected
87
+ * @abstract
88
+ * @param {GraphFlow<any>[]} workflows - Array of workflows to execute
89
+ * @param {string[]} startNodes - Array of starting node names for each workflow
90
+ * @param {any[]} inputs - Array of inputs for each workflow
91
+ * @param {AgentContext} context - The context in which to execute the workflows
92
+ * @returns {Promise<void>}
93
+ */
94
+ protected abstract executeWorkflows(
95
+ workflows: GraphFlow<any>[],
96
+ startNodes: string[],
97
+ inputs: any[],
98
+ context: AgentContext
99
+ ): Promise<void>;
100
+ }
@@ -0,0 +1,99 @@
1
+ import { AgentConfig } from "@/types/agent";
2
+ import { BaseMemoryType } from "../../../types";
3
+ import { Memory } from "../../memory";
4
+
5
+ /**
6
+ * Base agent class that handles role, goal, and personality management
7
+ * @class BaseAgent
8
+ */
9
+ export class BaseAgent {
10
+ private config: AgentConfig;
11
+ private memory?: Memory;
12
+
13
+ constructor(config: AgentConfig) {
14
+ this.config = config;
15
+ this.memory = config.memory;
16
+ }
17
+
18
+ async execute(context: any, inputs?: any): Promise<any> {
19
+ // Log execution if verbose
20
+ if (this.config.verbose) {
21
+ console.log(`Agent ${this.config.role} executing...`);
22
+ console.log("Context:", context);
23
+ console.log("Inputs:", inputs);
24
+ }
25
+
26
+ // Store context in memory if available
27
+ if (this.memory) {
28
+ await this.storeInMemory({
29
+ type: "execution",
30
+ content: JSON.stringify({ context, inputs }),
31
+ metadata: {
32
+ role: this.config.role,
33
+ timestamp: new Date().toISOString(),
34
+ },
35
+ });
36
+ }
37
+
38
+ // Execute tools if available
39
+ if (this.config.tools) {
40
+ for (const tool of this.config.tools) {
41
+ try {
42
+ const result = await tool.execute(context, inputs);
43
+ context = { ...context, ...result };
44
+ } catch (error) {
45
+ console.error(`Tool execution failed:`, error);
46
+ }
47
+ }
48
+ }
49
+
50
+ return context;
51
+ }
52
+
53
+ private async storeInMemory(data: {
54
+ type: string;
55
+ content: string;
56
+ metadata?: Record<string, any>;
57
+ }): Promise<BaseMemoryType | undefined> {
58
+ if (!this.memory) return;
59
+
60
+ return this.memory.createMemory({
61
+ content: data.content,
62
+ metadata: data.metadata,
63
+ roomId: "default",
64
+ });
65
+ }
66
+
67
+ public async recall(query: string): Promise<BaseMemoryType[]> {
68
+ if (!this.memory) return [];
69
+
70
+ return this.memory.getMemoryByIndex(query, {
71
+ roomId: "default",
72
+ limit: 10,
73
+ });
74
+ }
75
+
76
+ /**
77
+ * Get the agent's role - what function/job it performs
78
+ * @returns {string} The agent's role
79
+ */
80
+ public getRole(): string {
81
+ return this.config.role;
82
+ }
83
+
84
+ /**
85
+ * Get the agent's goal - what it tries to achieve
86
+ * @returns {string} The agent's goal
87
+ */
88
+ public getGoal(): string {
89
+ return this.config.goal;
90
+ }
91
+
92
+ /**
93
+ * Get the agent's backstory - its personality and behavioral traits
94
+ * @returns {string} The agent's backstory
95
+ */
96
+ public getBackstory(): string {
97
+ return this.config.backstory;
98
+ }
99
+ }