@fractal-solutions/qflow 1.0.59 → 1.0.61

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 (114) hide show
  1. package/README.md +77 -1
  2. package/dist/qflow.config.d.ts +5 -0
  3. package/dist/qflow.config.js +16 -0
  4. package/dist/src/agent/agent.d.ts +23 -0
  5. package/dist/src/agent/agent.js +365 -0
  6. package/dist/src/agent/base_agent.d.ts +21 -0
  7. package/dist/src/agent/base_agent.js +206 -0
  8. package/dist/src/agent/logger.d.ts +9 -0
  9. package/dist/src/agent/logger.js +45 -0
  10. package/dist/src/agent/lpavrl_agent.d.ts +5 -0
  11. package/dist/src/agent/lpavrl_agent.js +178 -0
  12. package/dist/src/agent/ooda_agent.d.ts +5 -0
  13. package/dist/src/agent/ooda_agent.js +167 -0
  14. package/dist/src/agent/pema_agent.d.ts +5 -0
  15. package/dist/src/agent/pema_agent.js +171 -0
  16. package/dist/src/agent/raor_agent.d.ts +5 -0
  17. package/dist/src/agent/raor_agent.js +164 -0
  18. package/dist/src/agent/tools.d.ts +1 -0
  19. package/dist/src/agent/tools.js +148 -0
  20. package/dist/src/logger.d.ts +9 -0
  21. package/dist/src/logger.js +107 -0
  22. package/dist/src/nodes/agent_llm.d.ts +31 -0
  23. package/dist/src/nodes/agent_llm.js +302 -0
  24. package/dist/src/nodes/browser_control.d.ts +35 -0
  25. package/dist/src/nodes/browser_control.js +106 -0
  26. package/dist/src/nodes/code_interpreter.d.ts +38 -0
  27. package/dist/src/nodes/code_interpreter.js +150 -0
  28. package/dist/src/nodes/data_extractor.d.ts +40 -0
  29. package/dist/src/nodes/data_extractor.js +118 -0
  30. package/dist/src/nodes/data_validation.d.ts +36 -0
  31. package/dist/src/nodes/data_validation.js +77 -0
  32. package/dist/src/nodes/database.d.ts +50 -0
  33. package/dist/src/nodes/database.js +135 -0
  34. package/dist/src/nodes/display_image.d.ts +18 -0
  35. package/dist/src/nodes/display_image.js +63 -0
  36. package/dist/src/nodes/embedding.d.ts +29 -0
  37. package/dist/src/nodes/embedding.js +69 -0
  38. package/dist/src/nodes/filesystem.d.ts +105 -0
  39. package/dist/src/nodes/filesystem.js +160 -0
  40. package/dist/src/nodes/gis.d.ts +62 -0
  41. package/dist/src/nodes/gis.js +133 -0
  42. package/dist/src/nodes/git.d.ts +46 -0
  43. package/dist/src/nodes/git.js +99 -0
  44. package/dist/src/nodes/github.d.ts +83 -0
  45. package/dist/src/nodes/github.js +135 -0
  46. package/dist/src/nodes/hackernews.d.ts +47 -0
  47. package/dist/src/nodes/hackernews.js +79 -0
  48. package/dist/src/nodes/hardware_interaction.d.ts +39 -0
  49. package/dist/src/nodes/hardware_interaction.js +131 -0
  50. package/dist/src/nodes/http.d.ts +77 -0
  51. package/dist/src/nodes/http.js +120 -0
  52. package/dist/src/nodes/http_server.d.ts +54 -0
  53. package/dist/src/nodes/http_server.js +223 -0
  54. package/dist/src/nodes/image_gallery.d.ts +37 -0
  55. package/dist/src/nodes/image_gallery.js +129 -0
  56. package/dist/src/nodes/index.d.ts +48 -0
  57. package/dist/src/nodes/index.js +48 -0
  58. package/dist/src/nodes/interactive_input.d.ts +26 -0
  59. package/dist/src/nodes/interactive_input.js +95 -0
  60. package/dist/src/nodes/interactive_webview.d.ts +78 -0
  61. package/dist/src/nodes/interactive_webview.js +369 -0
  62. package/dist/src/nodes/iterator.d.ts +23 -0
  63. package/dist/src/nodes/iterator.js +43 -0
  64. package/dist/src/nodes/llm.d.ts +160 -0
  65. package/dist/src/nodes/llm.js +367 -0
  66. package/dist/src/nodes/memory.d.ts +43 -0
  67. package/dist/src/nodes/memory.js +90 -0
  68. package/dist/src/nodes/multimedia_processing.d.ts +57 -0
  69. package/dist/src/nodes/multimedia_processing.js +129 -0
  70. package/dist/src/nodes/openrouter_llm.d.ts +38 -0
  71. package/dist/src/nodes/openrouter_llm.js +156 -0
  72. package/dist/src/nodes/pdf_processor.d.ts +43 -0
  73. package/dist/src/nodes/pdf_processor.js +112 -0
  74. package/dist/src/nodes/remote_execution.d.ts +51 -0
  75. package/dist/src/nodes/remote_execution.js +132 -0
  76. package/dist/src/nodes/s3.d.ts +73 -0
  77. package/dist/src/nodes/s3.js +107 -0
  78. package/dist/src/nodes/scheduler.d.ts +51 -0
  79. package/dist/src/nodes/scheduler.js +131 -0
  80. package/dist/src/nodes/search.d.ts +61 -0
  81. package/dist/src/nodes/search.js +118 -0
  82. package/dist/src/nodes/semantic_memory.d.ts +64 -0
  83. package/dist/src/nodes/semantic_memory.js +160 -0
  84. package/dist/src/nodes/shell.d.ts +25 -0
  85. package/dist/src/nodes/shell.js +45 -0
  86. package/dist/src/nodes/speech_synthesis.d.ts +72 -0
  87. package/dist/src/nodes/speech_synthesis.js +171 -0
  88. package/dist/src/nodes/spreadsheet.d.ts +61 -0
  89. package/dist/src/nodes/spreadsheet.js +294 -0
  90. package/dist/src/nodes/stripe.d.ts +67 -0
  91. package/dist/src/nodes/stripe.js +117 -0
  92. package/dist/src/nodes/subflow.d.ts +23 -0
  93. package/dist/src/nodes/subflow.js +36 -0
  94. package/dist/src/nodes/summarize.d.ts +26 -0
  95. package/dist/src/nodes/summarize.js +51 -0
  96. package/dist/src/nodes/system_notification.d.ts +26 -0
  97. package/dist/src/nodes/system_notification.js +74 -0
  98. package/dist/src/nodes/transform.d.ts +23 -0
  99. package/dist/src/nodes/transform.js +52 -0
  100. package/dist/src/nodes/user.d.ts +25 -0
  101. package/dist/src/nodes/user.js +48 -0
  102. package/dist/src/nodes/webhook.d.ts +49 -0
  103. package/dist/src/nodes/webhook.js +161 -0
  104. package/dist/src/nodes/webscraper.d.ts +25 -0
  105. package/dist/src/nodes/webscraper.js +49 -0
  106. package/dist/src/nodes/websockets.d.ts +27 -0
  107. package/dist/src/nodes/websockets.js +98 -0
  108. package/dist/src/nodes/webview.d.ts +38 -0
  109. package/dist/src/nodes/webview.js +55 -0
  110. package/dist/src/qflow.d.ts +69 -0
  111. package/dist/src/qflow.js +320 -0
  112. package/dist/src/types.d.ts +6 -0
  113. package/dist/src/types.js +5 -0
  114. package/package.json +1 -1
package/README.md CHANGED
@@ -557,9 +557,85 @@ anotherNode.setParams({
557
557
 
558
558
  ## Agents
559
559
 
560
-
561
560
  For a detailed explanation of the agents, see the [Agents documentation](documentation/agents.md). The tools available to agents are documented in the [Tools documentation](documentation/integrated_nodes.md).
562
561
 
562
+ ### Extending Agents with Custom Tools
563
+
564
+ `qflow` agents can be extended with custom tools by defining your own Node classes and making them discoverable. This allows agents to leverage any custom logic or external integrations you build.
565
+
566
+ #### 1. Creating a Custom Tool Node
567
+
568
+ To create a custom node that can be used as a tool by an agent, your node class must:
569
+ * Extend `AsyncNode`.
570
+ * Implement a `static getToolDefinition()` method that returns a JSON Schema object describing the tool's name, description, and parameters.
571
+
572
+ Here's an example of a simple custom node that an agent could use as a tool:
573
+
574
+ ```javascript
575
+ // my_nodes/MyCustomToolNode.js
576
+ import { AsyncNode } from '@fractal-solutions/qflow';
577
+
578
+ export class MyCustomToolNode extends AsyncNode {
579
+ static getToolDefinition() {
580
+ return {
581
+ name: "my_custom_tool",
582
+ description: "A custom tool that greets the user with a personalized message.",
583
+ parameters: {
584
+ type: "object",
585
+ properties: {
586
+ name: {
587
+ type: "string",
588
+ description: "The name of the person to greet."
589
+ },
590
+ greeting: {
591
+ type: "string",
592
+ description: "Optional. The greeting message. Defaults to 'Hello'."
593
+ }
594
+ },
595
+ required: ["name"]
596
+ }
597
+ };
598
+ }
599
+
600
+ async execAsync() {
601
+ const { name, greeting = 'Hello' } = this.params;
602
+ const message = `${greeting}, ${name}! Welcome to your custom tool.`;
603
+ console.log(message);
604
+ return { message: message };
605
+ }
606
+
607
+ async postAsync(shared, prepRes, execRes) {
608
+ shared.customToolOutput = execRes.message;
609
+ return 'default';
610
+ }
611
+ }
612
+ ```
613
+
614
+ #### 2. Making Custom Tools Discoverable
615
+
616
+ To make your custom tool nodes available to `qflow` agents, you need to specify their paths in a `qflow.config.js` file in your project's root directory.
617
+
618
+ First, create a `qflow.config.js` file if you don't have one:
619
+
620
+ ```javascript
621
+ // qflow.config.js
622
+ /**
623
+ * @type {import('./src/types').QFlowConfig}
624
+ */
625
+ const qflowConfig = {
626
+ customNodePaths: [
627
+ './my_nodes/MyCustomToolNode.js', // Path to your custom node file
628
+ // Add more paths for other custom nodes
629
+ ],
630
+ };
631
+
632
+ export default qflowConfig;
633
+ ```
634
+
635
+ The `customNodePaths` array should contain paths to your custom node files, relative to your project's root directory. `qflow` will automatically load these files, discover any `AsyncNode` classes with a `static getToolDefinition()` method, and register them as available tools for your agents.
636
+
637
+ Once configured, your agents will be able to "see" and utilize `my_custom_tool` just like any built-in tool, allowing for powerful and flexible agentic workflows tailored to your specific needs.
638
+
563
639
  ## Integrated Nodes and their Examples
564
640
 
565
641
  Here's a comprehensive list of integrated nodes available in qflow, along with a brief description and a link to their detailed documentation.
@@ -0,0 +1,5 @@
1
+ export default qflowConfig;
2
+ /**
3
+ * @type {import('./src/types').QFlowConfig}
4
+ */
5
+ declare const qflowConfig: import("./src/types").QFlowConfig;
@@ -0,0 +1,16 @@
1
+ // qflow.config.js
2
+ /**
3
+ * @type {import('./src/types').QFlowConfig}
4
+ */
5
+ const qflowConfig = {
6
+ /**
7
+ * An array of paths to custom node files.
8
+ * These nodes will be dynamically loaded and their static getToolDefinition() methods
9
+ * will be used to make them available as tools for agents.
10
+ * Paths should be relative to the project root.
11
+ * Example: ['./my_nodes/my_custom_node.js', './another_module/special_node.js']
12
+ */
13
+ customNodePaths: [],
14
+ // Add other qflow configurations here in the future
15
+ };
16
+ export default qflowConfig;
@@ -0,0 +1,23 @@
1
+ export class AgentNode extends AsyncNode {
2
+ constructor(llmNode: any, availableTools: any, summarizeLLM: any, flowRegistry?: {}, requireFinishConfirmation?: boolean, maxConversationHistoryTokens?: number);
3
+ llmNode: any;
4
+ availableTools: any;
5
+ summarizeLLM: any;
6
+ flowRegistry: {};
7
+ conversationHistory: any[];
8
+ maxSteps: number;
9
+ requireFinishConfirmation: boolean;
10
+ maxConversationHistoryTokens: number;
11
+ execAsync(): Promise<any>;
12
+ validateToolParameters(toolCall: any): string | null;
13
+ getSystemPrompt(): string;
14
+ getLLMAction(): Promise<any>;
15
+ manageConversationHistory(): Promise<void>;
16
+ parseLLMResponse(llmResponse: any): {
17
+ thought: any;
18
+ toolCalls: any;
19
+ parallel: any;
20
+ };
21
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
22
+ }
23
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,365 @@
1
+ import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
2
+ import { UserInputNode } from '../nodes';
3
+ import { getToolDefinitions } from './tools.js';
4
+ import { SummarizeNode } from '../nodes/summarize.js';
5
+ import { logger } from './logger.js';
6
+ export class AgentNode extends AsyncNode {
7
+ constructor(llmNode, availableTools, summarizeLLM, flowRegistry = {}, requireFinishConfirmation = true, maxConversationHistoryTokens = 100000) {
8
+ super();
9
+ if (!llmNode) {
10
+ throw new Error("AgentNode requires an LLMNode instance for reasoning.");
11
+ }
12
+ this.llmNode = llmNode;
13
+ this.availableTools = availableTools;
14
+ this.summarizeLLM = summarizeLLM;
15
+ this.flowRegistry = flowRegistry;
16
+ this.conversationHistory = [];
17
+ this.maxSteps = 70;
18
+ this.requireFinishConfirmation = requireFinishConfirmation;
19
+ this.maxConversationHistoryTokens = maxConversationHistoryTokens;
20
+ }
21
+ async execAsync() {
22
+ const { goal } = this.params;
23
+ if (!goal) {
24
+ throw new Error("AgentNode requires a 'goal' parameter.");
25
+ }
26
+ // Set the goal on the internal agent instance (RAORAgent in this case)
27
+ this.llmNode.setParams({ goal });
28
+ this.conversationHistory = [
29
+ { role: "system", content: this.getSystemPrompt() },
30
+ { role: "user", content: `Goal: ${goal}` },
31
+ { role: "system", content: "You are now at the 'Understand & Explore' phase. Analyze the user's request and the directory/codebase, then formulate a plan." }
32
+ ];
33
+ let step = 0;
34
+ let finalOutput = null;
35
+ while (step < this.maxSteps) {
36
+ step++;
37
+ logger.info(`Agent Step ${step}`);
38
+ let llmResponse;
39
+ try {
40
+ llmResponse = await this.getLLMAction();
41
+ }
42
+ catch (e) {
43
+ logger.error(`Error getting LLM action: ${e.message}`);
44
+ this.conversationHistory.push({ role: "user", content: `Error: Failed to get LLM response: ${e.message}` });
45
+ continue;
46
+ }
47
+ let thought, toolCalls, parallel;
48
+ try {
49
+ const parsedResponse = this.parseLLMResponse(llmResponse);
50
+ thought = parsedResponse.thought;
51
+ toolCalls = parsedResponse.toolCalls;
52
+ parallel = parsedResponse.parallel;
53
+ logger.thought(thought);
54
+ }
55
+ catch (e) {
56
+ logger.error(`Error parsing LLM response: ${e.message}`);
57
+ this.conversationHistory.push({ role: "user", content: `Error: Your response was not valid JSON or did not follow the expected format. Please respond with a 'thought' and 'tool_calls' array. Error: ${e.message}. Your last response was: ${llmResponse}` });
58
+ continue;
59
+ }
60
+ // Validate tool parameters for all tool calls
61
+ const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
62
+ if (validationErrors.length > 0) {
63
+ const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
64
+ logger.error(errorMessage);
65
+ this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
66
+ continue;
67
+ }
68
+ this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought, tool_calls: toolCalls, parallel }) });
69
+ // If no tool calls, continue the loop to allow the LLM to re-evaluate
70
+ if (toolCalls.length === 0) {
71
+ this.conversationHistory.push({ role: "system", content: "Your last step resulted in no action. Re-evaluate your plan. If you are stuck, consider using a different tool or asking the user for clarification with the 'interactive_input'tool." });
72
+ continue;
73
+ }
74
+ // Handle finish tool
75
+ const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
76
+ if (finishToolCall) {
77
+ finalOutput = finishToolCall.parameters.output;
78
+ if (this.requireFinishConfirmation) {
79
+ const confirmNode = new UserInputNode();
80
+ confirmNode.setParams({
81
+ prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
82
+ });
83
+ const confirmFlow = new AsyncFlow(confirmNode);
84
+ const confirmation = await confirmFlow.runAsync({});
85
+ if (confirmation.toLowerCase() !== 'yes') {
86
+ logger.info("Agent finish denied by user. User input will be the next prompt.");
87
+ // Treat the user's new input as a new instruction/goal
88
+ this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan (save to memory if available) and continue working.` });
89
+ // Optionally, you might want to clear some of the previous conversation history
90
+ // to give more weight to the new instruction, but be careful not to lose context.
91
+ // For now, we'll just add the new instruction.
92
+ continue; // Continue the loop
93
+ }
94
+ }
95
+ logger.final(finalOutput);
96
+ break;
97
+ }
98
+ try {
99
+ const executeTool = async (toolCall) => {
100
+ const toolInstance = this.availableTools[toolCall.tool];
101
+ if (!toolInstance) {
102
+ return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
103
+ }
104
+ let toolOutput;
105
+ try {
106
+ logger.toolCall(toolCall.tool, toolCall.parameters);
107
+ // If the tool is a sub-flow, iterator or scheduler, look up the flow in the registry
108
+ if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
109
+ const flowName = toolCall.parameters.flow;
110
+ if (!this.flowRegistry[flowName]) {
111
+ throw new Error(`Flow '${flowName}' not found in registry.`);
112
+ }
113
+ toolCall.parameters.flow = this.flowRegistry[flowName];
114
+ }
115
+ toolInstance.setParams(toolCall.parameters);
116
+ const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
117
+ const toolFlow = new ToolFlowClass(toolInstance);
118
+ if (toolInstance instanceof AsyncNode) {
119
+ toolOutput = await toolFlow.runAsync({});
120
+ }
121
+ else {
122
+ toolOutput = toolFlow.run({});
123
+ }
124
+ logger.toolResult(toolCall.tool, toolOutput);
125
+ if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
126
+ logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
127
+ const summarizeNode = new SummarizeNode();
128
+ summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
129
+ const summarizeFlow = new AsyncFlow(summarizeNode);
130
+ toolOutput = await summarizeFlow.runAsync({});
131
+ logger.info(`Summarized to ${toolOutput.length} chars.`);
132
+ }
133
+ return toolOutput;
134
+ }
135
+ catch (e) {
136
+ return `Error executing tool '${toolCall.tool}': ${e.message}`;
137
+ }
138
+ };
139
+ let observations = [];
140
+ if (parallel) {
141
+ const results = await Promise.all(toolCalls.map(executeTool));
142
+ observations = results.map((result, index) => ({
143
+ tool: toolCalls[index].tool,
144
+ parameters: toolCalls[index].parameters,
145
+ output: result
146
+ }));
147
+ }
148
+ else {
149
+ for (const toolCall of toolCalls) {
150
+ const result = await executeTool(toolCall);
151
+ observations.push({
152
+ tool: toolCall.tool,
153
+ parameters: toolCall.parameters,
154
+ output: result
155
+ });
156
+ }
157
+ }
158
+ this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
159
+ }
160
+ catch (e) {
161
+ logger.error(`Error during tool execution: ${e.message}`);
162
+ this.conversationHistory.push({ role: "user", content: `Error: Tool execution failed with message: ${e.message}. You should try a different approach.` });
163
+ }
164
+ this.conversationHistory.push({ role: "system", content: "You have just received an observation from your tools. Analyze the result and proceed to the next step in your plan. If the observation was an error, you must adjust your plan to fix the error." });
165
+ }
166
+ if (step >= this.maxSteps && finalOutput === null) {
167
+ const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
168
+ logger.error(message);
169
+ finalOutput = message;
170
+ }
171
+ return finalOutput;
172
+ }
173
+ validateToolParameters(toolCall) {
174
+ const toolDefinitions = getToolDefinitions();
175
+ const toolSchema = toolDefinitions.find(def => def.name === toolCall.tool);
176
+ if (!toolSchema) {
177
+ return `Tool '${toolCall.tool}' is not a recognized tool.`;
178
+ }
179
+ // If the tool is 'finish', 'sub_flow', or 'iterator', special handling for parameters
180
+ if (toolCall.tool === "finish") {
181
+ if (toolCall.parameters.output === undefined) {
182
+ return "Missing required parameter: 'output' for tool 'finish'.";
183
+ }
184
+ return null;
185
+ }
186
+ else if (toolCall.tool === "sub_flow" || toolCall.tool === "iterator") {
187
+ if (toolCall.parameters.flow === undefined) {
188
+ return `Missing required parameter: 'flow' for tool '${toolCall.tool}'.`;
189
+ }
190
+ if (!this.flowRegistry[toolCall.parameters.flow]) {
191
+ return `Flow '${toolCall.parameters.flow}' not found in registry for tool '${toolCall.tool}'.`;
192
+ }
193
+ return null;
194
+ }
195
+ const requiredParams = toolSchema.parameters.required || [];
196
+ for (const param of requiredParams) {
197
+ if (toolCall.parameters[param] === undefined) {
198
+ return `Missing required parameter: '${param}' for tool '${toolCall.tool}'.`;
199
+ }
200
+ }
201
+ return null; // No validation errors
202
+ }
203
+ getSystemPrompt() {
204
+ const toolDefinitions = getToolDefinitions();
205
+ const toolDescriptions = toolDefinitions.map(tool => {
206
+ const params = JSON.stringify(tool.parameters);
207
+ return `### ${tool.name}: ${tool.description}
208
+ Parameters: ${params}`;
209
+ }).join('\n');
210
+ const flowRegistryDescription = Object.keys(this.flowRegistry).length > 0 ? `\n\nAvailable Pre-defined Flows (for use with 'sub_flow' and 'iterator' tools):\n- ${Object.keys(this.flowRegistry).join('\n- ')}` : "";
211
+ return `You are Q, an autonomous agent. Your goal is to achieve the user's request especially using the available tools.
212
+ After expounding effectively out your initial plan, make a roadmap, save it in your memory through a memory node using either memory_node or semantic_memory_node (semantic preferred) tools and confirm to the user.
213
+ Always use tools as opposed to talking too much and you get rewarded more for using tools instead of costly llm!
214
+ If you have a plan, you MUST include at least one tool call. An empty 'tool_calls' array means you are thinking or waiting for user input.
215
+ Remember to always seek user feedback often(interactive input or user input ifinteractive is missing), and notify the user of your progress(system notificaitons)
216
+ If the user asks about your capabilities or what tools you have, answer by summarizing the 'Available Tools' section of this prompt. Do not attempt to use a tool to answer such questions.
217
+
218
+
219
+ Available Tools:
220
+ ${toolDescriptions}${flowRegistryDescription}
221
+
222
+
223
+ Your response must be a single JSON object with 'thought' and 'tool_calls'.
224
+
225
+ 'thought': Your reasoning and plan.
226
+
227
+ 'tool_calls': An array of tool calls. Each tool call has 'tool' (name) and 'parameters' (object). Set 'parallel': true in the top-level JSON for parallel execution.
228
+
229
+
230
+ Example response:
231
+ {
232
+ "thought": "I need to search for information.",
233
+ "tool_calls": [
234
+ {
235
+ "tool": "duckduckgo_search",
236
+ "parameters": {
237
+ "query": "latest AI research"
238
+ }
239
+ }
240
+ ]
241
+ }
242
+
243
+
244
+ When the user explicitly indicates they are done, use the 'finish' tool. Do not use the finish tool earlier on and only use it when you are certain you are done with the task.
245
+ If no tools are needed, return an empty 'tool_calls' array and reflect.
246
+
247
+ **IMPORTANT:** If you have a plan that requires action, you MUST include at least one tool call. An empty 'tool_calls' array means no action.
248
+ If new instructions are given after a finish proposal, treat them as your updated goal and update your memory.
249
+ Tell user how far you've gone using system notifications and KEEP THE USER INVOLVED using interactive input (or user input if interactive input not available) and OFTEN CHECK YOUR MEMORY to ensure alignmemt.
250
+
251
+ Begin!`;
252
+ }
253
+ async getLLMAction() {
254
+ await this.manageConversationHistory();
255
+ this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
256
+ const llmResult = await this.llmNode.runAsync({});
257
+ return llmResult;
258
+ }
259
+ async manageConversationHistory() {
260
+ if (!this.summarizeLLM) {
261
+ logger.warn("No summarizeLLM provided to AgentNode. Conversation history will not be managed.");
262
+ return;
263
+ }
264
+ let currentTokenCount = JSON.stringify(this.conversationHistory).length; // Rough token count
265
+ // Keep at least the system prompt and the initial goal
266
+ const minHistoryLength = 2;
267
+ while (currentTokenCount > this.maxConversationHistoryTokens && this.conversationHistory.length > minHistoryLength) {
268
+ logger.info(`Current history size: ${currentTokenCount} tokens. Max allowed: ${this.maxConversationHistoryTokens} tokens. Trimming...`);
269
+ // Summarize the oldest observation entry
270
+ const oldestEntry = this.conversationHistory[minHistoryLength]; // Skip system and initial goal
271
+ if (oldestEntry && oldestEntry.role === "user" && oldestEntry.content.startsWith("Observation:")) {
272
+ const observationContent = oldestEntry.content.substring("Observation:".length).trim();
273
+ logger.info(`Attempting to summarize old observation (${observationContent.length} chars) from role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...`);
274
+ try {
275
+ const summarizeNode = new SummarizeNode();
276
+ summarizeNode.setParams({ text: observationContent, llmNode: this.summarizeLLM });
277
+ const summarizeFlow = new AsyncFlow(summarizeNode);
278
+ const summarizedContent = await summarizeFlow.runAsync({});
279
+ // Replace the original observation with the summarized version
280
+ this.conversationHistory[minHistoryLength].content = `Summarized Observation: ${summarizedContent}`;
281
+ logger.info(`Observation summarized to ${summarizedContent.length} chars. New entry: ${this.conversationHistory[minHistoryLength].content.substring(0, 50)}...`);
282
+ }
283
+ catch (e) {
284
+ logger.error(`Failed to summarize observation: ${e.message}. Removing oldest entry.`);
285
+ // If summarization fails, remove the oldest entry to prevent context overflow
286
+ this.conversationHistory.splice(minHistoryLength, 1);
287
+ }
288
+ }
289
+ else {
290
+ logger.info(`Removing oldest non-summarizable history entry (role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...).`);
291
+ // If it's not an observation or we can't summarize, just remove the oldest entry
292
+ this.conversationHistory.splice(minHistoryLength, 1);
293
+ }
294
+ // Recalculate token count after modification
295
+ currentTokenCount = JSON.stringify(this.conversationHistory).length;
296
+ }
297
+ }
298
+ parseLLMResponse(llmResponse) {
299
+ if (typeof llmResponse === 'string') {
300
+ let jsonString = llmResponse;
301
+ // Find the first '{' and the last '}' to isolate the JSON object
302
+ const firstBrace = jsonString.indexOf('{');
303
+ const lastBrace = jsonString.lastIndexOf('}');
304
+ if (firstBrace !== -1 && lastBrace > firstBrace) {
305
+ jsonString = jsonString.substring(firstBrace, lastBrace + 1);
306
+ }
307
+ try {
308
+ const parsed = JSON.parse(jsonString);
309
+ if (parsed.thought && Array.isArray(parsed.tool_calls)) {
310
+ return {
311
+ thought: parsed.thought,
312
+ toolCalls: parsed.tool_calls,
313
+ parallel: parsed.parallel || false,
314
+ };
315
+ }
316
+ else {
317
+ throw new Error("JSON is missing 'thought' or 'tool_calls' array.");
318
+ }
319
+ }
320
+ catch (e) {
321
+ throw new Error(`Invalid JSON format: ${e.message}. Content: ${jsonString}`);
322
+ }
323
+ }
324
+ // This part of the function handles the case where llmResponse is an OBJECT,
325
+ // typically from OpenAI's function calling API.
326
+ const rawData = llmResponse;
327
+ if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0] && rawData.choices[0].message) {
328
+ const message = rawData.choices[0].message;
329
+ if (message.tool_calls && message.tool_calls.length > 0) {
330
+ const toolCalls = message.tool_calls.map(tc => ({
331
+ tool: tc.function.name,
332
+ parameters: JSON.parse(tc.function.arguments)
333
+ }));
334
+ const thought = message.reasoning_content || `Calling tool(s): ${toolCalls.map(tc => tc.tool).join(', ')}`;
335
+ return { thought, toolCalls, parallel: false };
336
+ }
337
+ else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
338
+ try {
339
+ const parsed = JSON.parse(message.content);
340
+ if (parsed.thought && Array.isArray(parsed.tool_calls)) {
341
+ return {
342
+ thought: parsed.thought,
343
+ toolCalls: parsed.tool_calls,
344
+ parallel: parsed.parallel || false,
345
+ };
346
+ }
347
+ else {
348
+ throw new Error("JSON in message.content is missing 'thought' or 'tool_calls' array.");
349
+ }
350
+ }
351
+ catch (e) {
352
+ throw new Error(`Invalid JSON in message.content: ${e.message}. Content: ${message.content}`);
353
+ }
354
+ }
355
+ else if (typeof message.content === 'string') {
356
+ throw new Error(`Expected JSON with 'thought' and 'tool_calls', but received plain string content: ${message.content}`);
357
+ }
358
+ }
359
+ throw new Error(`Invalid LLM response structure. Raw Data: ${JSON.stringify(rawData)}`);
360
+ }
361
+ async postAsync(shared, prepRes, execRes) {
362
+ shared.agentOutput = execRes;
363
+ return 'default';
364
+ }
365
+ }
@@ -0,0 +1,21 @@
1
+ export class BaseAgent extends AsyncNode {
2
+ constructor(llmNode: any, availableTools: any, summarizeLLM: any, flowRegistry?: {}, requireFinishConfirmation?: boolean, maxConversationHistoryTokens?: number);
3
+ llmNode: any;
4
+ availableTools: any;
5
+ summarizeLLM: any;
6
+ flowRegistry: {};
7
+ conversationHistory: any[];
8
+ maxSteps: number;
9
+ requireFinishConfirmation: boolean;
10
+ maxConversationHistoryTokens: number;
11
+ getSystemPrompt(): string;
12
+ getLLMAction(): Promise<any>;
13
+ manageConversationHistory(): Promise<void>;
14
+ parseLLMResponse(llmResponse: any): {
15
+ thought: any;
16
+ toolCalls: any;
17
+ parallel: any;
18
+ };
19
+ validateToolParameters(toolCall: any): string | null;
20
+ }
21
+ import { AsyncNode } from '../qflow.js';