@ai.ntellect/core 0.8.1 → 0.8.3
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.
- package/README.md +190 -118
- package/dist/graph/controller.d.ts +4 -5
- package/dist/graph/controller.d.ts.map +1 -1
- package/dist/graph/controller.js +10 -10
- package/dist/graph/controller.js.map +1 -1
- package/dist/graph/event-manager.d.ts.map +1 -1
- package/dist/graph/event-manager.js +4 -4
- package/dist/graph/event-manager.js.map +1 -1
- package/dist/graph/index.d.ts +5 -16
- package/dist/graph/index.d.ts.map +1 -1
- package/dist/graph/index.js +32 -52
- package/dist/graph/index.js.map +1 -1
- package/dist/graph/node.d.ts +1 -10
- package/dist/graph/node.d.ts.map +1 -1
- package/dist/graph/node.js +7 -36
- package/dist/graph/node.js.map +1 -1
- package/dist/graph/observer.d.ts +4 -0
- package/dist/graph/observer.d.ts.map +1 -1
- package/dist/graph/observer.js +27 -1
- package/dist/graph/observer.js.map +1 -1
- package/dist/modules/agent/agent.d.ts.map +1 -1
- package/dist/modules/agent/agent.js +3 -6
- package/dist/modules/agent/agent.js.map +1 -1
- package/dist/modules/agent/generic-assistant.d.ts.map +1 -1
- package/dist/modules/agent/generic-assistant.js +3 -3
- package/dist/modules/agent/generic-assistant.js.map +1 -1
- package/dist/modules/agent/generic-executor.d.ts +1 -0
- package/dist/modules/agent/generic-executor.d.ts.map +1 -1
- package/dist/modules/agent/generic-executor.js +24 -35
- package/dist/modules/agent/generic-executor.js.map +1 -1
- package/dist/modules/agent/llm-factory.d.ts.map +1 -1
- package/dist/types/index.d.ts +90 -25
- package/dist/types/index.d.ts.map +1 -1
- package/graph/controller.ts +10 -11
- package/graph/event-manager.ts +2 -14
- package/graph/index.ts +37 -67
- package/graph/node.ts +5 -39
- package/graph/observer.ts +35 -5
- package/modules/agent/agent.ts +7 -8
- package/modules/agent/generic-assistant.ts +7 -5
- package/modules/agent/generic-executor.ts +33 -40
- package/package.json +1 -1
- package/test/graph/controller.test.ts +62 -17
- package/test/graph/index.test.ts +128 -133
- package/test/graph/node.test.ts +38 -233
- package/test/graph/observer.test.ts +18 -23
- package/types/index.ts +91 -28
@@ -17,6 +17,7 @@ const chalk_1 = __importDefault(require("chalk"));
|
|
17
17
|
const zod_1 = require("zod");
|
18
18
|
const executor_1 = require("./base/executor");
|
19
19
|
const llm_factory_1 = require("./llm-factory");
|
20
|
+
const prompt_builder_1 = require("./prompt-builder");
|
20
21
|
/**
|
21
22
|
* Generic executor that handles the interaction between the agent and LLM
|
22
23
|
* Uses a structured prompt format:
|
@@ -86,6 +87,25 @@ ${graph
|
|
86
87
|
})
|
87
88
|
.join("\n\n");
|
88
89
|
}
|
90
|
+
buildSystemPrompt(context) {
|
91
|
+
return __awaiter(this, void 0, void 0, function* () {
|
92
|
+
return new prompt_builder_1.PromptBuilder()
|
93
|
+
.addSection("ROLE", this.agent.getRole())
|
94
|
+
.addSection("GOAL", this.agent.getGoal())
|
95
|
+
.addSection("BACKSTORY", this.agent.getBackstory())
|
96
|
+
.addSection("RECENT ACTIONS (check this before deciding what to do)", context.knowledge || "None")
|
97
|
+
.addSection("AVAILABLE ACTIONS (only if you need)", this.generateActionSchema())
|
98
|
+
.addSection("INSTRUCTIONS", `
|
99
|
+
- Never take actions if an recent action matches the user's input
|
100
|
+
- If you need to take actions, structure parameters according to the action's schema
|
101
|
+
- If goal is achieved, explain that you achieved for examples:
|
102
|
+
- "I have achieved the goal"
|
103
|
+
- "I have done what I needed to do"
|
104
|
+
- "I have completed the task"
|
105
|
+
`)
|
106
|
+
.build(context);
|
107
|
+
});
|
108
|
+
}
|
89
109
|
/**
|
90
110
|
* Makes a decision based on the current context using the LLM
|
91
111
|
* @param {AgentContext} context - The context to base the decision on
|
@@ -93,44 +113,13 @@ ${graph
|
|
93
113
|
*/
|
94
114
|
makeDecision(context) {
|
95
115
|
return __awaiter(this, void 0, void 0, function* () {
|
96
|
-
var _a;
|
97
116
|
this.log("thinking", chalk_1.default.dim("Analyzing context and available actions..."));
|
98
|
-
const
|
99
|
-
|
100
|
-
this.log("info", chalk_1.default.dim("Retrieved relevant memories:"));
|
101
|
-
memories.forEach((m) => this.log("info", chalk_1.default.dim(`- ${m.content}`)));
|
102
|
-
context.knowledge =
|
103
|
-
(context.knowledge || "") +
|
104
|
-
"\n" +
|
105
|
-
memories.map((m) => m.content).join("\n");
|
106
|
-
}
|
107
|
-
const systemPrompt = `
|
108
|
-
## ROLE
|
109
|
-
${this.agent.getRole()}
|
110
|
-
|
111
|
-
## GOAL
|
112
|
-
${this.agent.getGoal()}
|
113
|
-
|
114
|
-
## BACKSTORY
|
115
|
-
${this.agent.getBackstory()}
|
116
|
-
|
117
|
-
## RECENT ACTIONS
|
118
|
-
${context.knowledge ? `${context.knowledge}\n` : "None"}
|
119
|
-
|
120
|
-
## AVAILABLE ACTIONS
|
121
|
-
${this.generateActionSchema()}
|
122
|
-
|
123
|
-
## INSTRUCTIONS
|
124
|
-
- Analyze the user input and what you have done (if no action is needed, just return an empty array)
|
125
|
-
- Choose appropriate actions based on their parameters
|
126
|
-
- Structure parameters according to the action's schema
|
127
|
-
- Look at the goal and the actions you have done, if you have achieved the goal, STOP
|
128
|
-
`;
|
117
|
+
const systemPrompt = yield this.buildSystemPrompt(context);
|
118
|
+
console.log({ systemPrompt });
|
129
119
|
this.log("info", chalk_1.default.dim("Generating response..."));
|
130
120
|
const result = yield this.llm.generate({
|
131
121
|
system: systemPrompt,
|
132
|
-
user: `User
|
133
|
-
Actions you have already done: ${((_a = context.executedActions) === null || _a === void 0 ? void 0 : _a.map((a) => `\n- ${a.name} => ${JSON.stringify(a.result)}`).join("")) || "None"}`,
|
122
|
+
user: `User sent you this message at ${new Date().toISOString()}\n${context.input.raw}`,
|
134
123
|
}, zod_1.z.object({
|
135
124
|
actions: zod_1.z.array(zod_1.z.object({
|
136
125
|
name: zod_1.z.string(),
|
@@ -181,7 +170,7 @@ ${graph
|
|
181
170
|
// Initialize workflow context with input
|
182
171
|
const workflowContext = Object.assign(Object.assign({}, workflow.getContext()), input);
|
183
172
|
// Execute with merged context
|
184
|
-
const result = yield workflow.execute(startNode,
|
173
|
+
const result = yield workflow.execute(startNode, workflowContext);
|
185
174
|
this.log("success", chalk_1.default.green(`Workflow ${workflow.name} completed`));
|
186
175
|
this.log("info", chalk_1.default.dim(`Result: ${JSON.stringify(result, null, 2)}`));
|
187
176
|
if (context.executedActions) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"generic-executor.js","sourceRoot":"","sources":["../../../modules/agent/generic-executor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,kDAA0B;AAC1B,6BAAwB;AASxB,8CAAgD;AAChD,+CAA2C;
|
1
|
+
{"version":3,"file":"generic-executor.js","sourceRoot":"","sources":["../../../modules/agent/generic-executor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,kDAA0B;AAC1B,6BAAwB;AASxB,8CAAgD;AAChD,+CAA2C;AAC3C,qDAAiD;AAEjD;;;;;;;;;;;GAWG;AACH,MAAa,eAAgB,SAAQ,wBAAa;IAIhD;;;;;OAKG;IACH,YACE,KAAgB,EAChB,MAAwB,EACxB,MAAsB;;QAEtB,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,MAAA,MAAM,CAAC,OAAO,mCAAI,IAAI,CAAC;QACtC,IAAI,CAAC,GAAG,GAAG,wBAAU,CAAC,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACpD,CAAC;IAED;;;;;OAKG;IACK,GAAG,CACT,IAA2D,EAC3D,OAAe;QAEf,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO;QAE1B,MAAM,MAAM,GAAG;YACb,IAAI,EAAE,eAAK,CAAC,IAAI,CAAC,GAAG,CAAC;YACrB,OAAO,EAAE,eAAK,CAAC,KAAK,CAAC,GAAG,CAAC;YACzB,OAAO,EAAE,eAAK,CAAC,MAAM,CAAC,GAAG,C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ACd,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;wBACnC,UAAU,EAAE,IAAI;qBACjB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;KAAA;CACF;AAjOD,0CAiOC"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"llm-factory.d.ts","sourceRoot":"","sources":["../../../modules/agent/llm-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGvD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;GAGG;AACH,qBAAa,UAAU;IACrB;;;;;;OAMG;IACH,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS
|
1
|
+
{"version":3,"file":"llm-factory.d.ts","sourceRoot":"","sources":["../../../modules/agent/llm-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGvD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;GAGG;AACH,qBAAa,UAAU;IACrB;;;;;;OAMG;IACH,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS;;;CA6BnC"}
|
package/dist/types/index.d.ts
CHANGED
@@ -65,12 +65,44 @@ export type GraphContext<T extends ZodSchema> = {
|
|
65
65
|
[key: string]: any;
|
66
66
|
};
|
67
67
|
/**
|
68
|
-
* Configuration for event handling in
|
68
|
+
* Configuration for event handling strategies in nodes
|
69
|
+
* @typedef {Object} EventStrategy
|
70
|
+
* @property {"single" | "all" | "correlate"} type - The type of event handling strategy
|
71
|
+
* - single: Waits for any single event from the specified events
|
72
|
+
* - all: Waits for all specified events to occur
|
73
|
+
* - correlate: Uses a correlation function to match related events
|
74
|
+
* @property {(events: any[]) => boolean} [correlation] - Optional correlation function for "correlate" strategy
|
69
75
|
*/
|
70
76
|
export type EventStrategy = {
|
71
77
|
type: "single" | "all" | "correlate";
|
72
78
|
correlation?: (events: any[]) => boolean;
|
73
79
|
};
|
80
|
+
/**
|
81
|
+
* Configuration for event handling in nodes
|
82
|
+
* @typedef {Object} EventConfig
|
83
|
+
* @property {string[]} events - Array of event names to wait for
|
84
|
+
* @property {number} [timeout] - Optional timeout in milliseconds
|
85
|
+
* @property {EventStrategy} strategy - Strategy for handling multiple events
|
86
|
+
* @property {(events: any[]) => Promise<void>} [onSuccess] - Optional callback when events are successfully received
|
87
|
+
* @property {() => Promise<void>} [onTimeout] - Optional callback when event waiting times out
|
88
|
+
* @example
|
89
|
+
* ```typescript
|
90
|
+
* const eventConfig: EventConfig = {
|
91
|
+
* events: ["payment.received", "order.validated"],
|
92
|
+
* timeout: 5000,
|
93
|
+
* strategy: {
|
94
|
+
* type: "correlate",
|
95
|
+
* correlation: (events) => events.every(e => e.transactionId === events[0].transactionId)
|
96
|
+
* },
|
97
|
+
* onSuccess: async (events) => {
|
98
|
+
* console.log("Correlated events received:", events);
|
99
|
+
* },
|
100
|
+
* onTimeout: async () => {
|
101
|
+
* console.log("Event waiting timed out");
|
102
|
+
* }
|
103
|
+
* };
|
104
|
+
* ```
|
105
|
+
*/
|
74
106
|
export type EventConfig = {
|
75
107
|
events: string[];
|
76
108
|
timeout?: number;
|
@@ -78,12 +110,60 @@ export type EventConfig = {
|
|
78
110
|
onSuccess?: (events: any[]) => Promise<void>;
|
79
111
|
onTimeout?: () => Promise<void>;
|
80
112
|
};
|
113
|
+
/**
|
114
|
+
* Represents an event in the graph system
|
115
|
+
* @template T - Schema type for context validation
|
116
|
+
* @property {string} type - The type/name of the event
|
117
|
+
* @property {any} [payload] - Optional payload data
|
118
|
+
* @property {number} timestamp - Unix timestamp of when the event occurred
|
119
|
+
* @example
|
120
|
+
* ```typescript
|
121
|
+
* const event: GraphEvent<MySchema> = {
|
122
|
+
* type: "payment.received",
|
123
|
+
* payload: {
|
124
|
+
* transactionId: "tx123",
|
125
|
+
* amount: 100,
|
126
|
+
* currency: "USD"
|
127
|
+
* },
|
128
|
+
* timestamp: Date.now()
|
129
|
+
* };
|
130
|
+
* ```
|
131
|
+
*/
|
132
|
+
export type GraphEvent<T extends ZodSchema> = {
|
133
|
+
type: string;
|
134
|
+
payload?: any;
|
135
|
+
timestamp: number;
|
136
|
+
};
|
137
|
+
/**
|
138
|
+
* Configuration for waiting on multiple events
|
139
|
+
* @template T - Schema type for context validation
|
140
|
+
* @property {string[]} events - Array of event names to wait for
|
141
|
+
* @property {number} [timeout] - Optional timeout in milliseconds
|
142
|
+
* @property {"all" | "any" | "race"} strategy - Strategy for handling multiple events
|
143
|
+
* @property {(context: GraphContext<T>) => Promise<void>} [onSuccess] - Optional success callback
|
144
|
+
* @example
|
145
|
+
* ```typescript
|
146
|
+
* const config: WaitForEvents<MySchema> = {
|
147
|
+
* events: ["event1", "event2"],
|
148
|
+
* timeout: 5000,
|
149
|
+
* strategy: "all",
|
150
|
+
* onSuccess: async (context) => {
|
151
|
+
* console.log("All events received");
|
152
|
+
* }
|
153
|
+
* };
|
154
|
+
* ```
|
155
|
+
*/
|
156
|
+
export type WaitForEvents<T extends ZodSchema> = {
|
157
|
+
events: string[];
|
158
|
+
timeout?: number;
|
159
|
+
strategy: "all" | "any" | "race";
|
160
|
+
onSuccess?: <T extends ZodSchema>(context: GraphContext<T>) => Promise<void>;
|
161
|
+
};
|
81
162
|
/**
|
82
163
|
* Interface representing a node in the graph
|
83
164
|
* @interface
|
84
165
|
* @template T - Schema type
|
85
|
-
* @template
|
86
|
-
* @template O - Output schema type
|
166
|
+
* @template P - Parameters type
|
87
167
|
*/
|
88
168
|
export interface GraphNodeConfig<T extends ZodSchema, P = any> {
|
89
169
|
/** Name of the node */
|
@@ -93,12 +173,12 @@ export interface GraphNodeConfig<T extends ZodSchema, P = any> {
|
|
93
173
|
/** Schema for node inputs */
|
94
174
|
params?: P extends void ? never : ZodSchema<P>;
|
95
175
|
/** Execute function for the node */
|
96
|
-
execute: (context: GraphContext<T>,
|
176
|
+
execute: (context: GraphContext<T>, tools?: {
|
97
177
|
eventEmitter: IEventEmitter;
|
98
178
|
}) => Promise<void>;
|
99
|
-
/** Optional condition for node
|
179
|
+
/** Optional condition for node execution */
|
100
180
|
condition?: (context: GraphContext<T>, params?: P) => boolean;
|
101
|
-
/** Array of next node names or objects with conditions
|
181
|
+
/** Array of next node names or objects with conditions */
|
102
182
|
next?: Array<string | {
|
103
183
|
node: string;
|
104
184
|
condition: (context: GraphContext<T>) => boolean;
|
@@ -109,13 +189,9 @@ export interface GraphNodeConfig<T extends ZodSchema, P = any> {
|
|
109
189
|
when?: EventConfig;
|
110
190
|
/** Retry configuration */
|
111
191
|
retry?: {
|
112
|
-
/** Maximum number of retry attempts */
|
113
192
|
maxAttempts: number;
|
114
|
-
/** Delay between retries in milliseconds */
|
115
193
|
delay: number;
|
116
|
-
/** Error handler function */
|
117
194
|
onRetryFailed?: (error: Error, context: GraphContext<T>) => Promise<void>;
|
118
|
-
/** Continue execution on failed retry */
|
119
195
|
continueOnFailed?: boolean;
|
120
196
|
};
|
121
197
|
/** Error handler function */
|
@@ -130,12 +206,12 @@ export interface GraphNodeConfig<T extends ZodSchema, P = any> {
|
|
130
206
|
export type GraphConfig<T extends ZodSchema> = {
|
131
207
|
/** Name of the graph */
|
132
208
|
name: string;
|
133
|
-
/** Array of nodes in the graph */
|
134
|
-
nodes: GraphNodeConfig<T, any>[];
|
135
|
-
/** Initial context */
|
136
|
-
context: SchemaType<T>;
|
137
209
|
/** Schema for validation */
|
138
210
|
schema: T;
|
211
|
+
/** Initial context */
|
212
|
+
context: SchemaType<T>;
|
213
|
+
/** Array of nodes in the graph */
|
214
|
+
nodes: GraphNodeConfig<T, any>[];
|
139
215
|
/** Global error handler */
|
140
216
|
onError?: (error: Error, context: GraphContext<T>) => void;
|
141
217
|
/** Entry node name */
|
@@ -178,17 +254,6 @@ export type MeilisearchSettings = {
|
|
178
254
|
/** Array of sortable attributes */
|
179
255
|
sortableAttributes?: string[];
|
180
256
|
};
|
181
|
-
export type GraphEvent<T extends ZodSchema> = {
|
182
|
-
type: string;
|
183
|
-
payload?: any;
|
184
|
-
timestamp: number;
|
185
|
-
};
|
186
|
-
export type WaitForEvents<T extends ZodSchema> = {
|
187
|
-
events: string[];
|
188
|
-
timeout?: number;
|
189
|
-
strategy: "all" | "any" | "race";
|
190
|
-
onSuccess?: <T extends ZodSchema>(context: GraphContext<T>) => Promise<void>;
|
191
|
-
};
|
192
257
|
/**
|
193
258
|
* Configuration interface for NLP Engine
|
194
259
|
* @interface NLPConfig
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../types/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,KAAK,CAAC;AAChC,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAI9C;;;;;;;GAOG;AACH,MAAM,WAAW,iBAAiB;IAChC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,IAAI,CAAC;CACjB;AAID;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,kDAA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AAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IACjC,cAAc,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;IACtE,gBAAgB,CAAC,EAAE,MAAM,IAAI,CAAC;CAC/B,CAAC"}
|
package/graph/controller.ts
CHANGED
@@ -1,7 +1,6 @@
|
|
1
1
|
import { ZodSchema } from "zod";
|
2
2
|
import { GraphExecutionResult } from "../types";
|
3
3
|
import { GraphFlow } from "./index";
|
4
|
-
import { NodeParams } from "./node";
|
5
4
|
|
6
5
|
/**
|
7
6
|
* Controller class for managing the execution of graph flows
|
@@ -12,19 +11,19 @@ export class GraphController {
|
|
12
11
|
* Executes multiple graphs sequentially
|
13
12
|
* @param graphs - Array of GraphFlow instances to execute
|
14
13
|
* @param startNodes - Array of starting node identifiers for each graph
|
15
|
-
* @param
|
14
|
+
* @param contexts - Optional array of contexts for each graph
|
16
15
|
* @returns Map containing results of each graph execution, keyed by graph name and index
|
17
16
|
* @template T - Zod schema type for graph context validation
|
18
17
|
*/
|
19
18
|
static async executeSequential<T extends ZodSchema>(
|
20
19
|
graphs: GraphFlow<T>[],
|
21
20
|
startNodes: string[],
|
22
|
-
|
21
|
+
contexts?: Partial<any>[]
|
23
22
|
): Promise<GraphExecutionResult<T>[]> {
|
24
23
|
const results: GraphExecutionResult<T>[] = [];
|
25
24
|
|
26
25
|
for (let i = 0; i < graphs.length; i++) {
|
27
|
-
const context = await graphs[i].execute(startNodes[i],
|
26
|
+
const context = await graphs[i].execute(startNodes[i], contexts?.[i]);
|
28
27
|
results.push({
|
29
28
|
graphName: graphs[i].name,
|
30
29
|
nodeName: startNodes[i],
|
@@ -38,14 +37,14 @@ export class GraphController {
|
|
38
37
|
private static async executeGraph<T extends ZodSchema>(
|
39
38
|
graph: GraphFlow<T>,
|
40
39
|
startNode: string,
|
41
|
-
|
40
|
+
context?: Partial<any>
|
42
41
|
): Promise<GraphExecutionResult<T>> {
|
43
42
|
try {
|
44
|
-
const
|
43
|
+
const result = await graph.execute(startNode, context);
|
45
44
|
return {
|
46
45
|
graphName: graph.name,
|
47
46
|
nodeName: startNode,
|
48
|
-
context,
|
47
|
+
context: result,
|
49
48
|
};
|
50
49
|
} catch (error) {
|
51
50
|
throw error;
|
@@ -57,7 +56,7 @@ export class GraphController {
|
|
57
56
|
* @param graphs - Array of GraphFlow instances to execute
|
58
57
|
* @param startNodes - Array of starting node identifiers for each graph
|
59
58
|
* @param concurrency - Optional limit on number of concurrent graph executions
|
60
|
-
* @param
|
59
|
+
* @param contexts - Optional array of contexts for each graph
|
61
60
|
* @returns Map containing results of each graph execution, keyed by graph name
|
62
61
|
* @template T - Zod schema type for graph context validation
|
63
62
|
*/
|
@@ -65,7 +64,7 @@ export class GraphController {
|
|
65
64
|
graphs: GraphFlow<T>[],
|
66
65
|
startNodes: string[],
|
67
66
|
concurrency: number,
|
68
|
-
|
67
|
+
contexts?: Partial<any>[]
|
69
68
|
): Promise<GraphExecutionResult<T>[]> {
|
70
69
|
const results: GraphExecutionResult<T>[] = [];
|
71
70
|
|
@@ -73,8 +72,8 @@ export class GraphController {
|
|
73
72
|
const batch = graphs.slice(i, i + concurrency);
|
74
73
|
const batchResults = await Promise.all(
|
75
74
|
batch.map((graph, idx) => {
|
76
|
-
const
|
77
|
-
return this.executeGraph(graph, startNodes[i + idx],
|
75
|
+
const context = contexts?.[i + idx];
|
76
|
+
return this.executeGraph(graph, startNodes[i + idx], context);
|
78
77
|
})
|
79
78
|
);
|
80
79
|
results.push(...batchResults);
|
package/graph/event-manager.ts
CHANGED
@@ -131,7 +131,6 @@ export class GraphEventManager<T extends ZodSchema> {
|
|
131
131
|
await this.executeNode(
|
132
132
|
node.name,
|
133
133
|
freshContext,
|
134
|
-
undefined,
|
135
134
|
/* triggeredByEvent= */ true
|
136
135
|
);
|
137
136
|
}
|
@@ -161,12 +160,7 @@ export class GraphEventManager<T extends ZodSchema> {
|
|
161
160
|
throw new Error("No entry node defined for graph event handling");
|
162
161
|
}
|
163
162
|
|
164
|
-
await this.executeNode(
|
165
|
-
this.entryNode,
|
166
|
-
freshContext,
|
167
|
-
undefined,
|
168
|
-
false
|
169
|
-
);
|
163
|
+
await this.executeNode(this.entryNode, freshContext, false);
|
170
164
|
|
171
165
|
// Emit "graphCompleted"
|
172
166
|
this.eventEmitter.emit("graphCompleted", {
|
@@ -278,7 +272,6 @@ export class GraphEventManager<T extends ZodSchema> {
|
|
278
272
|
private async executeNode(
|
279
273
|
nodeName: string,
|
280
274
|
context: GraphContext<T>,
|
281
|
-
inputs: any,
|
282
275
|
triggeredByEvent: boolean
|
283
276
|
): Promise<void> {
|
284
277
|
if (!this.nodeExecutor) {
|
@@ -295,12 +288,7 @@ export class GraphEventManager<T extends ZodSchema> {
|
|
295
288
|
await this.handleNodeEvents(nodeName, node.when);
|
296
289
|
}
|
297
290
|
|
298
|
-
return this.nodeExecutor.executeNode(
|
299
|
-
nodeName,
|
300
|
-
context,
|
301
|
-
inputs,
|
302
|
-
triggeredByEvent
|
303
|
-
);
|
291
|
+
return this.nodeExecutor.executeNode(nodeName, context, triggeredByEvent);
|
304
292
|
}
|
305
293
|
|
306
294
|
/**
|
package/graph/index.ts
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
import { EventEmitter } from "events";
|
2
2
|
import { BehaviorSubject, Subject } from "rxjs";
|
3
3
|
import { ZodSchema } from "zod";
|
4
|
-
import { GraphObservable, IEventEmitter
|
4
|
+
import { GraphObservable, IEventEmitter } from "../interfaces";
|
5
5
|
import { NLPNode } from "../modules/nlp";
|
6
6
|
import {
|
7
7
|
GraphConfig,
|
@@ -11,7 +11,7 @@ import {
|
|
11
11
|
} from "../types";
|
12
12
|
import { GraphEventManager } from "./event-manager";
|
13
13
|
import { GraphLogger } from "./logger";
|
14
|
-
import { GraphNode
|
14
|
+
import { GraphNode } from "./node";
|
15
15
|
import { GraphObserver } from "./observer";
|
16
16
|
import { GraphVisualizer } from "./visualizer";
|
17
17
|
|
@@ -37,6 +37,7 @@ export class GraphFlow<T extends ZodSchema> {
|
|
37
37
|
private entryNode?: string;
|
38
38
|
private verbose: boolean = false;
|
39
39
|
public nodes: Map<string, GraphNodeConfig<T, any>>;
|
40
|
+
public name: string;
|
40
41
|
|
41
42
|
private eventSubject: Subject<GraphEvent<T>> = new Subject();
|
42
43
|
private stateSubject: BehaviorSubject<GraphContext<T>>;
|
@@ -51,15 +52,11 @@ export class GraphFlow<T extends ZodSchema> {
|
|
51
52
|
|
52
53
|
/**
|
53
54
|
* Creates a new instance of GraphFlow
|
54
|
-
* @param {
|
55
|
-
* @param {GraphConfig<T>} config - Configuration object containing nodes, schema, context, and error handlers
|
55
|
+
* @param {GraphConfig<T>} config - Configuration object containing name, nodes, schema, context, and error handlers
|
56
56
|
* @param {Object} options - Optional options for the graph flow
|
57
57
|
*/
|
58
|
-
constructor(
|
59
|
-
|
60
|
-
config: GraphConfig<T>,
|
61
|
-
options: { verbose?: boolean } = {}
|
62
|
-
) {
|
58
|
+
constructor(config: GraphConfig<T>, options: { verbose?: boolean } = {}) {
|
59
|
+
this.name = config.name;
|
63
60
|
this.nodes = new Map(
|
64
61
|
config.nodes.map((node: GraphNodeConfig<T, any>) => [node.name, node])
|
65
62
|
);
|
@@ -69,22 +66,23 @@ export class GraphFlow<T extends ZodSchema> {
|
|
69
66
|
this.eventEmitter =
|
70
67
|
config.eventEmitter || (new EventEmitter() as IEventEmitter);
|
71
68
|
this.graphEvents = config.events;
|
69
|
+
this.entryNode = config.entryNode;
|
72
70
|
this.verbose = options.verbose ?? false;
|
73
71
|
|
74
72
|
this.stateSubject = new BehaviorSubject<GraphContext<T>>(this.context);
|
75
73
|
|
76
|
-
this.logger = new GraphLogger(name, options.verbose);
|
74
|
+
this.logger = new GraphLogger(this.name, options.verbose);
|
77
75
|
this.eventManager = new GraphEventManager(
|
78
76
|
this.eventEmitter,
|
79
77
|
this.nodes,
|
80
|
-
name,
|
78
|
+
this.name,
|
81
79
|
this.context,
|
82
80
|
config.events,
|
83
81
|
config.entryNode,
|
84
82
|
config.onError
|
85
83
|
);
|
86
84
|
this.nodeExecutor = new GraphNode(
|
87
|
-
this.nodes
|
85
|
+
this.nodes,
|
88
86
|
this.logger,
|
89
87
|
this.eventManager,
|
90
88
|
this.eventSubject,
|
@@ -159,25 +157,18 @@ export class GraphFlow<T extends ZodSchema> {
|
|
159
157
|
* @private
|
160
158
|
* @param {string} nodeName - Name of the node to execute
|
161
159
|
* @param {GraphContext<T>} context - Current execution context
|
162
|
-
* @param {any} inputs - Input parameters for the node
|
163
160
|
* @param {boolean} triggeredByEvent - Whether the execution was triggered by an event
|
164
161
|
* @returns {Promise<void>}
|
165
162
|
*/
|
166
163
|
private async executeNode(
|
167
164
|
nodeName: string,
|
168
165
|
context: GraphContext<T>,
|
169
|
-
inputs: any,
|
170
166
|
triggeredByEvent: boolean = false
|
171
167
|
): Promise<void> {
|
172
168
|
const node = this.nodes.get(nodeName);
|
173
169
|
if (!node) throw new Error(`Node "${nodeName}" not found`);
|
174
170
|
|
175
|
-
return this.nodeExecutor.executeNode(
|
176
|
-
nodeName,
|
177
|
-
context,
|
178
|
-
inputs,
|
179
|
-
triggeredByEvent
|
180
|
-
);
|
171
|
+
return this.nodeExecutor.executeNode(nodeName, context, triggeredByEvent);
|
181
172
|
}
|
182
173
|
|
183
174
|
private addLog(message: string): void {
|
@@ -227,36 +218,33 @@ export class GraphFlow<T extends ZodSchema> {
|
|
227
218
|
/**
|
228
219
|
* Executes the graph flow starting from a specific node
|
229
220
|
* @param {string} startNode - Name of the node to start execution from
|
230
|
-
* @param {any} inputs - Optional input parameters for the start node
|
231
221
|
* @param {Partial<GraphContext<T>>} context - Optional context to merge
|
232
|
-
* @param {NodeParams} params - Optional node parameters
|
233
222
|
* @returns {Promise<GraphContext<T>>} Final context after execution
|
234
223
|
*/
|
235
224
|
public async execute(
|
236
225
|
startNode: string,
|
237
|
-
params?: NodeParams,
|
238
226
|
context?: Partial<GraphContext<T>>
|
239
227
|
): Promise<GraphContext<T>> {
|
240
|
-
|
241
|
-
|
242
|
-
|
228
|
+
try {
|
229
|
+
// Validate and merge context if provided
|
230
|
+
if (context) {
|
231
|
+
const mergedContext = { ...this.context, ...context };
|
232
|
+
const validationResult = this.validator?.safeParse(mergedContext);
|
233
|
+
if (!validationResult?.success) {
|
234
|
+
const errors = validationResult?.error?.errors.map(
|
235
|
+
(err) => `${err.path.join(".")}: ${err.message}`
|
236
|
+
);
|
237
|
+
throw new Error(`Context validation failed: ${errors?.join(", ")}`);
|
238
|
+
}
|
239
|
+
this.context = validationResult.data;
|
240
|
+
}
|
243
241
|
|
244
|
-
|
242
|
+
this.eventEmitter.emit("graphStarted", { name: this.name });
|
245
243
|
|
246
|
-
try {
|
247
244
|
const node = this.nodes.get(startNode);
|
248
245
|
if (!node) throw new Error(`Node "${startNode}" not found`);
|
249
246
|
|
250
|
-
|
251
|
-
throw new Error(`Params required for node "${startNode}"`);
|
252
|
-
}
|
253
|
-
|
254
|
-
await this.nodeExecutor.executeNode(
|
255
|
-
startNode,
|
256
|
-
this.context,
|
257
|
-
params,
|
258
|
-
false
|
259
|
-
);
|
247
|
+
await this.nodeExecutor.executeNode(startNode, this.context, false);
|
260
248
|
|
261
249
|
this.eventEmitter.emit("graphCompleted", {
|
262
250
|
name: this.name,
|
@@ -307,8 +295,8 @@ export class GraphFlow<T extends ZodSchema> {
|
|
307
295
|
public load(definition: GraphConfig<T>): void {
|
308
296
|
// Clear all existing nodes
|
309
297
|
this.nodes.clear();
|
298
|
+
|
310
299
|
// Wipe out old node-based event listeners
|
311
|
-
// (We keep external test listeners like "nodeStarted" or "nodeCompleted".)
|
312
300
|
if (definition.nodes?.length) {
|
313
301
|
const allEvents = new Set<string>();
|
314
302
|
definition.nodes.forEach((n) =>
|
@@ -323,14 +311,18 @@ export class GraphFlow<T extends ZodSchema> {
|
|
323
311
|
definition.nodes.forEach((node) => this.nodes.set(node.name, node));
|
324
312
|
|
325
313
|
// Parse the new context
|
326
|
-
|
327
|
-
|
328
|
-
|
314
|
+
const validationResult = definition.schema.safeParse(definition.context);
|
315
|
+
if (!validationResult.success) {
|
316
|
+
const errors = validationResult.error.errors.map(
|
317
|
+
(err) => `${err.path.join(".")}: ${err.message}`
|
318
|
+
);
|
319
|
+
throw new Error(`Context validation failed: ${errors.join(", ")}`);
|
320
|
+
}
|
321
|
+
this.context = validationResult.data;
|
329
322
|
this.validator = definition.schema;
|
330
323
|
|
331
|
-
// Store entry node
|
324
|
+
// Store entry node and graph events
|
332
325
|
this.entryNode = definition.entryNode;
|
333
|
-
// Store graph events
|
334
326
|
this.graphEvents = definition.events;
|
335
327
|
|
336
328
|
// Re-setup only node-based event triggers
|
@@ -342,7 +334,7 @@ export class GraphFlow<T extends ZodSchema> {
|
|
342
334
|
async (data?: Partial<GraphContext<T>>) => {
|
343
335
|
const freshContext = structuredClone(this.context);
|
344
336
|
if (data) Object.assign(freshContext, data);
|
345
|
-
await this.executeNode(node.name, freshContext,
|
337
|
+
await this.executeNode(node.name, freshContext, true);
|
346
338
|
}
|
347
339
|
);
|
348
340
|
});
|
@@ -423,28 +415,6 @@ export class GraphFlow<T extends ZodSchema> {
|
|
423
415
|
return this.validator as T;
|
424
416
|
}
|
425
417
|
|
426
|
-
/**
|
427
|
-
* Adds a new NLP node to the graph
|
428
|
-
* @param {NLPNodeConfig<T>} config - Configuration for the NLP node
|
429
|
-
* @returns {Promise<void>}
|
430
|
-
*/
|
431
|
-
public async addNLPNode(config: NLPNodeConfig<T>) {
|
432
|
-
const node = new NLPNode(config);
|
433
|
-
await node.initialize();
|
434
|
-
this.nlpNodes.set(config.name, node);
|
435
|
-
|
436
|
-
this.addNode({
|
437
|
-
name: config.name,
|
438
|
-
execute: async (context, input) => {
|
439
|
-
if (!input?.input) return;
|
440
|
-
const result = await node.process(input.input);
|
441
|
-
console.log("GraphFlow NLP result:", result);
|
442
|
-
Object.assign(context, { nlpResult: result });
|
443
|
-
},
|
444
|
-
next: config.next,
|
445
|
-
});
|
446
|
-
}
|
447
|
-
|
448
418
|
/**
|
449
419
|
* Processes natural language input using a specific NLP node
|
450
420
|
* @param {string} text - The input text to process
|