@fractal-solutions/qflow 1.0.62 → 1.0.64

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 (199) hide show
  1. package/dist/agent/tools.d.ts +1 -5378
  2. package/dist/agent/tools.js +145 -1171
  3. package/dist/nodes/browser_control.d.ts +31 -0
  4. package/dist/nodes/browser_control.js +33 -0
  5. package/dist/nodes/code_interpreter.d.ts +29 -0
  6. package/dist/nodes/code_interpreter.js +29 -0
  7. package/dist/nodes/data_extractor.d.ts +35 -0
  8. package/dist/nodes/data_extractor.js +37 -0
  9. package/dist/nodes/data_validation.d.ts +27 -0
  10. package/dist/nodes/data_validation.js +29 -0
  11. package/dist/nodes/database.d.ts +44 -0
  12. package/dist/nodes/database.js +46 -0
  13. package/dist/nodes/display_image.d.ts +14 -0
  14. package/dist/nodes/display_image.js +16 -0
  15. package/dist/nodes/embedding.d.ts +22 -0
  16. package/dist/nodes/embedding.js +24 -0
  17. package/dist/nodes/filesystem.d.ts +64 -0
  18. package/dist/nodes/filesystem.js +72 -0
  19. package/dist/nodes/gis.d.ts +25 -0
  20. package/dist/nodes/gis.js +27 -0
  21. package/dist/nodes/git.d.ts +42 -0
  22. package/dist/nodes/git.js +44 -0
  23. package/dist/nodes/github.d.ts +56 -0
  24. package/dist/nodes/github.js +60 -0
  25. package/dist/nodes/hackernews.d.ts +28 -0
  26. package/dist/nodes/hackernews.js +32 -0
  27. package/dist/nodes/hardware_interaction.d.ts +31 -0
  28. package/dist/nodes/hardware_interaction.js +33 -0
  29. package/dist/nodes/http.d.ts +51 -0
  30. package/dist/nodes/http.js +53 -0
  31. package/dist/nodes/http_server.d.ts +37 -0
  32. package/dist/nodes/http_server.js +33 -0
  33. package/dist/nodes/image_gallery.d.ts +29 -0
  34. package/dist/nodes/image_gallery.js +29 -0
  35. package/dist/nodes/interactive_input.d.ts +22 -0
  36. package/dist/nodes/interactive_input.js +24 -0
  37. package/dist/nodes/interactive_webview.d.ts +59 -0
  38. package/dist/nodes/interactive_webview.js +59 -0
  39. package/dist/nodes/iterator.d.ts +18 -0
  40. package/dist/nodes/iterator.js +20 -0
  41. package/dist/nodes/llm.d.ts +142 -0
  42. package/dist/nodes/llm.js +152 -0
  43. package/dist/nodes/memory.d.ts +31 -0
  44. package/dist/nodes/memory.js +80 -38
  45. package/dist/nodes/multimedia_processing.d.ts +47 -0
  46. package/dist/nodes/multimedia_processing.js +49 -0
  47. package/dist/nodes/openrouter_llm.d.ts +30 -0
  48. package/dist/nodes/openrouter_llm.js +32 -0
  49. package/dist/nodes/pdf_processor.d.ts +39 -0
  50. package/dist/nodes/pdf_processor.js +37 -0
  51. package/dist/nodes/remote_execution.d.ts +47 -0
  52. package/dist/nodes/remote_execution.js +49 -0
  53. package/dist/nodes/s3.d.ts +67 -0
  54. package/dist/nodes/s3.js +69 -0
  55. package/dist/nodes/scheduler.d.ts +31 -0
  56. package/dist/nodes/scheduler.js +33 -0
  57. package/dist/nodes/search.d.ts +36 -0
  58. package/dist/nodes/search.js +40 -0
  59. package/dist/nodes/semantic_memory.d.ts +47 -0
  60. package/dist/nodes/semantic_memory.js +49 -0
  61. package/dist/nodes/shell.d.ts +14 -0
  62. package/dist/nodes/shell.js +16 -0
  63. package/dist/nodes/speech_synthesis.d.ts +27 -0
  64. package/dist/nodes/speech_synthesis.js +29 -0
  65. package/dist/nodes/spreadsheet.d.ts +51 -0
  66. package/dist/nodes/spreadsheet.js +53 -0
  67. package/dist/nodes/stripe.d.ts +44 -0
  68. package/dist/nodes/stripe.js +48 -0
  69. package/dist/nodes/subflow.d.ts +18 -0
  70. package/dist/nodes/subflow.js +20 -0
  71. package/dist/nodes/summarize.d.ts +14 -0
  72. package/dist/nodes/summarize.js +20 -0
  73. package/dist/nodes/system_notification.d.ts +22 -0
  74. package/dist/nodes/system_notification.js +24 -0
  75. package/dist/nodes/transform.d.ts +18 -0
  76. package/dist/nodes/transform.js +20 -0
  77. package/dist/nodes/user.d.ts +14 -0
  78. package/dist/nodes/user.js +16 -0
  79. package/dist/nodes/webhook.d.ts +34 -0
  80. package/dist/nodes/webhook.js +36 -0
  81. package/dist/nodes/webscraper.d.ts +14 -0
  82. package/dist/nodes/webscraper.js +16 -0
  83. package/dist/nodes/websockets.d.ts +23 -0
  84. package/dist/nodes/websockets.js +25 -0
  85. package/dist/nodes/webview.d.ts +26 -0
  86. package/dist/nodes/webview.js +28 -0
  87. package/package.json +3 -2
  88. package/dist/qflow.config.d.ts +0 -5
  89. package/dist/qflow.config.js +0 -16
  90. package/dist/src/agent/agent.d.ts +0 -23
  91. package/dist/src/agent/agent.js +0 -365
  92. package/dist/src/agent/base_agent.d.ts +0 -21
  93. package/dist/src/agent/base_agent.js +0 -206
  94. package/dist/src/agent/logger.d.ts +0 -9
  95. package/dist/src/agent/logger.js +0 -45
  96. package/dist/src/agent/lpavrl_agent.d.ts +0 -5
  97. package/dist/src/agent/lpavrl_agent.js +0 -178
  98. package/dist/src/agent/ooda_agent.d.ts +0 -5
  99. package/dist/src/agent/ooda_agent.js +0 -167
  100. package/dist/src/agent/pema_agent.d.ts +0 -5
  101. package/dist/src/agent/pema_agent.js +0 -171
  102. package/dist/src/agent/raor_agent.d.ts +0 -5
  103. package/dist/src/agent/raor_agent.js +0 -164
  104. package/dist/src/agent/tools.d.ts +0 -1
  105. package/dist/src/agent/tools.js +0 -148
  106. package/dist/src/logger.d.ts +0 -9
  107. package/dist/src/logger.js +0 -107
  108. package/dist/src/nodes/agent_llm.d.ts +0 -31
  109. package/dist/src/nodes/agent_llm.js +0 -302
  110. package/dist/src/nodes/browser_control.d.ts +0 -35
  111. package/dist/src/nodes/browser_control.js +0 -106
  112. package/dist/src/nodes/code_interpreter.d.ts +0 -38
  113. package/dist/src/nodes/code_interpreter.js +0 -150
  114. package/dist/src/nodes/data_extractor.d.ts +0 -40
  115. package/dist/src/nodes/data_extractor.js +0 -118
  116. package/dist/src/nodes/data_validation.d.ts +0 -36
  117. package/dist/src/nodes/data_validation.js +0 -77
  118. package/dist/src/nodes/database.d.ts +0 -50
  119. package/dist/src/nodes/database.js +0 -135
  120. package/dist/src/nodes/display_image.d.ts +0 -18
  121. package/dist/src/nodes/display_image.js +0 -63
  122. package/dist/src/nodes/embedding.d.ts +0 -29
  123. package/dist/src/nodes/embedding.js +0 -69
  124. package/dist/src/nodes/filesystem.d.ts +0 -105
  125. package/dist/src/nodes/filesystem.js +0 -160
  126. package/dist/src/nodes/gis.d.ts +0 -62
  127. package/dist/src/nodes/gis.js +0 -133
  128. package/dist/src/nodes/git.d.ts +0 -46
  129. package/dist/src/nodes/git.js +0 -99
  130. package/dist/src/nodes/github.d.ts +0 -83
  131. package/dist/src/nodes/github.js +0 -135
  132. package/dist/src/nodes/hackernews.d.ts +0 -47
  133. package/dist/src/nodes/hackernews.js +0 -79
  134. package/dist/src/nodes/hardware_interaction.d.ts +0 -39
  135. package/dist/src/nodes/hardware_interaction.js +0 -131
  136. package/dist/src/nodes/http.d.ts +0 -77
  137. package/dist/src/nodes/http.js +0 -120
  138. package/dist/src/nodes/http_server.d.ts +0 -54
  139. package/dist/src/nodes/http_server.js +0 -223
  140. package/dist/src/nodes/image_gallery.d.ts +0 -37
  141. package/dist/src/nodes/image_gallery.js +0 -129
  142. package/dist/src/nodes/index.d.ts +0 -48
  143. package/dist/src/nodes/index.js +0 -48
  144. package/dist/src/nodes/interactive_input.d.ts +0 -26
  145. package/dist/src/nodes/interactive_input.js +0 -95
  146. package/dist/src/nodes/interactive_webview.d.ts +0 -78
  147. package/dist/src/nodes/interactive_webview.js +0 -369
  148. package/dist/src/nodes/iterator.d.ts +0 -23
  149. package/dist/src/nodes/iterator.js +0 -43
  150. package/dist/src/nodes/llm.d.ts +0 -160
  151. package/dist/src/nodes/llm.js +0 -367
  152. package/dist/src/nodes/memory.d.ts +0 -43
  153. package/dist/src/nodes/memory.js +0 -90
  154. package/dist/src/nodes/multimedia_processing.d.ts +0 -57
  155. package/dist/src/nodes/multimedia_processing.js +0 -129
  156. package/dist/src/nodes/openrouter_llm.d.ts +0 -38
  157. package/dist/src/nodes/openrouter_llm.js +0 -156
  158. package/dist/src/nodes/pdf_processor.d.ts +0 -43
  159. package/dist/src/nodes/pdf_processor.js +0 -112
  160. package/dist/src/nodes/remote_execution.d.ts +0 -51
  161. package/dist/src/nodes/remote_execution.js +0 -132
  162. package/dist/src/nodes/s3.d.ts +0 -73
  163. package/dist/src/nodes/s3.js +0 -107
  164. package/dist/src/nodes/scheduler.d.ts +0 -51
  165. package/dist/src/nodes/scheduler.js +0 -131
  166. package/dist/src/nodes/search.d.ts +0 -61
  167. package/dist/src/nodes/search.js +0 -118
  168. package/dist/src/nodes/semantic_memory.d.ts +0 -64
  169. package/dist/src/nodes/semantic_memory.js +0 -160
  170. package/dist/src/nodes/shell.d.ts +0 -25
  171. package/dist/src/nodes/shell.js +0 -45
  172. package/dist/src/nodes/speech_synthesis.d.ts +0 -72
  173. package/dist/src/nodes/speech_synthesis.js +0 -171
  174. package/dist/src/nodes/spreadsheet.d.ts +0 -61
  175. package/dist/src/nodes/spreadsheet.js +0 -294
  176. package/dist/src/nodes/stripe.d.ts +0 -67
  177. package/dist/src/nodes/stripe.js +0 -117
  178. package/dist/src/nodes/subflow.d.ts +0 -23
  179. package/dist/src/nodes/subflow.js +0 -36
  180. package/dist/src/nodes/summarize.d.ts +0 -26
  181. package/dist/src/nodes/summarize.js +0 -51
  182. package/dist/src/nodes/system_notification.d.ts +0 -26
  183. package/dist/src/nodes/system_notification.js +0 -74
  184. package/dist/src/nodes/transform.d.ts +0 -23
  185. package/dist/src/nodes/transform.js +0 -52
  186. package/dist/src/nodes/user.d.ts +0 -25
  187. package/dist/src/nodes/user.js +0 -48
  188. package/dist/src/nodes/webhook.d.ts +0 -49
  189. package/dist/src/nodes/webhook.js +0 -161
  190. package/dist/src/nodes/webscraper.d.ts +0 -25
  191. package/dist/src/nodes/webscraper.js +0 -49
  192. package/dist/src/nodes/websockets.d.ts +0 -27
  193. package/dist/src/nodes/websockets.js +0 -98
  194. package/dist/src/nodes/webview.d.ts +0 -38
  195. package/dist/src/nodes/webview.js +0 -55
  196. package/dist/src/qflow.d.ts +0 -69
  197. package/dist/src/qflow.js +0 -320
  198. /package/dist/{src/types.d.ts → types.d.ts} +0 -0
  199. /package/dist/{src/types.js → types.js} +0 -0
@@ -10,6 +10,34 @@ import { log } from '../logger.js';
10
10
  * @param {number} [params.height=600] - The height of the webview window.
11
11
  */
12
12
  export class WebviewNode extends AsyncNode {
13
+ static getToolDefinition() {
14
+ return {
15
+ name: "webview",
16
+ description: "Displays a webview window with custom HTML content.",
17
+ parameters: {
18
+ type: "object",
19
+ properties: {
20
+ html: {
21
+ type: "string",
22
+ description: "The HTML content to display in the webview."
23
+ },
24
+ title: {
25
+ type: "string",
26
+ description: "Optional. The title of the webview window. Defaults to 'Qflow Webview'."
27
+ },
28
+ width: {
29
+ type: "number",
30
+ description: "Optional. The width of the webview window. Defaults to 800."
31
+ },
32
+ height: {
33
+ type: "number",
34
+ description: "Optional. The height of the webview window. Defaults to 600."
35
+ }
36
+ },
37
+ required: ["html"]
38
+ }
39
+ };
40
+ }
13
41
  async execAsync() {
14
42
  const { html, title = 'Qflow Webview', width = 800, height = 600 } = this.params;
15
43
  if (!html) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.62",
3
+ "version": "1.0.64",
4
4
  "description": "A lightweight and flexible JavaScript library for creating and managing workflows and agents.",
5
5
  "main": "dist/qflow.js",
6
6
  "types": "dist/qflow.d.ts",
@@ -20,7 +20,8 @@
20
20
  ],
21
21
  "scripts": {
22
22
  "test": "bun test",
23
- "build": "tsc --project tsconfig.build.json",
23
+ "clean": "rm -rf dist",
24
+ "build": "bun run clean && tsc --project tsconfig.build.json",
24
25
  "postinstall": "bun scripts/postinstall.js"
25
26
  },
26
27
  "keywords": [
@@ -1,5 +0,0 @@
1
- export default qflowConfig;
2
- /**
3
- * @type {import('./src/types').QFlowConfig}
4
- */
5
- declare const qflowConfig: import("./src/types").QFlowConfig;
@@ -1,16 +0,0 @@
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;
@@ -1,23 +0,0 @@
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';
@@ -1,365 +0,0 @@
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
- }
@@ -1,21 +0,0 @@
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';