@fractal-solutions/qflow 1.0.61 → 1.0.63

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 (110) hide show
  1. package/README.md +75 -74
  2. package/package.json +1 -1
  3. package/dist/agent/agent.d.ts +0 -23
  4. package/dist/agent/agent.js +0 -365
  5. package/dist/agent/base_agent.d.ts +0 -21
  6. package/dist/agent/base_agent.js +0 -206
  7. package/dist/agent/logger.d.ts +0 -9
  8. package/dist/agent/logger.js +0 -45
  9. package/dist/agent/lpavrl_agent.d.ts +0 -5
  10. package/dist/agent/lpavrl_agent.js +0 -178
  11. package/dist/agent/ooda_agent.d.ts +0 -5
  12. package/dist/agent/ooda_agent.js +0 -167
  13. package/dist/agent/pema_agent.d.ts +0 -5
  14. package/dist/agent/pema_agent.js +0 -171
  15. package/dist/agent/raor_agent.d.ts +0 -5
  16. package/dist/agent/raor_agent.js +0 -164
  17. package/dist/agent/tools.d.ts +0 -5378
  18. package/dist/agent/tools.js +0 -1174
  19. package/dist/logger.d.ts +0 -9
  20. package/dist/logger.js +0 -107
  21. package/dist/nodes/agent_llm.d.ts +0 -31
  22. package/dist/nodes/agent_llm.js +0 -302
  23. package/dist/nodes/browser_control.d.ts +0 -4
  24. package/dist/nodes/browser_control.js +0 -73
  25. package/dist/nodes/code_interpreter.d.ts +0 -9
  26. package/dist/nodes/code_interpreter.js +0 -121
  27. package/dist/nodes/data_extractor.d.ts +0 -5
  28. package/dist/nodes/data_extractor.js +0 -81
  29. package/dist/nodes/data_validation.d.ts +0 -9
  30. package/dist/nodes/data_validation.js +0 -48
  31. package/dist/nodes/database.d.ts +0 -6
  32. package/dist/nodes/database.js +0 -89
  33. package/dist/nodes/display_image.d.ts +0 -4
  34. package/dist/nodes/display_image.js +0 -47
  35. package/dist/nodes/embedding.d.ts +0 -7
  36. package/dist/nodes/embedding.js +0 -45
  37. package/dist/nodes/filesystem.d.ts +0 -41
  38. package/dist/nodes/filesystem.js +0 -88
  39. package/dist/nodes/gis.d.ts +0 -37
  40. package/dist/nodes/gis.js +0 -106
  41. package/dist/nodes/git.d.ts +0 -4
  42. package/dist/nodes/git.js +0 -55
  43. package/dist/nodes/github.d.ts +0 -27
  44. package/dist/nodes/github.js +0 -75
  45. package/dist/nodes/hackernews.d.ts +0 -19
  46. package/dist/nodes/hackernews.js +0 -47
  47. package/dist/nodes/hardware_interaction.d.ts +0 -8
  48. package/dist/nodes/hardware_interaction.js +0 -98
  49. package/dist/nodes/http.d.ts +0 -26
  50. package/dist/nodes/http.js +0 -67
  51. package/dist/nodes/http_server.d.ts +0 -17
  52. package/dist/nodes/http_server.js +0 -190
  53. package/dist/nodes/image_gallery.d.ts +0 -8
  54. package/dist/nodes/image_gallery.js +0 -100
  55. package/dist/nodes/index.d.ts +0 -48
  56. package/dist/nodes/index.js +0 -48
  57. package/dist/nodes/interactive_input.d.ts +0 -4
  58. package/dist/nodes/interactive_input.js +0 -71
  59. package/dist/nodes/interactive_webview.d.ts +0 -19
  60. package/dist/nodes/interactive_webview.js +0 -310
  61. package/dist/nodes/iterator.d.ts +0 -5
  62. package/dist/nodes/iterator.js +0 -23
  63. package/dist/nodes/llm.d.ts +0 -18
  64. package/dist/nodes/llm.js +0 -215
  65. package/dist/nodes/memory.d.ts +0 -12
  66. package/dist/nodes/memory.js +0 -48
  67. package/dist/nodes/multimedia_processing.d.ts +0 -10
  68. package/dist/nodes/multimedia_processing.js +0 -80
  69. package/dist/nodes/openrouter_llm.d.ts +0 -8
  70. package/dist/nodes/openrouter_llm.js +0 -124
  71. package/dist/nodes/pdf_processor.d.ts +0 -4
  72. package/dist/nodes/pdf_processor.js +0 -75
  73. package/dist/nodes/remote_execution.d.ts +0 -4
  74. package/dist/nodes/remote_execution.js +0 -83
  75. package/dist/nodes/s3.d.ts +0 -6
  76. package/dist/nodes/s3.js +0 -38
  77. package/dist/nodes/scheduler.d.ts +0 -20
  78. package/dist/nodes/scheduler.js +0 -98
  79. package/dist/nodes/search.d.ts +0 -25
  80. package/dist/nodes/search.js +0 -78
  81. package/dist/nodes/semantic_memory.d.ts +0 -17
  82. package/dist/nodes/semantic_memory.js +0 -111
  83. package/dist/nodes/shell.d.ts +0 -11
  84. package/dist/nodes/shell.js +0 -29
  85. package/dist/nodes/speech_synthesis.d.ts +0 -45
  86. package/dist/nodes/speech_synthesis.js +0 -142
  87. package/dist/nodes/spreadsheet.d.ts +0 -10
  88. package/dist/nodes/spreadsheet.js +0 -241
  89. package/dist/nodes/stripe.d.ts +0 -23
  90. package/dist/nodes/stripe.js +0 -69
  91. package/dist/nodes/subflow.d.ts +0 -5
  92. package/dist/nodes/subflow.js +0 -16
  93. package/dist/nodes/summarize.d.ts +0 -12
  94. package/dist/nodes/summarize.js +0 -31
  95. package/dist/nodes/system_notification.d.ts +0 -4
  96. package/dist/nodes/system_notification.js +0 -50
  97. package/dist/nodes/transform.d.ts +0 -5
  98. package/dist/nodes/transform.js +0 -32
  99. package/dist/nodes/user.d.ts +0 -11
  100. package/dist/nodes/user.js +0 -32
  101. package/dist/nodes/webhook.d.ts +0 -15
  102. package/dist/nodes/webhook.js +0 -125
  103. package/dist/nodes/webscraper.d.ts +0 -11
  104. package/dist/nodes/webscraper.js +0 -33
  105. package/dist/nodes/websockets.d.ts +0 -4
  106. package/dist/nodes/websockets.js +0 -73
  107. package/dist/nodes/webview.d.ts +0 -12
  108. package/dist/nodes/webview.js +0 -27
  109. package/dist/qflow.d.ts +0 -69
  110. package/dist/qflow.js +0 -320
package/README.md CHANGED
@@ -262,6 +262,81 @@ This example demonstrates how to generate data within a qflow, create dynamic HT
262
262
 
263
263
  See [examples/webview_data_visualization.js](examples/webview_data_visualization.js) for the full example.
264
264
 
265
+
266
+
267
+ ## Integrated Nodes and their Examples
268
+
269
+ Here's a comprehensive list of integrated nodes available in qflow, along with a brief description and a link to their detailed documentation.
270
+
271
+ ### Data
272
+
273
+ * **[CodeInterpreterNode](documentation/nodes/code_interpreter.md)**: Executes Python code snippets.
274
+ * **[DataExtractorNode](documentation/nodes/data_extractor.md)**: Extracts structured data from HTML, JSON, or plain text.
275
+ * **[DatabaseNode](documentation/nodes/database.md)**: Provides a powerful and flexible way to interact with SQL databases.
276
+ * **[EmbeddingNode](documentation/nodes/embedding.md)**: Generates vector embeddings for text (requires Ollama).
277
+ * **[MemoryNode](documentation/nodes/memory.md)**: Stores and retrieves text memories (keyword-based).
278
+ * **[SemanticMemoryNode](documentation/nodes/semantic_memory.md)**: Stores and retrieves text memories via semantic search (requires Ollama).
279
+ * **[TransformNode](documentation/nodes/transform.md)**: Transforms input data using a provided JavaScript function.
280
+ * **[PDFProcessorNode](documentation/nodes/pdf_processor.md)**: Extracts text or images from PDF documents.
281
+ * **[SpreadsheetNode](documentation/nodes/spreadsheet.md)**: Reads from and writes to spreadsheet files (.xlsx, .xls, .csv) with advanced manipulation.
282
+ * **[DataValidationNode](documentation/nodes/data_validation.md)**: Validates structured data against a JSON Schema.
283
+
284
+ ### System
285
+
286
+ * **[ShellCommandNode](documentation/nodes/shell_command.md)**: Executes shell commands.
287
+ * **[ReadFileNode](documentation/nodes/read_file.md)**: Reads the content of a specified file.
288
+ * **[WriteFileNode](documentation/nodes/write_file.md)**: Writes content to a specified file.
289
+ * **[AppendFileNode](documentation/nodes/append_file.md)**: Appends content to an existing file.
290
+ * **[ListDirectoryNode](documentation/nodes/list_directory.md)**: Lists the files and subdirectories within a specified directory.
291
+ * **[SystemNotificationNode](documentation/nodes/system_notification.md)**: Displays a system-level notification across OSs.
292
+ * **[DisplayImageNode](documentation/nodes/display_image.md)**: Displays an image file using the system's default image viewer.
293
+ * **[HardwareInteractionNode](documentation/nodes/hardware_interaction.md)**: Communicates with local hardware via serial port (UART).
294
+ * **[ImageGalleryNode](documentation/nodes/image_gallery.md)**: Generates an HTML gallery from multiple image files and opens it in a web browser.
295
+ * **[SpeechSynthesisNode](documentation/nodes/speech_synthesis.md)**: Converts text to spoken audio using OS capabilities or cloud APIs.
296
+ * **[MultimediaProcessingNode](documentation/nodes/multimedia_processing.md)**: Performs various multimedia operations on audio and video files using ffmpeg.
297
+ * **[RemoteExecutionNode](documentation/nodes/remote_execution.md)**: Executes commands on remote machines via SSH.
298
+
299
+ ### Web
300
+
301
+ * **[HttpRequestNode](documentation/nodes/http_request.md)**: Makes a generic HTTP request to any URL.
302
+ * **[WebScraperNode](documentation/nodes/web_scraper.md)**: Fetches the HTML content of a given URL.
303
+ * **[DuckDuckGoSearchNode](documentation/nodes/duckduckgo_search.md)**: Performs a web search using DuckDuckGo.
304
+ * **[GoogleSearchNode](documentation/nodes/google_search.md)**: Performs a web search using the Google Custom Search API.
305
+ * **[BrowserControlNode](documentation/nodes/browser_control.md)**: Controls a web browser to navigate pages, interact with elements, and take screenshots.
306
+ * **[WebSocketsNode](documentation/nodes/websockets.md)**: Provides real-time, two-way communication with web services.
307
+ * **[WebhookNode](documentation/nodes/webhook.md)**: Exposes an HTTP endpoint to receive webhooks, triggering a specified qflow flow.
308
+ * **[HttpServerNode](documentation/nodes/http_server.md)**: Creates a web server and handles HTTP requests by triggering a qflow flow.
309
+ * **[InteractiveWebviewNode](documentation/nodes/interactive_webview.md)**: Displays an interactive webview window for notifications, dialogs, or user input.
310
+ * **[WebviewNode](documentation/nodes/webview.md)**: Displays a webview window with custom HTML content.
311
+
312
+ ### Flow Control
313
+
314
+ * **[SubFlowNode](documentation/nodes/sub_flow.md)**: Executes a sub-flow.
315
+ * **[IteratorNode](documentation/nodes/iterator.md)**: Iterates items, executes sub-flow for each.
316
+ * **[SchedulerNode](documentation/nodes/scheduler.md)**: Schedules qflow flows for future or recurring execution using cron syntax or a delay.
317
+
318
+ ### Other
319
+
320
+ * **[GitNode](documentation/nodes/git.md)**: Performs Git operations like clone, add, commit, and push.
321
+ * **[GISNode](documentation/nodes/gis.md)**: Performs Geographic Information System operations like geocoding and reverse geocoding.
322
+ * **[GitHubNode](documentation/nodes/github.md)**: Performs GitHub operations like creating and managing issues.
323
+ * **[HackerNewsNode](documentation/nodes/hackernews.md)**: Fetches top stories and item details from Hacker News.
324
+ * **[StripeNode](documentation/nodes/stripe.md)**: Performs Stripe operations like creating charges and retrieving account balances.
325
+
326
+ ### LLMs
327
+
328
+ * **[DeepSeekLLMNode](documentation/nodes/deepseek_llm.md)**: Interacts with the DeepSeek API.
329
+ * **[OpenAILLMNode](documentation/nodes/openai_llm.md)**: Interacts with the OpenAI API.
330
+ * **[GeminiLLMNode](documentation/nodes/gemini_llm.md)**: Interacts with the Google Gemini API.
331
+ * **[OllamaLLMNode](documentation/nodes/ollama_llm.md)**: Interacts with a local Ollama instance.
332
+ * **[HuggingFaceLLMNode](documentation/nodes/huggingface_llm.md)**: Interacts with the Hugging Face API.
333
+ * **[OpenRouterLLMNode](documentation/nodes/openrouter_llm.md)**: Interacts with the OpenRouter API.
334
+
335
+ ### Agent
336
+
337
+ * **[AgentNode](documentation/nodes/agent.md)**: The core of agentic behavior in qflow. It orchestrates tools and LLM reasoning to achieve complex goals.
338
+
339
+
265
340
  ## Observability (Event System)
266
341
 
267
342
  `qflow` includes a built-in event system for `AsyncFlow` that provides detailed insights into the execution of your workflows. This allows for powerful, real-time monitoring, logging, and debugging.
@@ -554,7 +629,6 @@ anotherNode.setParams({
554
629
  ```
555
630
 
556
631
 
557
-
558
632
  ## Agents
559
633
 
560
634
  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).
@@ -636,79 +710,6 @@ The `customNodePaths` array should contain paths to your custom node files, rela
636
710
 
637
711
  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
712
 
639
- ## Integrated Nodes and their Examples
640
-
641
- Here's a comprehensive list of integrated nodes available in qflow, along with a brief description and a link to their detailed documentation.
642
-
643
- ### Data
644
-
645
- * **[CodeInterpreterNode](documentation/nodes/code_interpreter.md)**: Executes Python code snippets.
646
- * **[DataExtractorNode](documentation/nodes/data_extractor.md)**: Extracts structured data from HTML, JSON, or plain text.
647
- * **[DatabaseNode](documentation/nodes/database.md)**: Provides a powerful and flexible way to interact with SQL databases.
648
- * **[EmbeddingNode](documentation/nodes/embedding.md)**: Generates vector embeddings for text (requires Ollama).
649
- * **[MemoryNode](documentation/nodes/memory.md)**: Stores and retrieves text memories (keyword-based).
650
- * **[SemanticMemoryNode](documentation/nodes/semantic_memory.md)**: Stores and retrieves text memories via semantic search (requires Ollama).
651
- * **[TransformNode](documentation/nodes/transform.md)**: Transforms input data using a provided JavaScript function.
652
- * **[PDFProcessorNode](documentation/nodes/pdf_processor.md)**: Extracts text or images from PDF documents.
653
- * **[SpreadsheetNode](documentation/nodes/spreadsheet.md)**: Reads from and writes to spreadsheet files (.xlsx, .xls, .csv) with advanced manipulation.
654
- * **[DataValidationNode](documentation/nodes/data_validation.md)**: Validates structured data against a JSON Schema.
655
-
656
- ### System
657
-
658
- * **[ShellCommandNode](documentation/nodes/shell_command.md)**: Executes shell commands.
659
- * **[ReadFileNode](documentation/nodes/read_file.md)**: Reads the content of a specified file.
660
- * **[WriteFileNode](documentation/nodes/write_file.md)**: Writes content to a specified file.
661
- * **[AppendFileNode](documentation/nodes/append_file.md)**: Appends content to an existing file.
662
- * **[ListDirectoryNode](documentation/nodes/list_directory.md)**: Lists the files and subdirectories within a specified directory.
663
- * **[SystemNotificationNode](documentation/nodes/system_notification.md)**: Displays a system-level notification across OSs.
664
- * **[DisplayImageNode](documentation/nodes/display_image.md)**: Displays an image file using the system's default image viewer.
665
- * **[HardwareInteractionNode](documentation/nodes/hardware_interaction.md)**: Communicates with local hardware via serial port (UART).
666
- * **[ImageGalleryNode](documentation/nodes/image_gallery.md)**: Generates an HTML gallery from multiple image files and opens it in a web browser.
667
- * **[SpeechSynthesisNode](documentation/nodes/speech_synthesis.md)**: Converts text to spoken audio using OS capabilities or cloud APIs.
668
- * **[MultimediaProcessingNode](documentation/nodes/multimedia_processing.md)**: Performs various multimedia operations on audio and video files using ffmpeg.
669
- * **[RemoteExecutionNode](documentation/nodes/remote_execution.md)**: Executes commands on remote machines via SSH.
670
-
671
- ### Web
672
-
673
- * **[HttpRequestNode](documentation/nodes/http_request.md)**: Makes a generic HTTP request to any URL.
674
- * **[WebScraperNode](documentation/nodes/web_scraper.md)**: Fetches the HTML content of a given URL.
675
- * **[DuckDuckGoSearchNode](documentation/nodes/duckduckgo_search.md)**: Performs a web search using DuckDuckGo.
676
- * **[GoogleSearchNode](documentation/nodes/google_search.md)**: Performs a web search using the Google Custom Search API.
677
- * **[BrowserControlNode](documentation/nodes/browser_control.md)**: Controls a web browser to navigate pages, interact with elements, and take screenshots.
678
- * **[WebSocketsNode](documentation/nodes/websockets.md)**: Provides real-time, two-way communication with web services.
679
- * **[WebhookNode](documentation/nodes/webhook.md)**: Exposes an HTTP endpoint to receive webhooks, triggering a specified qflow flow.
680
- * **[HttpServerNode](documentation/nodes/http_server.md)**: Creates a web server and handles HTTP requests by triggering a qflow flow.
681
- * **[InteractiveWebviewNode](documentation/nodes/interactive_webview.md)**: Displays an interactive webview window for notifications, dialogs, or user input.
682
- * **[WebviewNode](documentation/nodes/webview.md)**: Displays a webview window with custom HTML content.
683
-
684
- ### Flow Control
685
-
686
- * **[SubFlowNode](documentation/nodes/sub_flow.md)**: Executes a sub-flow.
687
- * **[IteratorNode](documentation/nodes/iterator.md)**: Iterates items, executes sub-flow for each.
688
- * **[SchedulerNode](documentation/nodes/scheduler.md)**: Schedules qflow flows for future or recurring execution using cron syntax or a delay.
689
-
690
- ### Other
691
-
692
- * **[GitNode](documentation/nodes/git.md)**: Performs Git operations like clone, add, commit, and push.
693
- * **[GISNode](documentation/nodes/gis.md)**: Performs Geographic Information System operations like geocoding and reverse geocoding.
694
- * **[GitHubNode](documentation/nodes/github.md)**: Performs GitHub operations like creating and managing issues.
695
- * **[HackerNewsNode](documentation/nodes/hackernews.md)**: Fetches top stories and item details from Hacker News.
696
- * **[StripeNode](documentation/nodes/stripe.md)**: Performs Stripe operations like creating charges and retrieving account balances.
697
-
698
- ### LLMs
699
-
700
- * **[DeepSeekLLMNode](documentation/nodes/deepseek_llm.md)**: Interacts with the DeepSeek API.
701
- * **[OpenAILLMNode](documentation/nodes/openai_llm.md)**: Interacts with the OpenAI API.
702
- * **[GeminiLLMNode](documentation/nodes/gemini_llm.md)**: Interacts with the Google Gemini API.
703
- * **[OllamaLLMNode](documentation/nodes/ollama_llm.md)**: Interacts with a local Ollama instance.
704
- * **[HuggingFaceLLMNode](documentation/nodes/huggingface_llm.md)**: Interacts with the Hugging Face API.
705
- * **[OpenRouterLLMNode](documentation/nodes/openrouter_llm.md)**: Interacts with the OpenRouter API.
706
-
707
- ### Agent
708
-
709
- * **[AgentNode](documentation/nodes/agent.md)**: The core of agentic behavior in qflow. It orchestrates tools and LLM reasoning to achieve complex goals.
710
-
711
-
712
713
 
713
714
  ## Error Handling
714
715
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.61",
3
+ "version": "1.0.63",
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",
@@ -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';