@fractal-solutions/qflow 1.0.23 → 1.0.25

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.
package/README.md CHANGED
@@ -150,6 +150,8 @@ The examples in [Basic Usage & Examples](#basic-usage--examples) below will cove
150
150
 
151
151
  These examples are a great resource for understanding how to leverage `qflow` to its full potential.
152
152
 
153
+ For a detailed list of all tools available to the `AgentNode` and their parameters, see the [Available Tools for Agents](#available-tools-for-agents) section.
154
+
153
155
  ## Basic Usage & Examples
154
156
 
155
157
  ### 1. Simple Node
@@ -1321,3 +1323,102 @@ test("Node should handle parameters via setParams", () => {
1321
1323
  We welcome contributions! Please see our GitHub repository for more details on how to contribute.
1322
1324
 
1323
1325
  ---
1326
+
1327
+ ## Available Tools for Agents
1328
+
1329
+ The `AgentNode` can be equipped with a variety of tools to perform a wide range of tasks. Below is a list of the built-in tools and their functionalities.
1330
+
1331
+ ### Core Tools
1332
+
1333
+ * **finish**: Ends the agent's execution and returns a final output.
1334
+ * `output`: A summary of the final result or the reason for stopping.
1335
+ * **user_input**: Prompts the user for input and waits for their response.
1336
+ * `prompt`: The message to display to the user.
1337
+
1338
+ ### File System
1339
+
1340
+ * **read_file**: Reads the content of a specified file.
1341
+ * `filePath`: The absolute path to the file to read.
1342
+ * **write_file**: Writes content to a specified file.
1343
+ * `filePath`: The absolute path to the file to write to.
1344
+ * `content`: The content to write to the file.
1345
+ * **append_file**: Appends content to an existing file.
1346
+ * `filePath`: The absolute path to the file to append to.
1347
+ * `content`: The content to append to the file.
1348
+ * **list_directory**: Lists the files and subdirectories within a specified directory.
1349
+ * `directoryPath`: The absolute path to the directory to list.
1350
+
1351
+ ### Web
1352
+
1353
+ * **duckduckgo_search**: Performs a web search using DuckDuckGo.
1354
+ * `query`: The search query.
1355
+ * **google_search**: Performs a web search using the Google Custom Search API.
1356
+ * `query`: The search query.
1357
+ * `apiKey`: Your Google API Key.
1358
+ * `cseId`: Your Custom Search Engine ID.
1359
+ * **http_request**: Makes a generic HTTP request to any URL.
1360
+ * `url`: The full URL of the API endpoint.
1361
+ * `method`: The HTTP method to use (e.g., 'GET', 'POST').
1362
+ * `headers`: Custom headers for the request.
1363
+ * `body`: The request payload.
1364
+ * `auth`: Authentication configuration.
1365
+ * **web_scraper**: Fetches the HTML content of a given URL.
1366
+ * `url`: The URL to scrape.
1367
+
1368
+ ### Data & Code
1369
+
1370
+ * **data_extractor**: Extracts structured data from HTML, JSON, or plain text.
1371
+ * `input`: The content string from which to extract data.
1372
+ * `type`: The type of content to extract from (html, json, or text).
1373
+ * `selector`: A CSS selector to target elements (for HTML).
1374
+ * `jsonPath`: A dot-notation path to extract data (for JSON).
1375
+ * `regex`: A regular expression to match and extract data (for text).
1376
+ * `group`: The capturing group index to return from the regex match.
1377
+ * **code_interpreter**: Executes Python code snippets.
1378
+ * `code`: The Python code snippet to execute.
1379
+ * `timeout`: Maximum execution time in milliseconds.
1380
+ * `args`: Command-line arguments to pass to the script.
1381
+ * `requireConfirmation`: If true, the user will be prompted for confirmation before executing the code.
1382
+ * **transform_node**: Transforms input data using a provided JavaScript function.
1383
+ * `input`: The data to be transformed.
1384
+ * `transformFunction`: A JavaScript function string that takes 'data' as an argument and returns the transformed result.
1385
+
1386
+ ### Memory & Embeddings
1387
+
1388
+ * **memory_node**: Stores and retrieves text-based memories from the agent's local file system.
1389
+ * `action`: The action to perform: 'store' or 'retrieve'.
1390
+ * `content`: The text content of the memory to store.
1391
+ * `query`: Keywords to search for within stored memories.
1392
+ * `id`: A unique identifier for the memory.
1393
+ * `memoryPath`: The directory path where memories are stored.
1394
+ * **semantic_memory_node**: Stores and retrieves text-based memories using vector embeddings for semantic search.
1395
+ * `action`: The action to perform: 'store' or 'retrieve'.
1396
+ * `content`: The text content of the memory to store.
1397
+ * `query`: The text query for semantic search.
1398
+ * `id`: A unique identifier for the memory.
1399
+ * `metadata`: Key-value pairs to store alongside the memory.
1400
+ * `memoryPath`: The directory path where memories and the index are stored.
1401
+ * `embeddingModel`: The Ollama embedding model name to use.
1402
+ * `embeddingBaseUrl`: The base URL of the Ollama API for embeddings.
1403
+ * `topK`: The number of top similar results to retrieve.
1404
+ * **generate_embedding**: Generates a vector embedding for a given text using a local Ollama embedding model.
1405
+ * `text`: The text string to generate an embedding for.
1406
+ * `model`: The Ollama embedding model name to use.
1407
+ * `baseUrl`: The base URL of the Ollama API.
1408
+
1409
+ ### LLM Reasoning
1410
+
1411
+ * **huggingface_llm_reasoning**: A powerful language model for general reasoning, problem-solving, and generating text, using Hugging Face's OpenAI-compatible router.
1412
+ * `prompt`: The prompt or question to send to the language model.
1413
+ * `model`: The Hugging Face model ID.
1414
+ * `hfToken`: Your Hugging Face API token.
1415
+ * `temperature`: Controls randomness.
1416
+ * `max_new_tokens`: Maximum number of tokens to generate.
1417
+ * `baseUrl`: The base URL of the Hugging Face router API.
1418
+ * **llm_reasoning**: A powerful language model for general reasoning, problem-solving, and generating text.
1419
+ * `prompt`: The prompt or question to send to the language model.
1420
+ * **ollama_llm_reasoning**: A powerful local language model for general reasoning, problem-solving, and generating text, running via Ollama.
1421
+ * `prompt`: The prompt or question to send to the local Ollama language model.
1422
+ * `model`: The Ollama model name to use.
1423
+ * `baseUrl`: The base URL of the Ollama API.
1424
+
@@ -1,6 +1,7 @@
1
1
  import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
2
2
  import { getToolDefinitions } from './tools.js';
3
- import { SummarizeNode } from '../nodes/summarize.js'; // Import SummarizeNode
3
+ import { SummarizeNode } from '../nodes/summarize.js';
4
+ import { logger } from './logger.js';
4
5
  export class AgentNode extends AsyncNode {
5
6
  constructor(llmNode, availableTools, summarizeLLM) {
6
7
  super();
@@ -8,10 +9,10 @@ export class AgentNode extends AsyncNode {
8
9
  throw new Error("AgentNode requires an LLMNode instance for reasoning.");
9
10
  }
10
11
  this.llmNode = llmNode;
11
- this.availableTools = availableTools; // Map of tool_name -> qflow_node_instance
12
- this.summarizeLLM = summarizeLLM; // LLM for summarization
12
+ this.availableTools = availableTools;
13
+ this.summarizeLLM = summarizeLLM;
13
14
  this.conversationHistory = [];
14
- this.maxSteps = 20; // Limit to prevent infinite loops
15
+ this.maxSteps = 20;
15
16
  }
16
17
  async execAsync() {
17
18
  const { goal } = this.params;
@@ -26,16 +27,13 @@ export class AgentNode extends AsyncNode {
26
27
  let finalOutput = null;
27
28
  while (step < this.maxSteps) {
28
29
  step++;
29
- console.log(`\n--- Agent Step ${step} ---`);
30
- // 1. Reason: Get LLM's next action
30
+ logger.info(`Agent Step ${step}`);
31
31
  let llmResponse;
32
32
  try {
33
33
  llmResponse = await this.getLLMAction();
34
- //console.log(`LLM Raw Response (before parsing):`, llmResponse); // Added logging
35
- //console.log(`LLM Raw Response Type (before parsing):`, typeof llmResponse); // Added logging
36
34
  }
37
35
  catch (e) {
38
- console.error("Error getting LLM action:", e.message);
36
+ logger.error(`Error getting LLM action: ${e.message}`);
39
37
  this.conversationHistory.push({ role: "user", content: `Error: Failed to get LLM response: ${e.message}` });
40
38
  continue;
41
39
  }
@@ -44,28 +42,29 @@ export class AgentNode extends AsyncNode {
44
42
  const parsedResponse = this.parseLLMResponse(llmResponse);
45
43
  thought = parsedResponse.thought;
46
44
  toolCall = parsedResponse.tool;
45
+ logger.thought(thought);
47
46
  }
48
47
  catch (e) {
49
- console.error("Error parsing LLM response:", e.message);
48
+ logger.error(`Error parsing LLM response: ${e.message}`);
50
49
  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' object. Error: ${e.message}. Your last response was: ${llmResponse}` });
51
- continue; // Ask LLM to try again
50
+ continue;
52
51
  }
53
52
  this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought, tool: toolCall }) });
54
53
  if (toolCall.tool === "finish") {
55
54
  finalOutput = toolCall.parameters.output;
56
- console.log(`Agent finished. Output: ${finalOutput}`);
55
+ logger.final(finalOutput);
57
56
  break;
58
57
  }
59
- // 2. Act: Execute the tool
60
58
  const toolInstance = this.availableTools[toolCall.tool];
61
59
  if (!toolInstance) {
62
- const errorMessage = `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
63
- console.error(errorMessage);
60
+ const errorMessage = `Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
61
+ logger.error(errorMessage);
64
62
  this.conversationHistory.push({ role: "user", content: errorMessage });
65
- continue; // Ask LLM to try again
63
+ continue;
66
64
  }
67
65
  let toolOutput;
68
66
  try {
67
+ logger.toolCall(toolCall.tool, toolCall.parameters);
69
68
  toolInstance.setParams(toolCall.parameters);
70
69
  const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
71
70
  const toolFlow = new ToolFlowClass(toolInstance);
@@ -75,27 +74,26 @@ export class AgentNode extends AsyncNode {
75
74
  else {
76
75
  toolOutput = toolFlow.run({});
77
76
  }
78
- console.log(`Tool '${toolCall.tool}' executed successfully.`);
79
- // Summarize large outputs before adding to history
80
- if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) { // Summarize if output is string and > 1000 chars
81
- console.log(`Summarizing large tool output (${toolOutput.length} chars)...`);
77
+ logger.toolResult(toolCall.tool, toolOutput);
78
+ if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
79
+ logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
82
80
  const summarizeNode = new SummarizeNode();
83
81
  summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
84
82
  const summarizeFlow = new AsyncFlow(summarizeNode);
85
83
  toolOutput = await summarizeFlow.runAsync({});
86
- console.log(`Summarized to ${toolOutput.length} chars.`);
84
+ logger.info(`Summarized to ${toolOutput.length} chars.`);
87
85
  }
88
86
  }
89
87
  catch (e) {
90
88
  toolOutput = `Error executing tool '${toolCall.tool}': ${e.message}`;
91
- console.error(toolOutput);
89
+ logger.error(toolOutput);
92
90
  }
93
- // 3. Observe: Add tool output to history
94
91
  this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(toolOutput)}` });
95
92
  }
96
93
  if (step >= this.maxSteps && finalOutput === null) {
97
- console.warn("Agent reached max steps without finishing.");
98
- finalOutput = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
94
+ const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
95
+ logger.error(message);
96
+ finalOutput = message;
99
97
  }
100
98
  return finalOutput;
101
99
  }
@@ -108,7 +106,6 @@ export class AgentNode extends AsyncNode {
108
106
  return `You are an autonomous agent designed to achieve a goal by selecting and using tools. Your responses must be in a specific JSON format.\n\nAvailable Tools:\n${toolDescriptions}\n\nYour response must be a single JSON object with two keys: 'thought' and 'tool'.\n'thought': A string explaining your reasoning process and plan.\n'tool': An object with two keys: 'tool' (the name of the tool to call) and 'parameters' (an object containing the parameters for that tool).\n\nExample response:\n{\n "thought": "I need to find information about X, so I will use the duckduckgo_search tool.",\n "tool": {\n "tool": "duckduckgo_search",\n "parameters": {\n "query": "X information"\n }\n }\n}\n\nWhen you have achieved the goal or cannot proceed, use the 'finish' tool.\nExample finish response:\n{\n "thought": "I have successfully achieved the goal.",\n "tool": {\n "tool": "finish",\n "parameters": {\n "output": "The final result of the goal."\n }\n}\n\nBegin!`;
109
107
  }
110
108
  async getLLMAction() {
111
- // The LLM expects a stringified array of messages
112
109
  this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
113
110
  const llmResult = await this.llmNode.runAsync({});
114
111
  return llmResult;
@@ -117,20 +114,15 @@ export class AgentNode extends AsyncNode {
117
114
  let parsed;
118
115
  let thought = '';
119
116
  let toolCall = {};
120
- // Check if llmResponse is already a parsed object (e.g., from AgentHuggingFaceLLMNode's raw data)
121
- // This is a temporary measure for debugging, ideally llmResponse should always be a string
122
117
  let rawData = llmResponse;
123
118
  if (typeof llmResponse === 'string') {
124
119
  try {
125
120
  rawData = JSON.parse(llmResponse);
126
121
  }
127
122
  catch (e) {
128
- // If it's not JSON, assume it's a direct text response from LLM
129
- // This path should ideally not be taken if LLM is tool-calling capable
130
123
  return { thought: "Direct LLM response", tool: { tool: "finish", parameters: { output: llmResponse } } };
131
124
  }
132
125
  }
133
- // Prioritize tool_calls if present (OpenAI function calling format)
134
126
  if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0].message) {
135
127
  const message = rawData.choices[0].message;
136
128
  if (message.tool_calls && message.tool_calls.length > 0) {
@@ -139,11 +131,10 @@ export class AgentNode extends AsyncNode {
139
131
  tool: firstToolCall.function.name,
140
132
  parameters: JSON.parse(firstToolCall.function.arguments)
141
133
  };
142
- thought = message.reasoning_content || `Calling tool: ${toolCall.tool}`; // Use reasoning_content if available
134
+ thought = message.reasoning_content || `Calling tool: ${toolCall.tool}`;
143
135
  return { thought, tool: toolCall };
144
136
  }
145
137
  else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
146
- // If no tool_calls, but content is JSON (for thought/tool/finish)
147
138
  try {
148
139
  parsed = JSON.parse(message.content);
149
140
  if (parsed.thought && parsed.tool && parsed.tool.tool && parsed.tool.parameters !== undefined) {
@@ -156,7 +147,6 @@ export class AgentNode extends AsyncNode {
156
147
  }
157
148
  }
158
149
  else if (typeof message.content === 'string') {
159
- // If content is plain text, assume it's a direct answer
160
150
  return { thought: "Direct LLM response", tool: { tool: "finish", parameters: { output: message.content } } };
161
151
  }
162
152
  }
@@ -0,0 +1,8 @@
1
+ export namespace logger {
2
+ function info(message: any): void;
3
+ function thought(message: any): void;
4
+ function toolCall(tool: any, params: any): void;
5
+ function toolResult(tool: any, result: any): void;
6
+ function error(message: any): void;
7
+ function final(message: any): void;
8
+ }
@@ -0,0 +1,44 @@
1
+ const colors = {
2
+ reset: "\x1b[0m",
3
+ cyan: "\x1b[36m",
4
+ yellow: "\x1b[33m",
5
+ green: "\x1b[32m",
6
+ magenta: "\x1b[35m",
7
+ red: "\x1b[31m",
8
+ grey: "\x1b[90m"
9
+ };
10
+ function colorize(text, color) {
11
+ return `${color}${text}${colors.reset}`;
12
+ }
13
+ export const logger = {
14
+ info: (message) => console.log(colorize(`[INFO] ${message}`, colors.cyan)),
15
+ thought: (message) => {
16
+ console.log("\n---------------------");
17
+ console.log(colorize("šŸ¤” Thought", colors.yellow));
18
+ console.log(colorize(message, colors.grey));
19
+ console.log("---------------------");
20
+ },
21
+ toolCall: (tool, params) => {
22
+ console.log(colorize("\nšŸ› ļø Tool Call", colors.green));
23
+ console.log(colorize(`Tool: ${tool}`, colors.magenta));
24
+ console.log(colorize(`Params: ${JSON.stringify(params, null, 2)}`, colors.magenta));
25
+ console.log("---------------------");
26
+ },
27
+ toolResult: (tool, result) => {
28
+ console.log(colorize("\nāœ… Tool Result", colors.green));
29
+ console.log(colorize(`Tool: ${tool}`, colors.magenta));
30
+ console.log(colorize(`Result: ${JSON.stringify(result, null, 2)}`, colors.grey));
31
+ console.log("---------------------");
32
+ },
33
+ error: (message) => {
34
+ console.log(colorize("\nāŒ Error", colors.red));
35
+ console.log(colorize(message, colors.red));
36
+ console.log("---------------------");
37
+ },
38
+ final: (message) => {
39
+ console.log("\n---------------------");
40
+ console.log(colorize("šŸŽ‰ Final Output", colors.yellow));
41
+ console.log(colorize(message, colors.cyan));
42
+ console.log("---------------------");
43
+ }
44
+ };
@@ -14,8 +14,10 @@ export class AgentOpenAILLMNode extends OpenAILLMNode {
14
14
  postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
15
15
  }
16
16
  export class AgentGeminiLLMNode extends GeminiLLMNode {
17
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
17
18
  }
18
19
  export class AgentOllamaLLMNode extends OllamaLLMNode {
20
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
19
21
  }
20
22
  export class AgentHuggingFaceLLMNode extends HuggingFaceLLMNode {
21
23
  preparePrompt(shared: any): void;
@@ -175,6 +175,10 @@ export class AgentGeminiLLMNode extends GeminiLLMNode {
175
175
  throw error;
176
176
  }
177
177
  }
178
+ async postAsync(shared, prepRes, execRes) {
179
+ shared.llmResponse = execRes; // Store the full LLM response object
180
+ return execRes; // Return the full LLM response object
181
+ }
178
182
  }
179
183
  export class AgentOllamaLLMNode extends OllamaLLMNode {
180
184
  preparePrompt(shared) {
@@ -217,6 +221,10 @@ export class AgentOllamaLLMNode extends OllamaLLMNode {
217
221
  throw error;
218
222
  }
219
223
  }
224
+ async postAsync(shared, prepRes, execRes) {
225
+ shared.llmResponse = execRes; // Store the full LLM response object
226
+ return execRes; // Return the full LLM response object
227
+ }
220
228
  }
221
229
  export class AgentHuggingFaceLLMNode extends HuggingFaceLLMNode {
222
230
  preparePrompt(shared) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.23",
3
+ "version": "1.0.25",
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",