### Streaming with Structured Output Source: https://github.com/bobofr/get-agent/blob/main/README.md This example combines streaming with Zod validation using `runStreamStructured`. It allows real-time display of streamed content while ensuring the final result conforms to a defined schema. ```typescript import { Agent } from "@thegetget/get-agent"; import { z } from "zod"; const agent = new Agent({ name: "Extracteur", model: "Qwen3.5-9B.gguf" }); const schema = z.object({ titre: z.string(), motsCles: z.array(z.string()), }); const { stream, result } = agent.runStreamStructured( "Génère un titre et des mots-clés pour un article sur les agents IA.", { schema, maxRetries: 2 } ); // Affichage temps réel for await (const chunk of stream) { process.stdout.write(chunk); } // Objet final validé const data = await result; console.log("\n\nObjet validé :", data); ``` -------------------------------- ### Create and Use a Math Skill Source: https://github.com/bobofr/get-agent/blob/main/README.md Defines and groups calculation and unit conversion tools into a reusable skill. The skill's tools are automatically prefixed unless `prefixToolNames` is set to false. Ensure Zod is installed for schema validation. ```typescript import { Agent, createTool, createSkill } from "@thegetget/get-agent"; import { z } from "zod"; // 1. Définir des outils const calculTool = createTool( "calculate", "Évalue une expression mathématique.", z.object({ expression: z.string() }), ({ expression }) => { const result = Function(`"use strict"; return (${expression})`)(); return { result }; } ); const convertTool = createTool( "convert_units", "Convertit des unités (km/miles, kg/lbs, C/F).", z.object({ value: z.number(), from: z.string(), to: z.string(), }), ({ value, from, to }) => { const conversions: Record number>> = { km: { miles: (v) => v * 0.621371 }, miles: { km: (v) => v * 1.60934 }, C: { F: (v) => (v * 9) / 5 + 32 }, F: { C: (v) => ((v - 32) * 5) / 9 }, }; return { result: conversions[from]?.[to]?.(value) ?? "Conversion non supportée" }; } ); // 2. Regrouper dans un Skill const mathSkill = createSkill({ name: "math", description: "Outils de calcul et conversion d'unités", tools: [calculTool, convertTool], systemPrompt: "Utilise les outils math_calculate et math_convert_units pour répondre aux questions numériques.", initialize: async () => console.log("✓ Math skill prêt"), shutdown: async () => console.log("✓ Math skill nettoyé"), }); // 3. Attacher le skill à un agent const agent = new Agent({ name: "Assistant", model: "Qwen3.5-9B.gguf", skills: [mathSkill], // Les outils seront exposés comme "math_calculate" et "math_convert_units" }); const response = await agent.run("Combien font 42 × 17, et convertis 100 km en miles ?"); console.log(response); // → 42 × 17 = 714. 100 km ≈ 62.14 miles. await agent.shutdown(); // Appelle automatiquement le hook shutdown du skill ``` -------------------------------- ### Human Approval for Sensitive Tools Source: https://github.com/bobofr/get-agent/blob/main/README.md Configure tools to require explicit user approval before execution using `requiresApproval` and `onApprovalRequired`. This example simulates a file deletion tool that requires confirmation. ```typescript import { Agent, createTool } from "@thegetget/get-agent"; import { z } from "zod"; const deleteFileTool = createTool( "delete_file", "Supprime définitivement un fichier.", z.object({ path: z.string() }), async ({ path }) => ({ success: true, deleted: path }) ); // Marque l'outil comme nécessitant une approbation humaine deleteFileTool.requiresApproval = true; const agent = new Agent({ name: "file-manager", systemPrompt: "Tu aides à gérer des fichiers.", model: "Qwen3.5-9B.gguf", tools: [deleteFileTool], // Appelé juste avant l'exécution de tout outil avec requiresApproval = true onApprovalRequired: async (toolName, args) => { console.log(`Approbation requise : ${toolName}(${JSON.stringify(args)})`); // Ici : demander une confirmation (readline, UI, webhook...). On simule un refus. return false; }, }); const response = await agent.run("Supprime le fichier /data/backup.sql."); console.log(response); // L'agent reçoit { cancelled: true } et adapte sa réponse ``` -------------------------------- ### Implementing Agent Hooks Source: https://github.com/bobofr/get-agent/blob/main/README.md Use AgentHooks to intercept and modify the agent's lifecycle. This example demonstrates logging LLM calls, normalizing tool arguments, and enriching tool results. ```typescript import { Agent, createTool, AgentHooks } from "@thegetget/get-agent"; import { z } from "zod"; const weatherTool = createTool( "get_weather", "Retourne la météo simulée pour une ville.", z.object({ city: z.string() }), async ({ city }) => ({ city, temperature: 21, condition: "Ensoleillé" }) ); const hooks: AgentHooks = { beforeLLMCall: (messages) => { console.log(`[hook] ${messages.length} messages envoyés au LLM`); return messages; }, afterLLMCall: (content, toolCalls) => { if (toolCalls?.length) console.log(`[hook] outils demandés : ${toolCalls.map(t => t.function.name).join(", ")}`); }, beforeToolCall: (toolName, args) => { // Normalise / valide les arguments avant exécution if (toolName === "get_weather") args.city = args.city.trim(); return args; }, afterToolCall: (toolName, _args, result) => { // Enrichit le résultat retourné au LLM return { ...result, source: "weather-api" }; }, }; const agent = new Agent({ name: "hooked-agent", model: "Qwen3.5-9B.gguf", tools: [weatherTool], hooks, }); console.log(await agent.run("Quelle est la météo à Paris ?")); ``` -------------------------------- ### Interactive REPL for Agents Source: https://github.com/bobofr/get-agent/blob/main/README.md This snippet demonstrates how to launch an interactive command-line interface (REPL) for an agent using `agent.repl()`. It's useful for quick testing and interaction with agents. ```typescript import { Agent } from "@thegetget/get-agent"; const agent = new Agent({ name: "mon-agent", systemPrompt: "Tu es un assistant utile.", model: "Qwen3.5-9B.gguf", }); // stream: true pour afficher les réponses en temps réel await agent.repl({ stream: true, prompt: "Vous" }); ``` -------------------------------- ### Sequential ETL Workflow Source: https://github.com/bobofr/get-agent/blob/main/README.md Demonstrates a linear sequence of steps for data extraction, transformation, and loading. Ensure all necessary imports are included. ```typescript import { Workflow } from "@thegetget/get-agent"; interface EtatPipeline { donneesBrutes: string; donneesNettoyees: string; rapport: string; } const pipeline = new Workflow({ name: "Pipeline ETL", verbose: true, }); pipeline .addStep("extraire", async (state) => { // Extraction des données depuis une source return { donneesBrutes: "ligne1;ligne2;ligne3" }; }) .addStep("transformer", async (state) => { // Nettoyage et transformation const nettoyees = state.donneesBrutes.split(";").map(s => s.trim()).join(", "); return { donneesNettoyees: nettoyees }; }) .addStep("charger", async (state) => { // Génération du rapport final return { rapport: `Données chargées : ${state.donneesNettoyees}` }; }); // Chaîne linéaire : extraire -> transformer -> charger -> END pipeline .setStart("extraire") .addEdge("extraire", "transformer") .addEdge("transformer", "charger") .addEdge("charger", "END"); const resultat = await pipeline.run({ donneesBrutes: "", donneesNettoyees: "", rapport: "", }); console.log(resultat.rapport); ``` -------------------------------- ### Connect to MCP Servers Source: https://github.com/bobofr/get-agent/blob/main/README.md Connects the agent to configured MCP servers via stdio and exposes their tools. Ensure the MCP server command and arguments are correctly specified. ```typescript import { Agent } from "@thegetget/get-agent"; const agent = new Agent({ name: "AgentFichiers", model: "Qwen3.5-9B.gguf", mcpServers: [ { name: "filesystem", command: "node", args: ["/chemin/vers/mcp-server-filesystem/dist/index.js", "/dossier/autorise"], } ] }); // L'agent utilise les outils fournis par le serveur MCP (ex: list_directory, read_file) const response = await agent.run("Quels sont les fichiers présents dans le dossier autorisé ?"); console.log(response); ``` -------------------------------- ### Creating an Agent Tool (Sub-Agents) Source: https://github.com/bobofr/get-agent/blob/main/README.md Encapsulate an Agent as a tool using `createAgentTool` to enable agent orchestration. This allows a main agent to delegate tasks to specialized sub-agents. ```typescript import { Agent, createAgentTool } from "@thegetget/get-agent"; // Agent spécialisé const traducteur = new Agent({ name: "Traducteur", systemPrompt: "Tu traduis fidèlement vers l'anglais. Réponds uniquement avec la traduction.", model: "Qwen3.5-9B.gguf", }); // On l'expose comme un outil const traducteurTool = createAgentTool(traducteur, { name: "traduire_en_anglais", description: "Traduit un texte français vers l'anglais.", keepHistory: false, // Réinitialise l'historique du sous-agent à chaque appel (défaut) }); // Agent orchestrateur const assistant = new Agent({ name: "Assistant", systemPrompt: "Tu es un assistant. Utilise tes outils quand c'est pertinent.", model: "Qwen3.5-9B.gguf", tools: [traducteurTool], }); console.log(await assistant.run("Traduis 'Bonjour le monde' en anglais.")); ``` -------------------------------- ### Multi-Agent Workflow with Feedback Loop Source: https://github.com/bobofr/get-agent/blob/main/README.md This snippet demonstrates a multi-agent workflow where agents collaborate and provide feedback to refine a draft. It's useful for complex content generation tasks requiring iterative improvement. ```typescript import { Workflow, Agent } from "@thegetget/get-agent"; interface BlogState { sujet: string; draft: string; feedback: string; approuve: boolean; } const redacteur = new Agent({ name: "Redacteur", systemPrompt: "Rédige des articles clairs et informatifs.", model: "Qwen3.5-9B.gguf" }); const correcteur = new Agent({ name: "Correcteur", systemPrompt: "Recherche les faiblesses. Réponds par 'OK' si le texte est parfait, sinon donne des axes d'amélioration.", model: "Qwen3.5-9B.gguf" }); const workflow = new Workflow({ name: "Redaction Article", verbose: true, }); workflow .addStep("rediger", async (state) => { const prompt = `Rédige un article sur : ${state.sujet}.\nFeedback précédent : ${state.feedback}`; const response = await redacteur.run(prompt); return { draft: typeof response === "string" ? response : JSON.stringify(response) }; }) .addStep("reviser", async (state) => { const prompt = `Valide l'article suivant :\n${state.draft}`; const response = await correcteur.run(prompt); const feedback = typeof response === "string" ? response : JSON.stringify(response); return { feedback, approuve: feedback.toUpperCase().includes("OK") }; }); workflow .setStart("rediger") .addEdge("rediger", "reviser") // Boucle : si rejeté, retour à la rédaction avec le feedback .addConditionalEdge("reviser", (state) => { return state.approuve ? "END" : "rediger"; }); const etatFinal = await workflow.run({ sujet: "Les avantages du protocole MCP pour les agents IA", draft: "", feedback: "", approuve: false }); console.log("Article validé et publié !\n", etatFinal.draft); ``` -------------------------------- ### Add and Remove Skills Dynamically Source: https://github.com/bobofr/get-agent/blob/main/README.md Demonstrates adding and removing skills from an agent at runtime. The `prefixToolNames` option can disable automatic tool name prefixing. Ensure the agent is shut down to trigger skill shutdown hooks. ```typescript import { Agent, createTool, createSkill } from "@thegetget/get-agent"; import { z } from "zod"; const timeTool = createTool( "current_time", "Retourne la date et l'heure actuelle.", z.object({}), () => ({ timestamp: new Date().toISOString() }) ); const timeSkill = createSkill({ name: "time", description: "Utilitaires de date et heure", tools: [timeTool], prefixToolNames: false, // Désactive le préfixe → l'outil reste "current_time" }); const agent = new Agent({ name: "Assistant", model: "Qwen3.5-9B.gguf", }); // Ajout dynamique await agent.addSkill(timeSkill); console.log(agent.getRegisteredSkills()); // [Skill { name: "time" }] console.log(agent.getRegisteredTools()); // [Tool { name: "current_time" }] // Utilisation const response = await agent.run("Quelle heure est-il ?"); console.log(response); // Suppression à chaud (appelle le hook shutdown du skill) await agent.removeSkill("time"); console.log(agent.getRegisteredTools()); // [] — les outils du skill ont été retirés await agent.shutdown(); ``` -------------------------------- ### Streaming Agent Responses Source: https://github.com/bobofr/get-agent/blob/main/README.md This snippet shows how to stream agent responses token by token using `runStream`. It's ideal for providing real-time feedback to the user during long-running agent tasks. ```typescript import { Agent } from "@thegetget/get-agent"; const agent = new Agent({ name: "Conteur", systemPrompt: "Tu es un conteur captivant.", model: "Qwen3.5-9B.gguf", showThinking: false, // Masque les blocs du flux }); // Itère sur les fragments au fur et à mesure de leur génération for await (const chunk of agent.runStream("Raconte une courte histoire sur un robot curieux.")) { process.stdout.write(chunk); } ``` -------------------------------- ### Conditional Order Processing Workflow Source: https://github.com/bobofr/get-agent/blob/main/README.md Illustrates a workflow with dynamic branching using `addConditionalEdge` based on order validation. The workflow can either confirm or cancel the order. ```typescript import { Workflow } from "@thegetget/get-agent"; interface EtatCommande { commandeId: string; panierValide: boolean; stockDisponible: boolean; status: string; } const workflow = new Workflow({ name: "Traitement Commande", verbose: true, }); workflow .addStep("verifierPanier", async (state) => { return { panierValide: true }; }) .addStep("verifierStock", async (state) => { return { stockDisponible: true }; }) .addStep("confirmerCommande", async (state) => { return { status: "CONFIRMÉE" }; }) .addStep("annulerCommande", async (state) => { return { status: "ANNULÉE" }; }); workflow .setStart("verifierPanier") // Branchement : panier valide -> vérifier stock, sinon -> annuler .addConditionalEdge("verifierPanier", (state) => { return state.panierValide ? "verifierStock" : "annulerCommande"; }) // Branchement : stock disponible -> confirmer, sinon -> annuler .addConditionalEdge("verifierStock", (state) => { return state.stockDisponible ? "confirmerCommande" : "annulerCommande"; }) .addEdge("confirmerCommande", "END") .addEdge("annulerCommande", "END"); const etatFinal = await workflow.run({ commandeId: "CMD-9876", panierValide: false, stockDisponible: false, status: "INITIE" }); console.log("Statut final :", etatFinal.status); ``` -------------------------------- ### AI Agent Text Analysis Workflow Source: https://github.com/bobofr/get-agent/blob/main/README.md Integrates an AI Agent within workflow steps to perform text summarization, sentiment analysis, and translation. Ensure the Agent model is correctly specified. ```typescript import { Workflow, Agent } from "@thegetget/get-agent"; interface EtatAnalyse { texteOriginal: string; resume: string; sentiment: string; traduction: string; } // Un seul agent polyvalent utilisé à chaque étape const agent = new Agent({ name: "Analyste", systemPrompt: "Tu es un assistant d'analyse de texte. Réponds de manière concise.", model: "Qwen3.5-9B.gguf", }); const pipeline = new Workflow({ name: "Analyse de Texte", verbose: true, }); pipeline .addStep("resumer", async (state) => { const response = await agent.run( `Résume le texte suivant en 2 phrases maximum :\n${state.texteOriginal}` ); return { resume: String(response) }; }) .addStep("analyserSentiment", async (state) => { const response = await agent.run( `Quel est le sentiment général (positif, négatif ou neutre) de ce texte ?\n${state.resume}` ); return { sentiment: String(response) }; }) .addStep("traduire", async (state) => { const response = await agent.run( `Traduis ce résumé en anglais :\n${state.resume}` ); return { traduction: String(response) }; }); pipeline .setStart("resumer") .addEdge("resumer", "analyserSentiment") .addEdge("analyserSentiment", "traduire") .addEdge("traduire", "END"); const resultat = await pipeline.run({ texteOriginal: "L'intelligence artificielle transforme tous les secteurs. Les entreprises adoptent massivement ces technologies pour améliorer leur productivité et innover.", resume: "", sentiment: "", traduction: "", }); console.log("Résumé :", resultat.resume); console.log("Sentiment :", resultat.sentiment); console.log("Traduction :", resultat.traduction); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.