@ai.ntellect/core 0.6.11 → 0.6.13
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/app/README.md +36 -0
- package/app/app/favicon.ico +0 -0
- package/app/app/globals.css +21 -0
- package/app/app/gun.ts +0 -0
- package/app/app/layout.tsx +18 -0
- package/app/app/page.tsx +321 -0
- package/app/eslint.config.mjs +16 -0
- package/app/next.config.ts +7 -0
- package/app/package-lock.json +5912 -0
- package/app/package.json +31 -0
- package/app/pnpm-lock.yaml +4031 -0
- package/app/postcss.config.mjs +8 -0
- package/app/public/file.svg +1 -0
- package/app/public/globe.svg +1 -0
- package/app/public/next.svg +1 -0
- package/app/public/vercel.svg +1 -0
- package/app/public/window.svg +1 -0
- package/app/tailwind.config.ts +18 -0
- package/app/tsconfig.json +27 -0
- package/dist/graph/controller.js +30 -41
- package/dist/graph/graph.js +167 -0
- package/dist/index.js +3 -2
- package/dist/memory/adapters/meilisearch/index.js +39 -63
- package/dist/utils/experimental-graph-rag.js +152 -0
- package/dist/utils/stringifiy-zod-schema.js +7 -6
- package/graph/controller.ts +57 -52
- package/graph/graph.ts +198 -0
- package/index.ts +3 -2
- package/memory/adapters/meilisearch/index.ts +41 -76
- package/package.json +2 -2
- package/tsconfig.json +1 -1
- package/types/index.ts +35 -38
- package/utils/experimental-graph-rag.ts +170 -0
- package/utils/stringifiy-zod-schema.ts +6 -6
- package/create-llm-to-select-multiple-graph copy.ts +0 -237
- package/create-llm-to-select-multiple-graph.ts +0 -148
- package/dist/create-llm-to-select-multiple-graph copy.js +0 -171
- package/dist/create-llm-to-select-multiple-graph.js +0 -142
- package/dist/graph/engine.js +0 -646
- package/dist/index copy.js +0 -76
- package/dist/utils/setup-graphs.js +0 -28
- package/graph/engine.ts +0 -805
- package/index copy.ts +0 -81
- package/utils/setup-graphs.ts +0 -45
package/dist/graph/engine.js
DELETED
@@ -1,646 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
9
|
-
});
|
10
|
-
};
|
11
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
12
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
13
|
-
};
|
14
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
15
|
-
exports.GraphEngine = void 0;
|
16
|
-
const events_1 = __importDefault(require("events"));
|
17
|
-
const zod_1 = require("zod");
|
18
|
-
/**
|
19
|
-
* Représente un workflow dirigé capable d’exécuter des noeuds en séquence ou en parallèle.
|
20
|
-
*
|
21
|
-
* @template T - Le type de données stockées dans le contexte du workflow
|
22
|
-
*/
|
23
|
-
class GraphEngine {
|
24
|
-
/**
|
25
|
-
* Crée une nouvelle instance de GraphEngine.
|
26
|
-
*
|
27
|
-
* @param {GraphDefinition<T>} [definition] - La définition initiale du workflow
|
28
|
-
* @param {GraphOptions<T>} [options] - Options de configuration
|
29
|
-
*/
|
30
|
-
constructor(definition, options) {
|
31
|
-
this.name = (definition === null || definition === void 0 ? void 0 : definition.name) || "anonymous";
|
32
|
-
this.eventEmitter = new events_1.default();
|
33
|
-
this.globalContext = new Map();
|
34
|
-
this.nodes = new Map();
|
35
|
-
this.executedNodes = new Set();
|
36
|
-
this.persistence = null;
|
37
|
-
this.notifier = null;
|
38
|
-
this.schema = options === null || options === void 0 ? void 0 : options.schema;
|
39
|
-
this.currentState = {};
|
40
|
-
if (definition) {
|
41
|
-
this.loadFromDefinition(definition);
|
42
|
-
}
|
43
|
-
if ((options === null || options === void 0 ? void 0 : options.autoDetectCycles) && this.checkForCycles()) {
|
44
|
-
throw new Error("Cycle détecté dans le workflow");
|
45
|
-
}
|
46
|
-
if (options === null || options === void 0 ? void 0 : options.initialState) {
|
47
|
-
this.setState(options.initialState);
|
48
|
-
}
|
49
|
-
}
|
50
|
-
/**
|
51
|
-
* Ajoute un élément au contexte global.
|
52
|
-
* @param {string} key - La clé
|
53
|
-
* @param {any} value - La valeur
|
54
|
-
*/
|
55
|
-
addToContext(key, value) {
|
56
|
-
this.globalContext.set(key, value);
|
57
|
-
}
|
58
|
-
/**
|
59
|
-
* Récupère un élément du contexte global.
|
60
|
-
* @param {string} key - La clé
|
61
|
-
*/
|
62
|
-
getContext(key) {
|
63
|
-
return this.globalContext.get(key);
|
64
|
-
}
|
65
|
-
/**
|
66
|
-
* Supprime un élément du contexte global.
|
67
|
-
* @param {string} key - La clé
|
68
|
-
*/
|
69
|
-
removeFromContext(key) {
|
70
|
-
this.globalContext.delete(key);
|
71
|
-
}
|
72
|
-
/**
|
73
|
-
* Définit la couche de persistance.
|
74
|
-
* @param {Persistence<T>} persistence
|
75
|
-
*/
|
76
|
-
setPersistence(persistence) {
|
77
|
-
this.persistence = persistence;
|
78
|
-
}
|
79
|
-
/**
|
80
|
-
* Définit le notifier en temps réel.
|
81
|
-
* @param {RealTimeNotifier} notifier
|
82
|
-
*/
|
83
|
-
setNotifier(notifier) {
|
84
|
-
this.notifier = notifier;
|
85
|
-
}
|
86
|
-
/**
|
87
|
-
* Charge un workflow à partir d'une définition.
|
88
|
-
* @private
|
89
|
-
* @param {GraphDefinition<T>} definition
|
90
|
-
*/
|
91
|
-
loadFromDefinition(definition) {
|
92
|
-
Object.entries(definition.nodes).forEach(([_, nodeConfig]) => {
|
93
|
-
this.addNode(nodeConfig);
|
94
|
-
});
|
95
|
-
}
|
96
|
-
/**
|
97
|
-
* Vérifie récursivement s’il existe un cycle dans le workflow.
|
98
|
-
* @param {string} nodeName
|
99
|
-
* @param {Set<string>} visited
|
100
|
-
* @param {Set<string>} recStack
|
101
|
-
* @returns {boolean}
|
102
|
-
*/
|
103
|
-
isCyclic(nodeName, visited, recStack) {
|
104
|
-
if (!visited.has(nodeName)) {
|
105
|
-
visited.add(nodeName);
|
106
|
-
recStack.add(nodeName);
|
107
|
-
const currentNode = this.nodes.get(nodeName);
|
108
|
-
if (currentNode === null || currentNode === void 0 ? void 0 : currentNode.relationships) {
|
109
|
-
for (const relation of currentNode.relationships) {
|
110
|
-
const targetNode = relation.name;
|
111
|
-
if (!visited.has(targetNode) &&
|
112
|
-
this.isCyclic(targetNode, visited, recStack)) {
|
113
|
-
return true;
|
114
|
-
}
|
115
|
-
else if (recStack.has(targetNode)) {
|
116
|
-
return true;
|
117
|
-
}
|
118
|
-
}
|
119
|
-
}
|
120
|
-
}
|
121
|
-
recStack.delete(nodeName);
|
122
|
-
return false;
|
123
|
-
}
|
124
|
-
/**
|
125
|
-
* Vérifie si le workflow contient des cycles.
|
126
|
-
* @returns {boolean}
|
127
|
-
*/
|
128
|
-
checkForCycles() {
|
129
|
-
const visited = new Set();
|
130
|
-
const recStack = new Set();
|
131
|
-
for (const nodeName of this.nodes.keys()) {
|
132
|
-
if (this.isCyclic(nodeName, visited, recStack)) {
|
133
|
-
return true;
|
134
|
-
}
|
135
|
-
}
|
136
|
-
return false;
|
137
|
-
}
|
138
|
-
/**
|
139
|
-
* Ajoute un nouveau nœud au workflow.
|
140
|
-
* @param {Node<T>} node
|
141
|
-
*/
|
142
|
-
addNode(node) {
|
143
|
-
if (node.relationships) {
|
144
|
-
node.relationships.forEach((relationship) => {
|
145
|
-
var _a, _b;
|
146
|
-
(_b = (_a = this.nodes.get(relationship.name)) === null || _a === void 0 ? void 0 : _a.relationships) === null || _b === void 0 ? void 0 : _b.push(relationship);
|
147
|
-
});
|
148
|
-
}
|
149
|
-
if (node.events) {
|
150
|
-
node.events.forEach((event) => {
|
151
|
-
this.eventEmitter.on(event, (data) => __awaiter(this, void 0, void 0, function* () {
|
152
|
-
const state = data.state || {};
|
153
|
-
yield this.execute(state, node.name);
|
154
|
-
}));
|
155
|
-
});
|
156
|
-
}
|
157
|
-
this.nodes.set(node.name, node);
|
158
|
-
}
|
159
|
-
/**
|
160
|
-
* Émet un événement sur l'event emitter du workflow.
|
161
|
-
* @param {string} eventName
|
162
|
-
* @param {any} data
|
163
|
-
*/
|
164
|
-
emit(eventName, data) {
|
165
|
-
this.eventEmitter.emit(eventName, data);
|
166
|
-
}
|
167
|
-
/**
|
168
|
-
* Ajoute un sous-graph (GraphEngine) comme un nœud dans le workflow courant.
|
169
|
-
* @param {GraphEngine<T>} subGraph
|
170
|
-
* @param {string} entryNode - Le nom du nœud de démarrage dans le sous-graph
|
171
|
-
* @param {string} name - Le nom symbolique à donner au sous-graph
|
172
|
-
*/
|
173
|
-
addSubGraph(subGraph, entryNode, name) {
|
174
|
-
const subGraphNode = {
|
175
|
-
name: name,
|
176
|
-
execute: (state) => __awaiter(this, void 0, void 0, function* () {
|
177
|
-
yield subGraph.execute(state, entryNode);
|
178
|
-
return state;
|
179
|
-
}),
|
180
|
-
};
|
181
|
-
this.nodes.set(name, subGraphNode);
|
182
|
-
}
|
183
|
-
/**
|
184
|
-
* Exécute le workflow à partir d’un nœud donné.
|
185
|
-
* @param {SharedState<T>} state
|
186
|
-
* @param {string} startNode
|
187
|
-
* @param {(state: SharedState<T>) => void} [onStream] - Callback sur l’évolution de l’état
|
188
|
-
* @param {(error: Error, nodeName: string, state: SharedState<T>) => void} [onError] - Callback sur erreur
|
189
|
-
*/
|
190
|
-
execute(state, startNode, onStream, onError) {
|
191
|
-
return __awaiter(this, void 0, void 0, function* () {
|
192
|
-
var _a;
|
193
|
-
try {
|
194
|
-
// Valide l'état initial via le schéma global (si défini)
|
195
|
-
if (this.schema) {
|
196
|
-
try {
|
197
|
-
this.schema.parse(state);
|
198
|
-
}
|
199
|
-
catch (error) {
|
200
|
-
const validationError = new Error(`Échec de la validation de l'état initial: ${error instanceof Error ? error.message : error}`);
|
201
|
-
if (onError)
|
202
|
-
onError(validationError, startNode, state);
|
203
|
-
throw validationError;
|
204
|
-
}
|
205
|
-
}
|
206
|
-
this.setState(state);
|
207
|
-
let currentNodeName = startNode;
|
208
|
-
while (currentNodeName) {
|
209
|
-
this.executedNodes.add(currentNodeName);
|
210
|
-
const currentNode = this.nodes.get(currentNodeName);
|
211
|
-
if (!currentNode) {
|
212
|
-
throw new Error(`Node ${currentNodeName} introuvable.`);
|
213
|
-
}
|
214
|
-
// Vérification de condition (si présente)
|
215
|
-
if (currentNode.condition &&
|
216
|
-
!currentNode.condition(this.currentState)) {
|
217
|
-
break;
|
218
|
-
}
|
219
|
-
try {
|
220
|
-
// Notifier : début d'exécution du nœud
|
221
|
-
if (this.notifier) {
|
222
|
-
this.notifier.notify("nodeExecutionStarted", {
|
223
|
-
workflow: this.name,
|
224
|
-
node: currentNodeName,
|
225
|
-
});
|
226
|
-
}
|
227
|
-
const newState = yield currentNode.execute(this.currentState);
|
228
|
-
if (newState) {
|
229
|
-
this.setState(newState);
|
230
|
-
if (onStream)
|
231
|
-
onStream(this);
|
232
|
-
}
|
233
|
-
// Sauvegarde via la persistence (optionnel)
|
234
|
-
if (this.persistence) {
|
235
|
-
yield this.persistence.saveState(this.name, this.currentState, currentNodeName);
|
236
|
-
}
|
237
|
-
// Notifier : fin d'exécution du nœud
|
238
|
-
if (this.notifier) {
|
239
|
-
yield this.notifier.notify("nodeExecutionCompleted", {
|
240
|
-
workflow: this.name,
|
241
|
-
node: currentNodeName,
|
242
|
-
state: this.currentState,
|
243
|
-
});
|
244
|
-
}
|
245
|
-
}
|
246
|
-
catch (error) {
|
247
|
-
if (onError) {
|
248
|
-
onError(error, currentNodeName, this.currentState);
|
249
|
-
}
|
250
|
-
if (this.notifier) {
|
251
|
-
this.notifier.notify("nodeExecutionFailed", {
|
252
|
-
workflow: this.name,
|
253
|
-
node: currentNodeName,
|
254
|
-
state: this.currentState,
|
255
|
-
error,
|
256
|
-
});
|
257
|
-
}
|
258
|
-
break;
|
259
|
-
}
|
260
|
-
const relationsNodes = currentNode.relationships || [];
|
261
|
-
// Check condition for all relations
|
262
|
-
let nextNodes = [];
|
263
|
-
for (const relation of relationsNodes) {
|
264
|
-
const nextNode = this.nodes.get(relation.name);
|
265
|
-
if ((nextNode === null || nextNode === void 0 ? void 0 : nextNode.condition) && !nextNode.condition(this.currentState)) {
|
266
|
-
// Skip this relation
|
267
|
-
continue;
|
268
|
-
}
|
269
|
-
nextNodes.push({
|
270
|
-
name: relation.name,
|
271
|
-
condition: nextNode === null || nextNode === void 0 ? void 0 : nextNode.condition,
|
272
|
-
});
|
273
|
-
}
|
274
|
-
if (nextNodes.length > 1) {
|
275
|
-
// Exécution parallèle des branches
|
276
|
-
yield Promise.all(nextNodes.map((relation) => this.execute(this.currentState, relation.name, onStream, onError)));
|
277
|
-
// Après exécution en parallèle, on arrête la boucle
|
278
|
-
break;
|
279
|
-
}
|
280
|
-
else {
|
281
|
-
// Cas normal : un seul chemin
|
282
|
-
currentNodeName = ((_a = relationsNodes[0]) === null || _a === void 0 ? void 0 : _a.name) || "";
|
283
|
-
}
|
284
|
-
}
|
285
|
-
return this.getState();
|
286
|
-
}
|
287
|
-
catch (error) {
|
288
|
-
if (onError) {
|
289
|
-
onError(error, startNode, state);
|
290
|
-
}
|
291
|
-
throw error;
|
292
|
-
}
|
293
|
-
});
|
294
|
-
}
|
295
|
-
/**
|
296
|
-
* Exécute plusieurs nœuds en parallèle au sein du même workflow, avec une limite de concurrence.
|
297
|
-
* @param {SharedState<T>} state
|
298
|
-
* @param {string[]} nodeNames
|
299
|
-
* @param {number} [concurrencyLimit=5]
|
300
|
-
*/
|
301
|
-
executeParallel(state_1, nodeNames_1) {
|
302
|
-
return __awaiter(this, arguments, void 0, function* (state, nodeNames, concurrencyLimit = 5, onStream, onError) {
|
303
|
-
const executeWithLimit = (nodeName) => __awaiter(this, void 0, void 0, function* () {
|
304
|
-
yield this.execute(state, nodeName, onStream, onError);
|
305
|
-
});
|
306
|
-
const chunks = [];
|
307
|
-
for (let i = 0; i < nodeNames.length; i += concurrencyLimit) {
|
308
|
-
chunks.push(nodeNames.slice(i, i + concurrencyLimit));
|
309
|
-
}
|
310
|
-
for (const chunk of chunks) {
|
311
|
-
yield Promise.all(chunk.map(executeWithLimit));
|
312
|
-
}
|
313
|
-
});
|
314
|
-
}
|
315
|
-
/**
|
316
|
-
* Met à jour le workflow avec une nouvelle définition (mise à jour des nœuds existants ou ajout de nouveaux).
|
317
|
-
* @param {GraphDefinition<T>} definition
|
318
|
-
*/
|
319
|
-
updateGraph(definition) {
|
320
|
-
Object.entries(definition.nodes).forEach(([_, nodeConfig]) => {
|
321
|
-
if (this.nodes.has(nodeConfig.name)) {
|
322
|
-
const existingNode = this.nodes.get(nodeConfig.name);
|
323
|
-
existingNode.relationships =
|
324
|
-
nodeConfig.relationships || existingNode.relationships;
|
325
|
-
existingNode.condition = nodeConfig.condition || existingNode.condition;
|
326
|
-
existingNode.events = nodeConfig.events || existingNode.events;
|
327
|
-
}
|
328
|
-
else {
|
329
|
-
this.addNode(nodeConfig);
|
330
|
-
}
|
331
|
-
});
|
332
|
-
}
|
333
|
-
/**
|
334
|
-
* Remplace complètement le workflow par une nouvelle définition.
|
335
|
-
* @param {GraphDefinition<T>} definition
|
336
|
-
*/
|
337
|
-
replaceGraph(definition) {
|
338
|
-
this.nodes.clear();
|
339
|
-
this.loadFromDefinition(definition);
|
340
|
-
}
|
341
|
-
/**
|
342
|
-
* Génère un diagramme Mermaid pour visualiser le workflow.
|
343
|
-
* @param {string} [title]
|
344
|
-
* @returns {string}
|
345
|
-
*/
|
346
|
-
generateMermaidDiagram(title) {
|
347
|
-
const lines = ["flowchart TD"];
|
348
|
-
if (title) {
|
349
|
-
lines.push(` subgraph ${title}`);
|
350
|
-
}
|
351
|
-
// Ajout des nœuds
|
352
|
-
this.nodes.forEach((node, nodeName) => {
|
353
|
-
const hasEvents = node.events && node.events.length > 0;
|
354
|
-
const hasCondition = !!node.condition;
|
355
|
-
// Style selon les propriétés
|
356
|
-
let style = "";
|
357
|
-
if (hasEvents) {
|
358
|
-
style = "style " + nodeName + " fill:#FFD700,stroke:#DAA520"; // Jaune pour event
|
359
|
-
}
|
360
|
-
else if (hasCondition) {
|
361
|
-
style = "style " + nodeName + " fill:#FFA500,stroke:#FF8C00"; // Orange pour condition
|
362
|
-
}
|
363
|
-
lines.push(` ${nodeName}[${nodeName}]`);
|
364
|
-
if (style) {
|
365
|
-
lines.push(` ${style}`);
|
366
|
-
}
|
367
|
-
});
|
368
|
-
// Ajout des connexions
|
369
|
-
this.nodes.forEach((node, nodeName) => {
|
370
|
-
if (node.relationships) {
|
371
|
-
node.relationships.forEach((relationsNode) => {
|
372
|
-
let connectionStyle = "";
|
373
|
-
if (node.condition) {
|
374
|
-
connectionStyle = "---|condition|";
|
375
|
-
}
|
376
|
-
else {
|
377
|
-
connectionStyle = "-->";
|
378
|
-
}
|
379
|
-
lines.push(` ${nodeName} ${connectionStyle} ${relationsNode}`);
|
380
|
-
});
|
381
|
-
}
|
382
|
-
// Gestion des events
|
383
|
-
if (node.events && node.events.length > 0) {
|
384
|
-
node.events.forEach((event) => {
|
385
|
-
const eventNodeId = `${event}_event`;
|
386
|
-
lines.push(` ${eventNodeId}((${event})):::event`);
|
387
|
-
lines.push(` ${eventNodeId} -.->|trigger| ${nodeName}`);
|
388
|
-
});
|
389
|
-
lines.push(" classDef event fill:#FFD700,stroke:#DAA520");
|
390
|
-
}
|
391
|
-
});
|
392
|
-
if (title) {
|
393
|
-
lines.push(" end");
|
394
|
-
}
|
395
|
-
return lines.join("\n");
|
396
|
-
}
|
397
|
-
/**
|
398
|
-
* Affiche le diagramme Mermaid dans la console.
|
399
|
-
* @param {string} [title]
|
400
|
-
*/
|
401
|
-
visualize(title) {
|
402
|
-
const diagram = this.generateMermaidDiagram(title);
|
403
|
-
console.log("Pour visualiser ce workflow, utilisez un rendu compatible Mermaid avec la syntaxe suivante :");
|
404
|
-
console.log("\n```mermaid");
|
405
|
-
console.log(diagram);
|
406
|
-
console.log("```\n");
|
407
|
-
}
|
408
|
-
/**
|
409
|
-
* Exporte la définition du workflow au format JSON (pour debug ou documentation).
|
410
|
-
* @param {GraphDefinition<T>} workflow
|
411
|
-
* @returns {string} JSON string
|
412
|
-
*/
|
413
|
-
exportGraphToJson(workflow) {
|
414
|
-
const result = {
|
415
|
-
workflowName: workflow.name,
|
416
|
-
entryNode: workflow.entryNode,
|
417
|
-
nodes: Object.entries(workflow.nodes).reduce((acc, [key, node]) => {
|
418
|
-
acc[key] = {
|
419
|
-
name: node.name,
|
420
|
-
description: node.description || "No description provided",
|
421
|
-
execute: node.execute.name,
|
422
|
-
condition: node.condition ? node.condition.toString() : "None",
|
423
|
-
relationships: node.relationships || [],
|
424
|
-
};
|
425
|
-
return acc;
|
426
|
-
}, {}),
|
427
|
-
};
|
428
|
-
return JSON.stringify(result, null, 2);
|
429
|
-
}
|
430
|
-
/**
|
431
|
-
* Génère une représentation textuelle (console) du schéma du workflow.
|
432
|
-
* @returns {string}
|
433
|
-
*/
|
434
|
-
visualizeSchema() {
|
435
|
-
const output = [];
|
436
|
-
output.push(`📋 Graph: ${this.name}`);
|
437
|
-
output.push("=".repeat(50));
|
438
|
-
// Schéma global
|
439
|
-
if (this.schema) {
|
440
|
-
output.push("🔷 Global Schema:");
|
441
|
-
output.push("-".repeat(30));
|
442
|
-
if (this.schema instanceof zod_1.z.ZodObject) {
|
443
|
-
const shape = this.schema.shape;
|
444
|
-
Object.entries(shape).forEach(([key, value]) => {
|
445
|
-
const description = this.describeZodType(value, 1);
|
446
|
-
output.push(`${key}:`);
|
447
|
-
output.push(description);
|
448
|
-
});
|
449
|
-
}
|
450
|
-
output.push("");
|
451
|
-
}
|
452
|
-
// Détails des nœuds
|
453
|
-
output.push("🔷 Nodes:");
|
454
|
-
output.push("-".repeat(30));
|
455
|
-
this.nodes.forEach((node, nodeName) => {
|
456
|
-
output.push(`\n📍 Node: ${nodeName}`);
|
457
|
-
output.push(`Description: ${node.description || "No description provided"}`);
|
458
|
-
if (node.relationships && node.relationships.length > 0) {
|
459
|
-
const rels = node.relationships.map((r) => r.name).join(", ");
|
460
|
-
output.push(`Next nodes: ${rels}`);
|
461
|
-
}
|
462
|
-
output.push("");
|
463
|
-
});
|
464
|
-
return output.join("\n");
|
465
|
-
}
|
466
|
-
/**
|
467
|
-
* Décrit récursivement un type Zod pour l'affichage.
|
468
|
-
* @param {z.ZodType} type
|
469
|
-
* @param {number} indent
|
470
|
-
* @returns {string}
|
471
|
-
*/
|
472
|
-
describeZodType(type, indent = 0) {
|
473
|
-
const padding = " ".repeat(indent);
|
474
|
-
if (type instanceof zod_1.z.ZodObject) {
|
475
|
-
const shape = type.shape;
|
476
|
-
const lines = [];
|
477
|
-
Object.entries(shape).forEach(([key, value]) => {
|
478
|
-
const isOptional = value instanceof zod_1.z.ZodOptional;
|
479
|
-
const actualType = isOptional
|
480
|
-
? value.unwrap()
|
481
|
-
: value;
|
482
|
-
const description = this.describeZodType(actualType, indent + 1);
|
483
|
-
lines.push(`${padding}${key}${isOptional ? "?" : ""}: ${description}`);
|
484
|
-
});
|
485
|
-
return lines.join("\n");
|
486
|
-
}
|
487
|
-
if (type instanceof zod_1.z.ZodArray) {
|
488
|
-
const elementType = this.describeZodType(type.element, indent);
|
489
|
-
return `Array<${elementType}>`;
|
490
|
-
}
|
491
|
-
if (type instanceof zod_1.z.ZodString) {
|
492
|
-
const checks = type._def.checks || [];
|
493
|
-
const constraints = checks
|
494
|
-
.map((check) => {
|
495
|
-
if (check.kind === "url")
|
496
|
-
return "url";
|
497
|
-
if (check.kind === "email")
|
498
|
-
return "email";
|
499
|
-
return check.kind;
|
500
|
-
})
|
501
|
-
.join(", ");
|
502
|
-
return constraints ? `string (${constraints})` : "string";
|
503
|
-
}
|
504
|
-
if (type instanceof zod_1.z.ZodNumber) {
|
505
|
-
return "number";
|
506
|
-
}
|
507
|
-
if (type instanceof zod_1.z.ZodBoolean) {
|
508
|
-
return "boolean";
|
509
|
-
}
|
510
|
-
if (type instanceof zod_1.z.ZodOptional) {
|
511
|
-
return `${this.describeZodType(type.unwrap(), indent)} (optional)`;
|
512
|
-
}
|
513
|
-
return type.constructor.name.replace("Zod", "") || "unknown";
|
514
|
-
}
|
515
|
-
/**
|
516
|
-
* Met à jour le contexte du workflow pour un nœud, en renvoyant un nouvel état.
|
517
|
-
* @param {SharedState<T>} state
|
518
|
-
* @param {Partial<T>} updates
|
519
|
-
* @returns {SharedState<T>}
|
520
|
-
*/
|
521
|
-
updateNodeState(state, updates) {
|
522
|
-
return Object.assign(Object.assign({}, state), updates);
|
523
|
-
}
|
524
|
-
/**
|
525
|
-
* Récupère l'état courant du workflow.
|
526
|
-
* @returns {SharedState<T>}
|
527
|
-
*/
|
528
|
-
getState() {
|
529
|
-
return this.currentState;
|
530
|
-
}
|
531
|
-
/**
|
532
|
-
* Définit le nouvel état courant du workflow et met à jour le contexte global.
|
533
|
-
* @param {Partial<SharedState<T>>} state
|
534
|
-
*/
|
535
|
-
setState(state) {
|
536
|
-
this.currentState = this.mergeStates(this.currentState, state);
|
537
|
-
if (state) {
|
538
|
-
Object.entries(state).forEach(([key, value]) => {
|
539
|
-
this.globalContext.set(key, value);
|
540
|
-
});
|
541
|
-
}
|
542
|
-
const currentNode = Array.from(this.executedNodes).pop();
|
543
|
-
if (currentNode) {
|
544
|
-
const node = this.nodes.get(currentNode);
|
545
|
-
if (node) {
|
546
|
-
node.state = Object.assign(Object.assign({}, (node.state || {})), (state || {}));
|
547
|
-
}
|
548
|
-
}
|
549
|
-
}
|
550
|
-
/**
|
551
|
-
* Fusionne deux états.
|
552
|
-
* @param {SharedState<T>} currentState
|
553
|
-
* @param {Partial<SharedState<T>>} newState
|
554
|
-
* @returns {SharedState<T>}
|
555
|
-
*/
|
556
|
-
mergeStates(currentState, newState) {
|
557
|
-
return Object.assign(Object.assign({}, currentState), (newState || {}));
|
558
|
-
}
|
559
|
-
/**
|
560
|
-
* Met à jour l'état courant et le renvoie.
|
561
|
-
* @param {Partial<T>} updates
|
562
|
-
* @returns {SharedState<T>}
|
563
|
-
*/
|
564
|
-
updateState(updates) {
|
565
|
-
const currentState = this.getState();
|
566
|
-
const newState = Object.assign(Object.assign({}, currentState), updates);
|
567
|
-
this.setState(newState);
|
568
|
-
return newState;
|
569
|
-
}
|
570
|
-
/* =============================================
|
571
|
-
= MÉTHODES STATIQUES POUR PLUSIEURS GRAPHES =
|
572
|
-
============================================= */
|
573
|
-
/**
|
574
|
-
* Exécute plusieurs GraphEngine en **séquence** (l'un après l'autre).
|
575
|
-
* @param graphs Liste des graphes à exécuter
|
576
|
-
* @param startNodes Noms des nœuds de départ correspondants
|
577
|
-
* @param initialStates États initiaux correspondants
|
578
|
-
* @param onStream Callback d'avancement
|
579
|
-
* @param onError Callback d'erreur
|
580
|
-
* @returns Tableau des états finaux de chaque graphe
|
581
|
-
*/
|
582
|
-
static executeGraphsInSequence(graphs, startNodes, initialStates, actions, // Pass actions here
|
583
|
-
onStream, onError) {
|
584
|
-
return __awaiter(this, void 0, void 0, function* () {
|
585
|
-
// Return updated actions directly
|
586
|
-
const finalStates = [];
|
587
|
-
for (let i = 0; i < graphs.length; i++) {
|
588
|
-
const graph = graphs[i];
|
589
|
-
const startNode = startNodes[i];
|
590
|
-
const initialState = initialStates[i];
|
591
|
-
const result = yield graph.execute(initialState, startNode, onStream, onError);
|
592
|
-
finalStates.push({
|
593
|
-
name: graph.name,
|
594
|
-
result,
|
595
|
-
});
|
596
|
-
}
|
597
|
-
// Map results to actions
|
598
|
-
return actions.map((action) => {
|
599
|
-
const result = finalStates.find((state) => state.name === action.name);
|
600
|
-
return Object.assign(Object.assign({}, action), { result: result ? result.result : null });
|
601
|
-
});
|
602
|
-
});
|
603
|
-
}
|
604
|
-
/**
|
605
|
-
* Exécute plusieurs GraphEngine en **parallèle** (sans limite de concurrence).
|
606
|
-
* @param graphs Liste des graphes
|
607
|
-
* @param startNodes Noms des nœuds de départ
|
608
|
-
* @param initialStates États initiaux
|
609
|
-
* @param onStream Callback d'avancement
|
610
|
-
* @param onError Callback d'erreur
|
611
|
-
* @returns Tableau des états finaux de chaque graphe
|
612
|
-
*/
|
613
|
-
static executeGraphsInParallel(graphs, startNodes, initialStates, onStream, onError) {
|
614
|
-
return __awaiter(this, void 0, void 0, function* () {
|
615
|
-
const promises = graphs.map((graph, index) => graph.execute(initialStates[index], startNodes[index], onStream, onError));
|
616
|
-
return Promise.all(promises);
|
617
|
-
});
|
618
|
-
}
|
619
|
-
/**
|
620
|
-
* Exécute plusieurs GraphEngine en parallèle **avec une limite de concurrence**.
|
621
|
-
* @param graphs Liste des graphes
|
622
|
-
* @param startNodes Noms des nœuds de départ
|
623
|
-
* @param initialStates États initiaux
|
624
|
-
* @param concurrencyLimit Limite de concurrence
|
625
|
-
* @param onStream Callback d'avancement
|
626
|
-
* @param onError Callback d'erreur
|
627
|
-
* @returns Tableau des états finaux de chaque graphe
|
628
|
-
*/
|
629
|
-
static executeGraphsWithConcurrencyLimit(graphs, startNodes, initialStates, concurrencyLimit, onStream, onError) {
|
630
|
-
return __awaiter(this, void 0, void 0, function* () {
|
631
|
-
const results = [];
|
632
|
-
for (let i = 0; i < graphs.length; i += concurrencyLimit) {
|
633
|
-
const chunkGraphs = graphs.slice(i, i + concurrencyLimit);
|
634
|
-
const chunkStartNodes = startNodes.slice(i, i + concurrencyLimit);
|
635
|
-
const chunkInitialStates = initialStates.slice(i, i + concurrencyLimit);
|
636
|
-
const chunkPromises = chunkGraphs.map((graph, index) => {
|
637
|
-
return graph.execute(chunkInitialStates[index], chunkStartNodes[index], onStream, onError);
|
638
|
-
});
|
639
|
-
const chunkResults = yield Promise.all(chunkPromises);
|
640
|
-
results.push(...chunkResults);
|
641
|
-
}
|
642
|
-
return results;
|
643
|
-
});
|
644
|
-
}
|
645
|
-
}
|
646
|
-
exports.GraphEngine = GraphEngine;
|