agentic-api 2.0.31 → 2.0.314

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 (89) hide show
  1. package/dist/src/agents/agents.example.js +21 -22
  2. package/dist/src/agents/authentication.js +1 -2
  3. package/dist/src/agents/prompts.d.ts +5 -4
  4. package/dist/src/agents/prompts.js +42 -87
  5. package/dist/src/agents/reducer.core.d.ts +24 -2
  6. package/dist/src/agents/reducer.core.js +125 -35
  7. package/dist/src/agents/reducer.loaders.d.ts +55 -1
  8. package/dist/src/agents/reducer.loaders.js +114 -1
  9. package/dist/src/agents/reducer.types.d.ts +45 -2
  10. package/dist/src/agents/semantic.js +1 -2
  11. package/dist/src/agents/simulator.d.ts +4 -0
  12. package/dist/src/agents/simulator.executor.d.ts +5 -1
  13. package/dist/src/agents/simulator.executor.js +41 -9
  14. package/dist/src/agents/simulator.js +86 -28
  15. package/dist/src/agents/simulator.prompts.d.ts +3 -2
  16. package/dist/src/agents/simulator.prompts.js +52 -78
  17. package/dist/src/agents/simulator.types.d.ts +20 -5
  18. package/dist/src/agents/simulator.utils.d.ts +7 -2
  19. package/dist/src/agents/simulator.utils.js +33 -11
  20. package/dist/src/agents/system.js +1 -2
  21. package/dist/src/execute.d.ts +17 -3
  22. package/dist/src/execute.js +156 -158
  23. package/dist/src/index.d.ts +1 -1
  24. package/dist/src/index.js +1 -1
  25. package/dist/src/{princing.openai.d.ts → pricing.llm.d.ts} +6 -0
  26. package/dist/src/pricing.llm.js +234 -0
  27. package/dist/src/prompts.d.ts +13 -4
  28. package/dist/src/prompts.js +221 -114
  29. package/dist/src/rag/embeddings.d.ts +36 -18
  30. package/dist/src/rag/embeddings.js +125 -128
  31. package/dist/src/rag/index.d.ts +5 -5
  32. package/dist/src/rag/index.js +14 -17
  33. package/dist/src/rag/parser.d.ts +2 -1
  34. package/dist/src/rag/parser.js +11 -14
  35. package/dist/src/rag/rag.examples.d.ts +27 -0
  36. package/dist/src/rag/rag.examples.js +151 -0
  37. package/dist/src/rag/rag.manager.d.ts +383 -0
  38. package/dist/src/rag/rag.manager.js +1378 -0
  39. package/dist/src/rag/types.d.ts +128 -12
  40. package/dist/src/rag/types.js +100 -1
  41. package/dist/src/rag/usecase.d.ts +37 -0
  42. package/dist/src/rag/usecase.js +96 -7
  43. package/dist/src/rules/git/git.e2e.helper.js +1 -0
  44. package/dist/src/rules/git/git.health.d.ts +57 -0
  45. package/dist/src/rules/git/git.health.js +281 -1
  46. package/dist/src/rules/git/index.d.ts +2 -2
  47. package/dist/src/rules/git/index.js +12 -1
  48. package/dist/src/rules/git/repo.d.ts +117 -0
  49. package/dist/src/rules/git/repo.js +536 -0
  50. package/dist/src/rules/git/repo.tools.d.ts +22 -1
  51. package/dist/src/rules/git/repo.tools.js +50 -1
  52. package/dist/src/rules/types.d.ts +16 -14
  53. package/dist/src/rules/utils.matter.d.ts +0 -4
  54. package/dist/src/rules/utils.matter.js +26 -7
  55. package/dist/src/scrapper.d.ts +15 -22
  56. package/dist/src/scrapper.js +57 -110
  57. package/dist/src/stategraph/index.d.ts +1 -1
  58. package/dist/src/stategraph/stategraph.d.ts +31 -2
  59. package/dist/src/stategraph/stategraph.js +93 -6
  60. package/dist/src/stategraph/stategraph.storage.js +4 -0
  61. package/dist/src/stategraph/types.d.ts +22 -0
  62. package/dist/src/types.d.ts +4 -2
  63. package/dist/src/types.js +1 -1
  64. package/dist/src/usecase.d.ts +11 -2
  65. package/dist/src/usecase.js +27 -35
  66. package/dist/src/utils.d.ts +32 -18
  67. package/dist/src/utils.js +60 -126
  68. package/package.json +7 -2
  69. package/dist/src/agents/digestor.test.d.ts +0 -1
  70. package/dist/src/agents/digestor.test.js +0 -45
  71. package/dist/src/agents/reducer.example.d.ts +0 -28
  72. package/dist/src/agents/reducer.example.js +0 -118
  73. package/dist/src/agents/reducer.process.d.ts +0 -16
  74. package/dist/src/agents/reducer.process.js +0 -143
  75. package/dist/src/agents/reducer.tools.d.ts +0 -29
  76. package/dist/src/agents/reducer.tools.js +0 -157
  77. package/dist/src/agents/simpleExample.d.ts +0 -3
  78. package/dist/src/agents/simpleExample.js +0 -38
  79. package/dist/src/agents/system-review.d.ts +0 -5
  80. package/dist/src/agents/system-review.js +0 -181
  81. package/dist/src/agents/systemReview.d.ts +0 -4
  82. package/dist/src/agents/systemReview.js +0 -22
  83. package/dist/src/princing.openai.js +0 -54
  84. package/dist/src/rag/tools.d.ts +0 -76
  85. package/dist/src/rag/tools.js +0 -196
  86. package/dist/src/rules/user.mapper.d.ts +0 -61
  87. package/dist/src/rules/user.mapper.js +0 -160
  88. package/dist/src/rules/utils/slug.d.ts +0 -22
  89. package/dist/src/rules/utils/slug.js +0 -35
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentic-api",
3
- "version": "2.0.31",
3
+ "version": "2.0.314",
4
4
  "description": "API pour l'orchestration d'agents intelligents avec séquences et escalades automatiques",
5
5
  "main": "dist/src/index.js",
6
6
  "types": "dist/src/index.d.ts",
@@ -10,7 +10,11 @@
10
10
  "scripts": {
11
11
  "prebuild": "npm version patch --no-git-tag-version",
12
12
  "build": "tsc",
13
- "test": "jest",
13
+ "test": "jest -- tests --testPathIgnorePatterns=agent* --silent --verbose=false",
14
+ "test:quiet": "jest --silent -- tests --testPathIgnorePatterns=agent*",
15
+ "test:verbose": "jest --verbose -- tests --testPathIgnorePatterns=agent*",
16
+ "test:simulator": "jest -- tests --testNamePattern=simulator.* --silent --verbose=false",
17
+ "test:simulator:quiet": "jest --silent -- tests --testNamePattern=simulator.*",
14
18
  "lint": "eslint 'src/**/*.ts'",
15
19
  "prepublishOnly": "npm run build",
16
20
  "extract:pdf": "texttopdf ",
@@ -21,6 +25,7 @@
21
25
  },
22
26
  "dependencies": {
23
27
  "@mozilla/readability": "^0.6.0",
28
+ "async-mutex": "^0.5.0",
24
29
  "dotenv": "^16.4.7",
25
30
  "hnswlib-node": "^3.0.0",
26
31
  "jsdom": "^26.0.0",
@@ -1 +0,0 @@
1
- export {};
@@ -1,45 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const execute_1 = require("../execute");
4
- const digestor_1 = require("./digestor");
5
- // Implémentation simple du cache pour les tests
6
- class TestCache {
7
- constructor() {
8
- this.cache = new Map();
9
- }
10
- async get(key) {
11
- return this.cache.get(key) || null;
12
- }
13
- async set(key, value, ttl) {
14
- this.cache.set(key, value);
15
- return value;
16
- }
17
- }
18
- describe("Digestor Agent", () => {
19
- it("should merge two chunks of 50 characters", async () => {
20
- // Création d'un contenu de test de 100 caractères
21
- const testContent = "A".repeat(50) + "B".repeat(50);
22
- // Configuration de l'agent avec une instruction simple de fusion
23
- const agentConfig = {
24
- name: "chunkMerger",
25
- publicDescription: "Agent that merges chunks of text",
26
- instructions: `You are a simple agent that merges chunks of text.
27
- When you receive a chunk, you should:
28
- 1. If it's the first chunk, store it
29
- 2. If it's the second chunk, merge it with the first one
30
- 3. If you receive "EOF", return the final merged result`,
31
- tools: [digestor_1.Digestor.createTools(new TestCache(), 50).toolPullContentDigestor]
32
- };
33
- // Mock du cache pour simuler le contenu
34
- const cache = new TestCache();
35
- await cache.set("content:test.txt", testContent);
36
- // Exécution de l'agent
37
- const result = await (0, execute_1.executeAgentSet)([agentConfig], {
38
- messages: [],
39
- cache,
40
- user: { id: "test-user" }
41
- });
42
- // Vérification du résultat
43
- expect(result.messages[result.messages.length - 1].content).toBe("A".repeat(50) + "B".repeat(50));
44
- });
45
- });
@@ -1,28 +0,0 @@
1
- /**
2
- * MapLLM Reducer - Simple hierarchical reducer
3
- *
4
- * Main export file for the MapLLM reducer functionality
5
- */
6
- export { MapLLM } from './reducer.core';
7
- export { FileNativeLoader, StringNativeLoader } from './reducer.loaders';
8
- export type { NativeLoader, StatefulReducerConfig, MapLLMOptions, ReduceResult, ChunkStrategy } from './reducer.types';
9
- export declare const exampleConfigs: {
10
- weather: {
11
- digestPrompt: string;
12
- reducePrompt: string;
13
- };
14
- foods: {
15
- digestPrompt: string;
16
- reducePrompt: string;
17
- };
18
- };
19
- export declare const examples: {
20
- /**
21
- * Example: Weather data analysis
22
- */
23
- weatherAnalysis(weatherFilePath: string): Promise<import("./reducer.types").ReduceResult>;
24
- /**
25
- * Example: Food selection from string content
26
- */
27
- foodSelection(foodListContent: string): Promise<import("./reducer.types").ReduceResult>;
28
- };
@@ -1,118 +0,0 @@
1
- "use strict";
2
- /**
3
- * MapLLM Reducer - Simple hierarchical reducer
4
- *
5
- * Main export file for the MapLLM reducer functionality
6
- */
7
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
- if (k2 === undefined) k2 = k;
9
- var desc = Object.getOwnPropertyDescriptor(m, k);
10
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
- desc = { enumerable: true, get: function() { return m[k]; } };
12
- }
13
- Object.defineProperty(o, k2, desc);
14
- }) : (function(o, m, k, k2) {
15
- if (k2 === undefined) k2 = k;
16
- o[k2] = m[k];
17
- }));
18
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
- Object.defineProperty(o, "default", { enumerable: true, value: v });
20
- }) : function(o, v) {
21
- o["default"] = v;
22
- });
23
- var __importStar = (this && this.__importStar) || (function () {
24
- var ownKeys = function(o) {
25
- ownKeys = Object.getOwnPropertyNames || function (o) {
26
- var ar = [];
27
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
- return ar;
29
- };
30
- return ownKeys(o);
31
- };
32
- return function (mod) {
33
- if (mod && mod.__esModule) return mod;
34
- var result = {};
35
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
- __setModuleDefault(result, mod);
37
- return result;
38
- };
39
- })();
40
- Object.defineProperty(exports, "__esModule", { value: true });
41
- exports.examples = exports.exampleConfigs = exports.StringNativeLoader = exports.FileNativeLoader = exports.MapLLM = void 0;
42
- // Core classes
43
- var reducer_core_1 = require("./reducer.core");
44
- Object.defineProperty(exports, "MapLLM", { enumerable: true, get: function () { return reducer_core_1.MapLLM; } });
45
- var reducer_loaders_1 = require("./reducer.loaders");
46
- Object.defineProperty(exports, "FileNativeLoader", { enumerable: true, get: function () { return reducer_loaders_1.FileNativeLoader; } });
47
- Object.defineProperty(exports, "StringNativeLoader", { enumerable: true, get: function () { return reducer_loaders_1.StringNativeLoader; } });
48
- // Example configurations
49
- exports.exampleConfigs = {
50
- weather: {
51
- digestPrompt: `Tu es un expert en analyse de données météorologiques.
52
- Analyse ce chunk de données météo et extrais:
53
- - Les types de météo présents (ensoleillé, pluvieux, nuageux, neigeux, orageux)
54
- - Le nombre d'entrées par type
55
- - Les IDs associés à chaque type
56
-
57
- Réponds en JSON strict avec la structure:
58
- {
59
- "weatherTypes": {
60
- "ensoleillé": {"count": N, "ids": [...]},
61
- "pluvieux": {"count": N, "ids": [...]}
62
- }
63
- }`,
64
- reducePrompt: `Tu es un expert en consolidation de données météorologiques.
65
- Synthétise toutes les analyses météo en un résultat consolidé:
66
- - Fusionne tous les types de météo
67
- - Additionne les counts
68
- - Combine les IDs (sans doublons)
69
- - Calcule les totaux par type
70
-
71
- Réponds en JSON avec la structure finale consolidée.`
72
- },
73
- foods: {
74
- digestPrompt: `Tu es un expert en nutrition végétarienne.
75
- Analyse cette liste d'aliments et identifie:
76
- - Les aliments végétariens/vegan
77
- - Leur catégorie (légumes, fruits, céréales, légumineuses, etc.)
78
- - Leur valeur nutritionnelle approximative
79
-
80
- Réponds en JSON strict avec les aliments sélectionnés.`,
81
- reducePrompt: `Tu es un expert en nutrition végétarienne.
82
- Crée une sélection équilibrée d'aliments végétariens/vegan:
83
- - Distribution équilibrée entre catégories
84
- - Maximum 50 aliments
85
- - Priorité aux aliments nutritifs et variés
86
-
87
- Réponds avec la liste finale sélectionnée en JSON.`
88
- }
89
- };
90
- // Usage examples
91
- exports.examples = {
92
- /**
93
- * Example: Weather data analysis
94
- */
95
- async weatherAnalysis(weatherFilePath) {
96
- const { FileNativeLoader } = await Promise.resolve().then(() => __importStar(require('./reducer.loaders')));
97
- const { MapLLM } = await Promise.resolve().then(() => __importStar(require('./reducer.core')));
98
- const loader = new FileNativeLoader(weatherFilePath, { type: 'lines', size: 50 });
99
- const mapper = new MapLLM(loader);
100
- return await mapper.reduce(exports.exampleConfigs.weather, {
101
- verbose: true,
102
- maxRetries: 3
103
- });
104
- },
105
- /**
106
- * Example: Food selection from string content
107
- */
108
- async foodSelection(foodListContent) {
109
- const { StringNativeLoader } = await Promise.resolve().then(() => __importStar(require('./reducer.loaders')));
110
- const { MapLLM } = await Promise.resolve().then(() => __importStar(require('./reducer.core')));
111
- const loader = new StringNativeLoader(foodListContent, { type: 'lines', size: 100 });
112
- const mapper = new MapLLM(loader);
113
- return await mapper.reduce(exports.exampleConfigs.foods, {
114
- verbose: true,
115
- maxDigestSize: 3000
116
- });
117
- }
118
- };
@@ -1,16 +0,0 @@
1
- import { StatefulReducerConfig, StatefulReduceResult, StatefulProcessOptions, ChunkLoader } from "./reducer.types";
2
- /**
3
- * Main function to process a document using the stateful agent reduce pattern
4
- *
5
- * @param sessionId - Session ID for the discussion/document to process
6
- * @param config - Stateful reducer configuration
7
- * @param loader - ChunkLoader interface for loading content chunks
8
- * @param options - Additional options
9
- * @returns Promise resolving to the stateful reduce result
10
- */
11
- export declare function statefulReduceProcess<T = any>(sessionId: string, config: StatefulReducerConfig, loader: ChunkLoader, options?: StatefulProcessOptions): Promise<StatefulReduceResult<T>>;
12
- /**
13
- * Legacy function name for backward compatibility
14
- * @deprecated Use statefulReduceProcess instead
15
- */
16
- export declare function agentReduceProcess<T = any>(sessionId: string, config: any, loader: ChunkLoader, options?: any): Promise<any>;
@@ -1,143 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.statefulReduceProcess = statefulReduceProcess;
4
- exports.agentReduceProcess = agentReduceProcess;
5
- const execute_1 = require("../execute");
6
- const reducer_tools_1 = require("./reducer.tools");
7
- /**
8
- * Main function to process a document using the stateful agent reduce pattern
9
- *
10
- * @param sessionId - Session ID for the discussion/document to process
11
- * @param config - Stateful reducer configuration
12
- * @param loader - ChunkLoader interface for loading content chunks
13
- * @param options - Additional options
14
- * @returns Promise resolving to the stateful reduce result
15
- */
16
- async function statefulReduceProcess(sessionId, config, loader, options = {}) {
17
- const { stdout = process.stdout, maxIterations = 50, model = (0, execute_1.modelConfig)("MEDIUM"), verbose = config.verbose || false } = options;
18
- // Create the stateful reducer tools
19
- const { statefulReduceProcessChunk, toolStatefulReduceProcessChunk } = (0, reducer_tools_1.createStatefulReduceTools)(loader, config);
20
- // Create initial agent configuration with dynamic system prompt
21
- let agentConfig = {
22
- name: "statefulReducer",
23
- model,
24
- publicDescription: "Agent that processes large content using stateful reducer pattern with digest replacement",
25
- instructions: `${config.systemTemplate.replace('{{reducerContent}}', '')}
26
-
27
- IMPORTANT: Always use sessionId="${sessionId}" and template="${config.templates ? Object.keys(config.templates)[0] : 'semantic'}" when calling statefulReduceProcessChunk.
28
- Start with position=0 and continue with the nextPosition returned by the tool.`,
29
- tools: [toolStatefulReduceProcessChunk],
30
- toolLogic: {
31
- statefulReduceProcessChunk: (args, context) => statefulReduceProcessChunk(args, context)
32
- }
33
- };
34
- // Track the conversation and results
35
- let position = 0;
36
- let iterations = 0;
37
- let finalDigest;
38
- let allMessages = [];
39
- let totalUsage = { prompt: 0, completion: 0, total: 0, cost: 0 };
40
- let compressionHistory = [];
41
- if (verbose) {
42
- console.log(`🚀 statefulReduceProcess: Starting stateful reduce process for session: ${sessionId}`);
43
- }
44
- // Process the document iteratively with stateful pattern
45
- while (iterations < maxIterations) {
46
- iterations++;
47
- const templateName = config.templates ? Object.keys(config.templates)[0] : 'semantic';
48
- const query = iterations === 1
49
- ? `Process the session "${sessionId}" with template "${templateName}" starting from position 0 using stateful reducer pattern.`
50
- : `Continue processing from position ${position} with stateful reducer pattern.`;
51
- if (verbose) {
52
- console.log(`📝 statefulReduceProcess: Iteration ${iterations}: Processing from position ${position}`);
53
- }
54
- try {
55
- // Execute the agent for this iteration
56
- const result = await (0, execute_1.executeAgent)([agentConfig], {
57
- query,
58
- home: "statefulReducer",
59
- stdout,
60
- verbose
61
- });
62
- // Accumulate usage
63
- if (result.usage) {
64
- totalUsage.prompt += result.usage.prompt || 0;
65
- totalUsage.completion += result.usage.completion || 0;
66
- totalUsage.total += result.usage.total || 0;
67
- totalUsage.cost += result.usage.cost || 0;
68
- }
69
- // Add messages to our conversation log
70
- if (result.messages) {
71
- allMessages.push(...result.messages);
72
- }
73
- // Parse the last tool result to get next position and check for EOF
74
- const lastMessage = result.messages?.[result.messages.length - 1];
75
- if (lastMessage?.role === 'tool') {
76
- try {
77
- const toolResult = JSON.parse(lastMessage.content);
78
- if (toolResult.eof) {
79
- finalDigest = toolResult.finalDigest;
80
- if (verbose) {
81
- console.log(`✅ Stateful document processing complete after ${iterations} iterations`);
82
- console.log(`📊 Final digest size: ${toolResult.metadata?.finalDigestSize || 'unknown'} chars`);
83
- }
84
- break;
85
- }
86
- // Update position for next iteration
87
- position = toolResult.nextPosition || position;
88
- // Update agent configuration with new system prompt (STATEFUL)
89
- if (toolResult.systemPrompt) {
90
- agentConfig.instructions = toolResult.systemPrompt;
91
- if (verbose) {
92
- console.log(`🔄 System prompt updated for iteration ${iterations + 1}`);
93
- }
94
- }
95
- // Track compression if applied
96
- if (toolResult.compressionApplied) {
97
- compressionHistory.push(toolResult.compressionRatio || 0.8);
98
- }
99
- }
100
- catch (error) {
101
- if (verbose) {
102
- console.error(`❌ Error parsing tool result:`, error);
103
- }
104
- break;
105
- }
106
- }
107
- }
108
- catch (error) {
109
- if (verbose) {
110
- console.error(`❌ Error in iteration ${iterations}:`, error);
111
- }
112
- throw error;
113
- }
114
- }
115
- if (iterations >= maxIterations) {
116
- throw new Error(`Maximum iterations (${maxIterations}) reached without completion`);
117
- }
118
- if (finalDigest === undefined) {
119
- throw new Error("Processing completed but no final digest was produced");
120
- }
121
- return {
122
- finalDigest: finalDigest,
123
- iterations,
124
- compressionHistory,
125
- metadata: {
126
- totalChunks: iterations,
127
- finalDigestSize: typeof finalDigest === 'string' ? finalDigest.length : JSON.stringify(finalDigest).length,
128
- averageCompressionRatio: compressionHistory.length > 0
129
- ? compressionHistory.reduce((a, b) => a + b, 0) / compressionHistory.length
130
- : 1.0,
131
- sessionId
132
- },
133
- messages: allMessages
134
- };
135
- }
136
- /**
137
- * Legacy function name for backward compatibility
138
- * @deprecated Use statefulReduceProcess instead
139
- */
140
- async function agentReduceProcess(sessionId, config, loader, options = {}) {
141
- console.warn('agentReduceProcess is deprecated. Use statefulReduceProcess instead.');
142
- return statefulReduceProcess(sessionId, config, loader, options);
143
- }
@@ -1,29 +0,0 @@
1
- import { Tool } from "../types";
2
- import { StatefulReducerConfig, ChunkLoader } from "./reducer.types";
3
- /**
4
- * Creates the stateful agent reduce tools with proper configuration
5
- *
6
- * @param loader - ChunkLoader interface for loading content chunks
7
- * @param config - Stateful reducer configuration
8
- * @returns Object containing the tool function and tool definition
9
- */
10
- export declare function createStatefulReduceTools(loader: ChunkLoader, config: StatefulReducerConfig): {
11
- statefulReduceProcessChunk: (args: any, context: any) => Promise<{
12
- role: string;
13
- name: string;
14
- content: string;
15
- }>;
16
- toolStatefulReduceProcessChunk: Tool;
17
- };
18
- /**
19
- * Legacy function name for backward compatibility
20
- * @deprecated Use createStatefulReduceTools instead
21
- */
22
- export declare function createAgentReduceTools(loader: ChunkLoader, config: any): {
23
- statefulReduceProcessChunk: (args: any, context: any) => Promise<{
24
- role: string;
25
- name: string;
26
- content: string;
27
- }>;
28
- toolStatefulReduceProcessChunk: Tool;
29
- };
@@ -1,157 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createStatefulReduceTools = createStatefulReduceTools;
4
- exports.createAgentReduceTools = createAgentReduceTools;
5
- const reducer_core_1 = require("./reducer.core");
6
- /**
7
- * Creates the tool definition for stateful agent reduce content processing
8
- */
9
- const createStatefulReduceTool = () => ({
10
- type: "function",
11
- function: {
12
- strict: true,
13
- name: "statefulReduceProcessChunk",
14
- description: `
15
- This tool processes large content with a STATEFUL reducer pattern using digest replacement.
16
-
17
- ## Core Principles (STATEFUL)
18
- 1. Each call processes ONE chunk and updates internal digest state
19
- 2. First chunk: creates initial digest
20
- 3. Subsequent chunks: digest + reduce → REPLACES previous digest (no accumulation)
21
- 4. Continue calling until you receive "eof": true
22
- 5. System prompt is dynamically updated with current digest
23
-
24
- ## Parameters
25
- - **sessionId** *(string)* - Session ID for the discussion/document to process
26
- - **template** *(string)* - Processing template to apply
27
- - **position** *(number)* - Byte offset to resume reading (0 for first call)
28
-
29
- ## Workflow (Stateful)
30
- 1. Load chunk from position
31
- 2. If first chunk: digest → update system prompt
32
- 3. If subsequent: digest + reduce with current state → REPLACE digest → update system prompt
33
- 4. Return current digest and continue until EOF
34
- `,
35
- parameters: {
36
- type: "object",
37
- properties: {
38
- sessionId: {
39
- type: "string",
40
- description: "Session ID for the discussion/document to process"
41
- },
42
- template: {
43
- type: "string",
44
- description: "Processing template to apply",
45
- enum: ["facts", "compress", "semantic", "minutes", "custom", "weather", "aliments", "mobilite"]
46
- },
47
- position: {
48
- type: "number",
49
- description: "Current position in the document (0 for first call)"
50
- }
51
- },
52
- required: ["sessionId", "template", "position"],
53
- additionalProperties: false,
54
- }
55
- }
56
- });
57
- /**
58
- * Creates the stateful agent reduce tools with proper configuration
59
- *
60
- * @param loader - ChunkLoader interface for loading content chunks
61
- * @param config - Stateful reducer configuration
62
- * @returns Object containing the tool function and tool definition
63
- */
64
- function createStatefulReduceTools(loader, config) {
65
- const toolStatefulReduceProcessChunk = createStatefulReduceTool();
66
- // Stateful engine instance - maintains state across calls
67
- let engine = null;
68
- /**
69
- * Stateful reduce process chunk tool implementation
70
- */
71
- const statefulReduceProcessChunk = async (args, context) => {
72
- const { sessionId, template, position } = args;
73
- if (!sessionId) {
74
- throw new Error("Session ID is required for stateful reduce processing");
75
- }
76
- // Initialize engine on first call
77
- if (!engine) {
78
- engine = new reducer_core_1.StatefulReducerEngine(config);
79
- engine.setSessionId(sessionId);
80
- if (config.verbose) {
81
- console.log(`🚀 STATEFUL TOOL: Initialized engine for session ${sessionId}`);
82
- }
83
- }
84
- if (config.verbose) {
85
- console.log(`🔄 STATEFUL TOOL: Loading chunk from position ${position} for session ${sessionId}`);
86
- }
87
- // Load the chunk using the external loader
88
- const chunk = await loader.loadNativeChunk(sessionId, position);
89
- if (!chunk || !chunk.content) {
90
- throw new Error("Failed to load content chunk");
91
- }
92
- // Update engine position
93
- engine.updatePosition(chunk.position);
94
- // Check if template exists
95
- if (!config.templates || !config.templates[template]) {
96
- return {
97
- role: "assistant",
98
- name: "statefulReduceProcessChunk",
99
- content: JSON.stringify({
100
- error: `Missing template '${template}'. Available templates: ${Object.keys(config.templates || {}).join(', ')}`,
101
- nextPosition: position,
102
- eof: false,
103
- systemPrompt: engine.getSystemPrompt()
104
- })
105
- };
106
- }
107
- // If this is EOF, return the final result
108
- if (chunk.eof && chunk.content.includes('EOF')) {
109
- engine.setEof(true);
110
- const finalResult = engine.getFinalResult();
111
- return {
112
- role: "assistant",
113
- name: "statefulReduceProcessChunk",
114
- content: JSON.stringify({
115
- finalDigest: finalResult.finalDigest,
116
- nextPosition: chunk.position,
117
- eof: true,
118
- systemPrompt: engine.getSystemPrompt(),
119
- metadata: finalResult.metadata,
120
- instructions: "This is the final result. The document processing is complete."
121
- })
122
- };
123
- }
124
- // Process chunk with stateful engine
125
- const currentDigest = await engine.processChunk(chunk.content);
126
- const state = engine.getState();
127
- // Return current state and instructions for next iteration
128
- return {
129
- role: "assistant",
130
- name: "statefulReduceProcessChunk",
131
- content: JSON.stringify({
132
- currentDigest,
133
- nextPosition: chunk.position,
134
- eof: chunk.eof,
135
- systemPrompt: engine.getSystemPrompt(),
136
- template,
137
- iteration: state.iteration,
138
- chunkCount: state.chunkCount,
139
- instructions: state.iteration === 1
140
- ? `Premier digest créé. Continue avec le chunk suivant.`
141
- : `Digest mis à jour (remplacement). Continue avec le chunk suivant.`
142
- })
143
- };
144
- };
145
- return {
146
- statefulReduceProcessChunk,
147
- toolStatefulReduceProcessChunk
148
- };
149
- }
150
- /**
151
- * Legacy function name for backward compatibility
152
- * @deprecated Use createStatefulReduceTools instead
153
- */
154
- function createAgentReduceTools(loader, config) {
155
- console.warn('createAgentReduceTools is deprecated. Use createStatefulReduceTools instead.');
156
- return createStatefulReduceTools(loader, config);
157
- }
@@ -1,3 +0,0 @@
1
- import { AgentConfig } from "../types";
2
- declare const agents: AgentConfig[];
3
- export default agents;
@@ -1,38 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const execute_1 = require("../execute");
4
- const utils_1 = require("../utils");
5
- const prompts_1 = require("./prompts");
6
- const prompts_2 = require("./prompts");
7
- const prompts_3 = require("./prompts");
8
- // Définition des agents
9
- const haiku = {
10
- name: "haiku",
11
- model: (0, execute_1.modelConfig)("LOW"),
12
- publicDescription: "Agent qui écrit des haïkus.", // Contexte pour l'outil agent_transfer
13
- instructions: prompts_3.haikuPrompt,
14
- tools: [],
15
- };
16
- const morse = {
17
- name: "morse",
18
- model: (0, execute_1.modelConfig)("LOW"),
19
- publicDescription: "Agent qui écrit en morse.", // Contexte pour l'outil agent_transfer
20
- instructions: prompts_2.morsePrompt,
21
- tools: [],
22
- };
23
- const welcome = {
24
- name: "orientation",
25
- human: true,
26
- model: (0, execute_1.modelConfig)("MEDIUM"),
27
- publicDescription: "Agent chargé de l’accueil, de la coordination et de l’orientation. Il redirige les utilisateurs vers l’agent spécialisé approprié",
28
- instructions: prompts_1.welcomePrompt,
29
- tools: [],
30
- downstreamAgents: [haiku, morse],
31
- };
32
- //
33
- // go back to welcome once the task is done
34
- haiku.downstreamAgents = [welcome];
35
- morse.downstreamAgents = [welcome];
36
- // add the transfer tool to point to downstreamAgents
37
- const agents = (0, utils_1.injectTransferTools)([welcome, haiku, morse]);
38
- exports.default = agents;
@@ -1,5 +0,0 @@
1
- import { AgentConfig } from "../types";
2
- export declare const systemReviewPrompt = "\n# PROMPT D\u2019ANALYSE \u2014 Audit de directives LLM d'un prompt syst\u00E8me\n\n## R\u00D4LE :\nAssume le r\u00F4le d\u2019un expert sp\u00E9cialis\u00E9 dans l\u2019analyse, la formalisation et l\u2019\u00E9valuation des directives d\u2019un prompt syst\u00E8me d\u2019un Agent LLM.\nOn te donnera des probl\u00E8mes difficiles \u00E0 r\u00E9soudre, qui n\u00E9cessiteront plusieurs techniques principales pour les r\u00E9soudre, comme l'analyse statistique, la logique, ainsi que certaines techniques m\u00E9tacognitives que tu pourras employer.\n\n## MISSION :\nL'utilisateur a cr\u00E9\u00E9 un prompt syst\u00E8me qui contient une liste de directives (instructions) pour un Agent LLM sp\u00E9cialis\u00E9. \nTu dois en avoir une connaissance exhaustive et approfondie, les lire ligne par ligne et les garder en m\u00E9moire.\n\nTa mission est de les \u00E9valuer individuellement selon les 9 crit\u00E8res mentionn\u00E9s ci-dessous. \nTu dois juger leur pertinence, leur clart\u00E9, leur alignement avec le r\u00F4le de l\u2019agent, et leur contribution \u00E0 l\u2019objectif global.\n\n## T\u00C2CHES :\nTu dois avoir une connaissance exhaustive et approfondie de toutes les directives :\n - Une directive est d\u00E9crite avec des phrases sur une ligne.\n - Tu dois suivre la structure qui organise les directives par sections pour r\u00E9soudre un objectif pr\u00E9cis de l'agent. \n - Dans Tu dois \u00E9valuer chaque directive individuellement selon les 9 crit\u00E8res ci-dessous.\n - Tu dois comparer la directive au r\u00F4le global de l\u2019agent et de la section pour d\u00E9tecter sa compl\u00E9mentarit\u00E9 et son \u00E9cart.\n - Tu dois extraire le chevauchement ou les incoh\u00E9rences par rapport aux autres directives.\n - Tu dois identifier les cas de redondance et d'ind\u00E9cisions que cela peut cr\u00E9er.\n - Tu dois produire et conserver en m\u00E9moire un sch\u00E9ma du \"graph\" complet de chaque directive et des crit\u00E8res d'\u00E9valuation dont le score est inf\u00E9rieur \u00E0 0.9.\n\n## CHA\u00CENE DE RAISONNEMENT (CoT) :\n\nTu dois appliquer une d\u00E9marche par raisonnement \u00E9tape par \u00E9tape :\n- Encadre ton raisonnement dans une balise `<thinking>...</thinking>`.\n- Utilise des balises `<step>` pour chaque \u00E9tape de r\u00E9flexion.\n- Reste succinct dans les \u00E9tapes.\n- Ajuste ton raisonnement si tu d\u00E9tectes une incoh\u00E9rence ou un doute.\n\n\n## CRIT\u00C8RES D\u2019ANALYSE\n\n1. **Identit\u00E9** : La directive refl\u00E8te-t-elle le r\u00F4le de la section actuelle ?\n2. **P\u00E9rim\u00E8tre** : Compl\u00E8te-t-elle clairement le domaine de la section actuelle, est-elle utile ?\n3. **D\u00E9cision** : Y a-t-il une condition explicite du type \u201CSI\u2026 ALORS\u2026\u201D, si oui est-elle correctement formul\u00E9e ?\n4. **Ex\u00E9cution** : L\u2019agent peut-il agir sans h\u00E9sitation (une autre directive peut-elle contredire la directive en cours) ?\n5. **Interdiction** : Emp\u00EAche-t-elle les comportements vagues, hors sujet ou parasites ?\n7. **Robustesse** : Faut-il pr\u00E9voir des cas limites ?\n8. **Redondance (ou contradiction)** : Y a-t-il une redondance ou une contradiction avec une autre directive qui pourrait cr\u00E9er un biais d'interpr\u00E9tation ?\n9. **Simplification** : Pourrait-elle \u00EAtre reformul\u00E9e sans perte ?\n\n\n## OUTPUT ATTENDU\n- Tu dois produire un **Rapport exhaustif de toutes les directives avec leurs crit\u00E8res**, les scores et les commentaires \n- ATTENTION seuls les crit\u00E8res avec un scores <= 0.9 int\u00E9ressent l'utilisateur et doivent \u00EAtre affich\u00E9es.\n\n";
3
- export declare const systemReview: AgentConfig;
4
- declare const agents: AgentConfig[];
5
- export default agents;