@fractal-solutions/qflow 1.0.22 → 1.0.24

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.
@@ -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 = 10; // 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.22",
3
+ "version": "1.0.24",
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",