Ajouter des conditions
Ajoutez des conditions pour orienter l'exécution en fonction des données du contexte. Créez des branches conditionnelles pour adapter le parcours.
Ajouter des conditions à un graphe
Implémentation du graphe avec logique conditionnelle
import { GraphFlow, GraphNodeConfig } from "@ai.ntellect/core";
import { z } from "zod";
// Définition du schéma du contexte
const schema = z.object({
input: z.string(),
processed: z.string().optional(),
result: z.string().optional(),
});
// Nœud 1 : Convertir le texte en majuscules
const processText: GraphNodeConfig<typeof schema> = {
name: "processText",
execute: async (context) => {
context.processed = context.input.toUpperCase();
console.log("Texte transformé :", context.processed);
},
next: (context) => {
return (context.processed?.length ?? 0) > 10
? ["longTextHandler"]
: ["shortTextHandler"];
},
};
// Nœud 2A : Gérer un texte long
const longTextHandler: GraphNodeConfig<typeof schema> = {
name: "longTextHandler",
execute: async (context) => {
context.result = `LONG: ${context.processed}`;
console.log("Le texte est long :", context.result);
},
next: ["logResult"],
};
// Nœud 2B : Gérer un texte court
const shortTextHandler: GraphNodeConfig<typeof schema> = {
name: "shortTextHandler",
execute: async (context) => {
context.result = `COURT: ${context.processed}`;
console.log("Le texte est court :", context.result);
},
next: ["logResult"],
};
// Nœud final : Afficher le résultat
const logResult: GraphNodeConfig<typeof schema> = {
name: "logResult",
execute: async (context) => {
console.log("Résultat final :", context.result);
},
};
// Création du graphe
const graph = new GraphFlow("GraphWithDecision", {
name: "GraphWithDecision",
nodes: [processText, longTextHandler, shortTextHandler, logResult],
context: { input: "" },
schema,
entryNode: "processText",
});
// Exécution du graphe avec différents inputs
(async () => {
console.log("Exécution avec un texte court");
await graph.execute("processText", { input: "Hello" });
console.log("Exécution avec un texte long");
await graph.execute("processText", { input: "Hello GraphFlow!" });
})();Explication du code
Ajout d’un next dynamique
next dynamiqueAffichage du résultat final
Résultat attendu
Cas 1 : Texte court
Cas 2 : Texte long
Récapitulatif
Mis à jour