@ai.ntellect/core 0.6.10 → 0.6.12

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