@fractal-solutions/qflow 1.0.31 → 1.0.33

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.
@@ -14,13 +14,9 @@ export class AgentNode extends AsyncNode {
14
14
  getLLMAction(): Promise<any>;
15
15
  manageConversationHistory(): Promise<void>;
16
16
  parseLLMResponse(llmResponse: any): {
17
- thought: string;
18
- toolCalls: any;
19
- parallel: boolean;
20
- } | {
21
17
  thought: any;
22
- toolCalls: never[];
23
- parallel: boolean;
18
+ toolCalls: any;
19
+ parallel: any;
24
20
  };
25
21
  postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
26
22
  }
@@ -14,7 +14,7 @@ export class AgentNode extends AsyncNode {
14
14
  this.summarizeLLM = summarizeLLM;
15
15
  this.flowRegistry = flowRegistry;
16
16
  this.conversationHistory = [];
17
- this.maxSteps = 20;
17
+ this.maxSteps = 70;
18
18
  this.requireFinishConfirmation = requireFinishConfirmation;
19
19
  this.maxConversationHistoryTokens = maxConversationHistoryTokens;
20
20
  }
@@ -93,66 +93,72 @@ export class AgentNode extends AsyncNode {
93
93
  logger.final(finalOutput);
94
94
  break;
95
95
  }
96
- const executeTool = async (toolCall) => {
97
- const toolInstance = this.availableTools[toolCall.tool];
98
- if (!toolInstance) {
99
- return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
100
- }
101
- let toolOutput;
102
- try {
103
- logger.toolCall(toolCall.tool, toolCall.parameters);
104
- // If the tool is a sub-flow or iterator, look up the flow in the registry
105
- if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator') {
106
- const flowName = toolCall.parameters.flow;
107
- if (!this.flowRegistry[flowName]) {
108
- throw new Error(`Flow '${flowName}' not found in registry.`);
109
- }
110
- toolCall.parameters.flow = this.flowRegistry[flowName];
111
- }
112
- toolInstance.setParams(toolCall.parameters);
113
- const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
114
- const toolFlow = new ToolFlowClass(toolInstance);
115
- if (toolInstance instanceof AsyncNode) {
116
- toolOutput = await toolFlow.runAsync({});
96
+ try {
97
+ const executeTool = async (toolCall) => {
98
+ const toolInstance = this.availableTools[toolCall.tool];
99
+ if (!toolInstance) {
100
+ return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
117
101
  }
118
- else {
119
- toolOutput = toolFlow.run({});
102
+ let toolOutput;
103
+ try {
104
+ logger.toolCall(toolCall.tool, toolCall.parameters);
105
+ // If the tool is a sub-flow, iterator or scheduler, look up the flow in the registry
106
+ if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
107
+ const flowName = toolCall.parameters.flow;
108
+ if (!this.flowRegistry[flowName]) {
109
+ throw new Error(`Flow '${flowName}' not found in registry.`);
110
+ }
111
+ toolCall.parameters.flow = this.flowRegistry[flowName];
112
+ }
113
+ toolInstance.setParams(toolCall.parameters);
114
+ const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
115
+ const toolFlow = new ToolFlowClass(toolInstance);
116
+ if (toolInstance instanceof AsyncNode) {
117
+ toolOutput = await toolFlow.runAsync({});
118
+ }
119
+ else {
120
+ toolOutput = toolFlow.run({});
121
+ }
122
+ logger.toolResult(toolCall.tool, toolOutput);
123
+ if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
124
+ logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
125
+ const summarizeNode = new SummarizeNode();
126
+ summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
127
+ const summarizeFlow = new AsyncFlow(summarizeNode);
128
+ toolOutput = await summarizeFlow.runAsync({});
129
+ logger.info(`Summarized to ${toolOutput.length} chars.`);
130
+ }
131
+ return toolOutput;
120
132
  }
121
- logger.toolResult(toolCall.tool, toolOutput);
122
- if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
123
- logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
124
- const summarizeNode = new SummarizeNode();
125
- summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
126
- const summarizeFlow = new AsyncFlow(summarizeNode);
127
- toolOutput = await summarizeFlow.runAsync({});
128
- logger.info(`Summarized to ${toolOutput.length} chars.`);
133
+ catch (e) {
134
+ return `Error executing tool '${toolCall.tool}': ${e.message}`;
129
135
  }
130
- return toolOutput;
136
+ };
137
+ let observations = [];
138
+ if (parallel) {
139
+ const results = await Promise.all(toolCalls.map(executeTool));
140
+ observations = results.map((result, index) => ({
141
+ tool: toolCalls[index].tool,
142
+ parameters: toolCalls[index].parameters,
143
+ output: result
144
+ }));
131
145
  }
132
- catch (e) {
133
- return `Error executing tool '${toolCall.tool}': ${e.message}`;
146
+ else {
147
+ for (const toolCall of toolCalls) {
148
+ const result = await executeTool(toolCall);
149
+ observations.push({
150
+ tool: toolCall.tool,
151
+ parameters: toolCall.parameters,
152
+ output: result
153
+ });
154
+ }
134
155
  }
135
- };
136
- let observations = [];
137
- if (parallel) {
138
- const results = await Promise.all(toolCalls.map(executeTool));
139
- observations = results.map((result, index) => ({
140
- tool: toolCalls[index].tool,
141
- parameters: toolCalls[index].parameters,
142
- output: result
143
- }));
156
+ this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
144
157
  }
145
- else {
146
- for (const toolCall of toolCalls) {
147
- const result = await executeTool(toolCall);
148
- observations.push({
149
- tool: toolCall.tool,
150
- parameters: toolCall.parameters,
151
- output: result
152
- });
153
- }
158
+ catch (e) {
159
+ logger.error(`Error during tool execution: ${e.message}`);
160
+ this.conversationHistory.push({ role: "user", content: `Error: Tool execution failed with message: ${e.message}. You should try a different approach.` });
154
161
  }
155
- this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
156
162
  this.conversationHistory.push({ role: "system", content: "Reflect on the last observation(s) and update your plan if necessary. What is your next step?" });
157
163
  }
158
164
  if (step >= this.maxSteps && finalOutput === null) {
@@ -249,58 +255,59 @@ Parameters: ${params}`;
249
255
  }
250
256
  parseLLMResponse(llmResponse) {
251
257
  let parsed;
252
- let thought = '';
253
- let toolCalls = [];
254
- let parallel = false;
255
- let rawData = llmResponse;
256
258
  if (typeof llmResponse === 'string') {
259
+ // Regex to find json content within ```json ... ``` or just ``` ... ```
260
+ const markdownMatch = llmResponse.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
261
+ const jsonString = markdownMatch ? markdownMatch[1] : llmResponse;
257
262
  try {
258
- parsed = JSON.parse(llmResponse);
263
+ parsed = JSON.parse(jsonString);
259
264
  if (parsed.thought && Array.isArray(parsed.tool_calls)) {
260
- thought = parsed.thought;
261
- toolCalls = parsed.tool_calls;
262
- parallel = parsed.parallel || false;
263
- return { thought, toolCalls, parallel };
265
+ // This is a valid, complete tool call plan.
266
+ return {
267
+ thought: parsed.thought,
268
+ toolCalls: parsed.tool_calls,
269
+ parallel: parsed.parallel || false,
270
+ };
264
271
  }
265
- throw new Error("Missing required keys or invalid format in LLM response (thought, tool_calls array).");
266
272
  }
267
273
  catch (e) {
268
- // If it's not valid JSON for tool calls, assume it's a direct text response from LLM
269
- //return { thought: "Direct LLM response", toolCalls: [{ tool: "finish", parameters: { output: llmResponse } }], parallel: false };
270
- return { thought: message.content, toolCalls: [], parallel: false };
274
+ // JSON.parse failed. This is expected if the LLM just sends a text response.
275
+ // We will fall through and treat the original response as a thought.
271
276
  }
277
+ // If we are here, it means the response was either not valid JSON,
278
+ // or it was valid JSON but didn't have the required 'thought' and 'tool_calls' keys.
279
+ // In either case, we treat the entire original response as a thought with no tool calls.
280
+ return { thought: llmResponse, toolCalls: [], parallel: false };
272
281
  }
273
- // Prioritize tool_calls if present (OpenAI function calling format)
282
+ // This part of the function handles the case where llmResponse is an OBJECT,
283
+ // typically from OpenAI's function calling API.
284
+ const rawData = llmResponse;
274
285
  if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0] && rawData.choices[0].message) {
275
286
  const message = rawData.choices[0].message;
276
287
  if (message.tool_calls && message.tool_calls.length > 0) {
277
- toolCalls = message.tool_calls.map(tc => ({
288
+ const toolCalls = message.tool_calls.map(tc => ({
278
289
  tool: tc.function.name,
279
290
  parameters: JSON.parse(tc.function.arguments)
280
291
  }));
281
- thought = message.reasoning_content || `Calling tool(s): ${toolCalls.map(tc => tc.tool).join(', ')}`;
282
- // OpenAI function calling implies sequential execution unless explicitly handled otherwise
283
- parallel = false;
284
- return { thought, toolCalls, parallel };
292
+ const thought = message.reasoning_content || `Calling tool(s): ${toolCalls.map(tc => tc.tool).join(', ')}`;
293
+ return { thought, toolCalls, parallel: false };
285
294
  }
286
295
  else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
287
- // If no tool_calls, but content is JSON (for thought/tool_calls/finish)
288
296
  try {
289
297
  parsed = JSON.parse(message.content);
290
298
  if (parsed.thought && Array.isArray(parsed.tool_calls)) {
291
- thought = parsed.thought;
292
- toolCalls = parsed.tool_calls;
293
- parallel = parsed.parallel || false;
294
- return { thought, toolCalls, parallel };
299
+ return {
300
+ thought: parsed.thought,
301
+ toolCalls: parsed.tool_calls,
302
+ parallel: parsed.parallel || false,
303
+ };
295
304
  }
296
- throw new Error("Missing required keys or invalid format in message.content (thought, tool_calls array).");
297
305
  }
298
306
  catch (e) {
299
307
  throw new Error(`Invalid JSON or unexpected format in message.content: ${e.message}. Content: ${message.content}`);
300
308
  }
301
309
  }
302
310
  else if (typeof message.content === 'string') {
303
- // If it's a plain string, treat it as a thought and no tool calls
304
311
  return { thought: message.content, toolCalls: [], parallel: false };
305
312
  }
306
313
  }
@@ -43,7 +43,7 @@ export class AgentDeepSeekLLMNode extends DeepSeekLLMNode {
43
43
  throw new Error(`DeepSeek API error: ${response.status} - ${errorData.error.message}`);
44
44
  }
45
45
  const data = await response.json();
46
- console.log("DeepSeek Raw Data:", JSON.stringify(data, null, 2)); // Added logging
46
+ //console.log("DeepSeek Raw Data:", JSON.stringify(data, null, 2)); // Added logging
47
47
  if (!data.choices || data.choices.length === 0 || !data.choices[0].message || typeof data.choices[0].message.content !== 'string') {
48
48
  throw new Error('Invalid response structure from DeepSeek API or missing content.');
49
49
  }
@@ -6,6 +6,7 @@ export * from "./hackernews.js";
6
6
  export * from "./github.js";
7
7
  export * from "./stripe.js";
8
8
  export * from "./webscraper.js";
9
+ export * from "./browser_control.js";
9
10
  export * from "./system_notification.js";
10
11
  export * from "./interactive_input.js";
11
12
  export * from "./pdf_processor.js";
@@ -6,6 +6,7 @@ export * from './hackernews.js';
6
6
  export * from './github.js';
7
7
  export * from './stripe.js';
8
8
  export * from './webscraper.js';
9
+ export * from './browser_control.js';
9
10
  export * from './system_notification.js';
10
11
  export * from './interactive_input.js';
11
12
  export * from './pdf_processor.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.31",
3
+ "version": "1.0.33",
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",