@fractal-solutions/qflow 1.0.60 → 1.0.62
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 +75 -74
- package/dist/qflow.config.d.ts +5 -0
- package/dist/qflow.config.js +16 -0
- package/dist/src/agent/agent.d.ts +23 -0
- package/dist/src/agent/agent.js +365 -0
- package/dist/src/agent/base_agent.d.ts +21 -0
- package/dist/src/agent/base_agent.js +206 -0
- package/dist/src/agent/logger.d.ts +9 -0
- package/dist/src/agent/logger.js +45 -0
- package/dist/src/agent/lpavrl_agent.d.ts +5 -0
- package/dist/src/agent/lpavrl_agent.js +178 -0
- package/dist/src/agent/ooda_agent.d.ts +5 -0
- package/dist/src/agent/ooda_agent.js +167 -0
- package/dist/src/agent/pema_agent.d.ts +5 -0
- package/dist/src/agent/pema_agent.js +171 -0
- package/dist/src/agent/raor_agent.d.ts +5 -0
- package/dist/src/agent/raor_agent.js +164 -0
- package/dist/src/agent/tools.d.ts +1 -0
- package/dist/src/agent/tools.js +148 -0
- package/dist/src/logger.d.ts +9 -0
- package/dist/src/logger.js +107 -0
- package/dist/src/nodes/agent_llm.d.ts +31 -0
- package/dist/src/nodes/agent_llm.js +302 -0
- package/dist/src/nodes/browser_control.d.ts +35 -0
- package/dist/src/nodes/browser_control.js +106 -0
- package/dist/src/nodes/code_interpreter.d.ts +38 -0
- package/dist/src/nodes/code_interpreter.js +150 -0
- package/dist/src/nodes/data_extractor.d.ts +40 -0
- package/dist/src/nodes/data_extractor.js +118 -0
- package/dist/src/nodes/data_validation.d.ts +36 -0
- package/dist/src/nodes/data_validation.js +77 -0
- package/dist/src/nodes/database.d.ts +50 -0
- package/dist/src/nodes/database.js +135 -0
- package/dist/src/nodes/display_image.d.ts +18 -0
- package/dist/src/nodes/display_image.js +63 -0
- package/dist/src/nodes/embedding.d.ts +29 -0
- package/dist/src/nodes/embedding.js +69 -0
- package/dist/src/nodes/filesystem.d.ts +105 -0
- package/dist/src/nodes/filesystem.js +160 -0
- package/dist/src/nodes/gis.d.ts +62 -0
- package/dist/src/nodes/gis.js +133 -0
- package/dist/src/nodes/git.d.ts +46 -0
- package/dist/src/nodes/git.js +99 -0
- package/dist/src/nodes/github.d.ts +83 -0
- package/dist/src/nodes/github.js +135 -0
- package/dist/src/nodes/hackernews.d.ts +47 -0
- package/dist/src/nodes/hackernews.js +79 -0
- package/dist/src/nodes/hardware_interaction.d.ts +39 -0
- package/dist/src/nodes/hardware_interaction.js +131 -0
- package/dist/src/nodes/http.d.ts +77 -0
- package/dist/src/nodes/http.js +120 -0
- package/dist/src/nodes/http_server.d.ts +54 -0
- package/dist/src/nodes/http_server.js +223 -0
- package/dist/src/nodes/image_gallery.d.ts +37 -0
- package/dist/src/nodes/image_gallery.js +129 -0
- package/dist/src/nodes/index.d.ts +48 -0
- package/dist/src/nodes/index.js +48 -0
- package/dist/src/nodes/interactive_input.d.ts +26 -0
- package/dist/src/nodes/interactive_input.js +95 -0
- package/dist/src/nodes/interactive_webview.d.ts +78 -0
- package/dist/src/nodes/interactive_webview.js +369 -0
- package/dist/src/nodes/iterator.d.ts +23 -0
- package/dist/src/nodes/iterator.js +43 -0
- package/dist/src/nodes/llm.d.ts +160 -0
- package/dist/src/nodes/llm.js +367 -0
- package/dist/src/nodes/memory.d.ts +43 -0
- package/dist/src/nodes/memory.js +90 -0
- package/dist/src/nodes/multimedia_processing.d.ts +57 -0
- package/dist/src/nodes/multimedia_processing.js +129 -0
- package/dist/src/nodes/openrouter_llm.d.ts +38 -0
- package/dist/src/nodes/openrouter_llm.js +156 -0
- package/dist/src/nodes/pdf_processor.d.ts +43 -0
- package/dist/src/nodes/pdf_processor.js +112 -0
- package/dist/src/nodes/remote_execution.d.ts +51 -0
- package/dist/src/nodes/remote_execution.js +132 -0
- package/dist/src/nodes/s3.d.ts +73 -0
- package/dist/src/nodes/s3.js +107 -0
- package/dist/src/nodes/scheduler.d.ts +51 -0
- package/dist/src/nodes/scheduler.js +131 -0
- package/dist/src/nodes/search.d.ts +61 -0
- package/dist/src/nodes/search.js +118 -0
- package/dist/src/nodes/semantic_memory.d.ts +64 -0
- package/dist/src/nodes/semantic_memory.js +160 -0
- package/dist/src/nodes/shell.d.ts +25 -0
- package/dist/src/nodes/shell.js +45 -0
- package/dist/src/nodes/speech_synthesis.d.ts +72 -0
- package/dist/src/nodes/speech_synthesis.js +171 -0
- package/dist/src/nodes/spreadsheet.d.ts +61 -0
- package/dist/src/nodes/spreadsheet.js +294 -0
- package/dist/src/nodes/stripe.d.ts +67 -0
- package/dist/src/nodes/stripe.js +117 -0
- package/dist/src/nodes/subflow.d.ts +23 -0
- package/dist/src/nodes/subflow.js +36 -0
- package/dist/src/nodes/summarize.d.ts +26 -0
- package/dist/src/nodes/summarize.js +51 -0
- package/dist/src/nodes/system_notification.d.ts +26 -0
- package/dist/src/nodes/system_notification.js +74 -0
- package/dist/src/nodes/transform.d.ts +23 -0
- package/dist/src/nodes/transform.js +52 -0
- package/dist/src/nodes/user.d.ts +25 -0
- package/dist/src/nodes/user.js +48 -0
- package/dist/src/nodes/webhook.d.ts +49 -0
- package/dist/src/nodes/webhook.js +161 -0
- package/dist/src/nodes/webscraper.d.ts +25 -0
- package/dist/src/nodes/webscraper.js +49 -0
- package/dist/src/nodes/websockets.d.ts +27 -0
- package/dist/src/nodes/websockets.js +98 -0
- package/dist/src/nodes/webview.d.ts +38 -0
- package/dist/src/nodes/webview.js +55 -0
- package/dist/src/qflow.d.ts +69 -0
- package/dist/src/qflow.js +320 -0
- package/dist/src/types.d.ts +6 -0
- package/dist/src/types.js +5 -0
- package/package.json +1 -1
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { BaseAgent } from './base_agent.js';
|
|
2
|
+
import { logger } from './logger.js';
|
|
3
|
+
import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
|
|
4
|
+
import { UserInputNode } from '../nodes/index.js';
|
|
5
|
+
export class PEMAAgent extends BaseAgent {
|
|
6
|
+
async execAsync() {
|
|
7
|
+
const { goal } = this.params;
|
|
8
|
+
if (!goal) {
|
|
9
|
+
throw new Error("PEMAAgent requires a 'goal' parameter.");
|
|
10
|
+
}
|
|
11
|
+
this.conversationHistory = [
|
|
12
|
+
{ role: "system", content: this.getSystemPrompt() },
|
|
13
|
+
{ role: "user", content: `Goal: ${goal}` },
|
|
14
|
+
];
|
|
15
|
+
let step = 0;
|
|
16
|
+
let finalOutput = null;
|
|
17
|
+
while (step < this.maxSteps) {
|
|
18
|
+
step++;
|
|
19
|
+
logger.info(`Agent Step ${step}`);
|
|
20
|
+
// Plan
|
|
21
|
+
this.conversationHistory.push({ role: "user", content: "Current Phase: PLAN. Define actions needed to reach the goal." });
|
|
22
|
+
const planResponse = await this.getLLMAction();
|
|
23
|
+
let parsedPlanResponse;
|
|
24
|
+
try {
|
|
25
|
+
parsedPlanResponse = this.parseLLMResponse(planResponse);
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
logger.error(`Error parsing LLM response in Plan phase: ${e.message}`);
|
|
29
|
+
this.conversationHistory.push({ role: "user", content: `
|
|
30
|
+
CRITICAL ERROR: Your last response was NOT valid JSON or did not follow the expected format.\nError details: ${e.message}\nYour invalid response was: \n\`\`\`\n${planResponse}\n\`\`\`\nYou MUST respond with a single JSON object containing \'thought\' and \'tool_calls\'. Do NOT generate any other text or code outside of this JSON structure. Re-evaluate your plan and provide a valid JSON response.\n` });
|
|
31
|
+
continue; // Re-run the loop to allow the LLM to correct itself
|
|
32
|
+
}
|
|
33
|
+
const { thought: planThought, toolCalls, parallel } = parsedPlanResponse;
|
|
34
|
+
logger.thought(planThought);
|
|
35
|
+
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: planThought, tool_calls: toolCalls, parallel }) });
|
|
36
|
+
// Validate tool parameters for all tool calls
|
|
37
|
+
const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
|
|
38
|
+
if (validationErrors.length > 0) {
|
|
39
|
+
const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
|
|
40
|
+
logger.error(errorMessage);
|
|
41
|
+
this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
|
|
42
|
+
continue; // Re-run the loop to allow the LLM to correct itself
|
|
43
|
+
}
|
|
44
|
+
// Handle finish tool (check here before acting)
|
|
45
|
+
const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
|
|
46
|
+
if (finishToolCall) {
|
|
47
|
+
finalOutput = finishToolCall.parameters.output;
|
|
48
|
+
if (this.requireFinishConfirmation) {
|
|
49
|
+
const confirmNode = new UserInputNode();
|
|
50
|
+
confirmNode.setParams({
|
|
51
|
+
prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
|
|
52
|
+
});
|
|
53
|
+
const confirmFlow = new AsyncFlow(confirmNode);
|
|
54
|
+
const confirmation = await confirmFlow.runAsync({});
|
|
55
|
+
if (confirmation.toLowerCase() !== 'yes') {
|
|
56
|
+
logger.info("Agent finish denied by user. User input will be the next prompt.");
|
|
57
|
+
this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
|
|
58
|
+
continue; // Continue the loop
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
logger.final(finalOutput);
|
|
62
|
+
break; // Exit the main loop as agent is finished
|
|
63
|
+
}
|
|
64
|
+
// If no tool calls and not trying to finish, prompt LLM to generate tool calls
|
|
65
|
+
if (toolCalls.length === 0) {
|
|
66
|
+
this.conversationHistory.push({ role: "user", content: "Current Phase: PLAN. Your previous response did not include any tool calls. If you intend to take action, you MUST include at least one tool call in your JSON response. Re-evaluate your plan and provide tool calls." });
|
|
67
|
+
continue; // Re-run the loop to force tool call generation
|
|
68
|
+
}
|
|
69
|
+
// Execute
|
|
70
|
+
const observations = await this.executeToolCalls(toolCalls, parallel);
|
|
71
|
+
this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
|
|
72
|
+
// Check for tool errors and add specific instructions for reflection
|
|
73
|
+
const toolErrors = observations.filter(obs => obs.success === false);
|
|
74
|
+
if (toolErrors.length > 0) {
|
|
75
|
+
const errorMessages = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
|
|
76
|
+
this.conversationHistory.push({ role: "system", content: `
|
|
77
|
+
IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
|
|
78
|
+
${errorMessages}
|
|
79
|
+
|
|
80
|
+
Explain *why* these tools failed. Propose an alternative tool or a revised plan to achieve the goal without these tools, or suggest how to fix the underlying issue. Do NOT generate irrelevant code, random thoughts, or go off-topic. Focus solely on addressing these errors and getting back on track to achieve the user's goal.
|
|
81
|
+
` });
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
// Monitor
|
|
85
|
+
this.conversationHistory.push({ role: "user", content: "Current Phase: MONITOR. Check current status against the plan." });
|
|
86
|
+
}
|
|
87
|
+
const monitorResponse = await this.getLLMAction();
|
|
88
|
+
const { thought: monitorThought } = this.parseLLMResponse(monitorResponse);
|
|
89
|
+
logger.thought(monitorThought);
|
|
90
|
+
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: monitorThought }) });
|
|
91
|
+
// Adjust
|
|
92
|
+
this.conversationHistory.push({ role: "user", content: "Current Phase: ADJUST. Modify the plan if deviations are detected." });
|
|
93
|
+
const adjustResponse = await this.getLLMAction();
|
|
94
|
+
const { thought: adjustThought } = this.parseLLMResponse(adjustResponse);
|
|
95
|
+
logger.thought(adjustThought);
|
|
96
|
+
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: adjustThought }) });
|
|
97
|
+
if (finishToolCall) {
|
|
98
|
+
finalOutput = finishToolCall.parameters.output;
|
|
99
|
+
logger.final(finalOutput);
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (step >= this.maxSteps && finalOutput === null) {
|
|
104
|
+
const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
|
|
105
|
+
logger.error(message);
|
|
106
|
+
finalOutput = message;
|
|
107
|
+
}
|
|
108
|
+
return finalOutput;
|
|
109
|
+
}
|
|
110
|
+
async executeToolCalls(toolCalls, parallel) {
|
|
111
|
+
const executeTool = async (toolCall) => {
|
|
112
|
+
const toolInstance = this.availableTools[toolCall.tool];
|
|
113
|
+
if (!toolInstance) {
|
|
114
|
+
return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
|
|
115
|
+
}
|
|
116
|
+
let toolOutput;
|
|
117
|
+
try {
|
|
118
|
+
logger.toolCall(toolCall.tool, toolCall.parameters);
|
|
119
|
+
if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
|
|
120
|
+
const flowName = toolCall.parameters.flow;
|
|
121
|
+
if (!this.flowRegistry[flowName]) {
|
|
122
|
+
throw new Error(`Flow '${flowName}' not found in registry.`);
|
|
123
|
+
}
|
|
124
|
+
toolCall.parameters.flow = this.flowRegistry[flowName];
|
|
125
|
+
}
|
|
126
|
+
toolInstance.setParams(toolCall.parameters);
|
|
127
|
+
const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
|
|
128
|
+
const toolFlow = new ToolFlowClass(toolInstance);
|
|
129
|
+
if (toolInstance instanceof AsyncNode) {
|
|
130
|
+
toolOutput = await toolFlow.runAsync({});
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
toolOutput = toolFlow.run({});
|
|
134
|
+
}
|
|
135
|
+
logger.toolResult(toolCall.tool, toolOutput);
|
|
136
|
+
if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
|
|
137
|
+
logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
|
|
138
|
+
const summarizeNode = new SummarizeNode();
|
|
139
|
+
summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
|
|
140
|
+
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
141
|
+
toolOutput = await summarizeFlow.runAsync({});
|
|
142
|
+
logger.info(`Summarized to ${toolOutput.length} chars.`);
|
|
143
|
+
}
|
|
144
|
+
return { success: true, output: toolOutput };
|
|
145
|
+
}
|
|
146
|
+
catch (e) {
|
|
147
|
+
return { success: false, error: `Error executing tool '${toolCall.tool}': ${e.message}` };
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
let observations = [];
|
|
151
|
+
if (parallel) {
|
|
152
|
+
const results = await Promise.all(toolCalls.map(executeTool));
|
|
153
|
+
observations = results.map((result, index) => ({
|
|
154
|
+
tool: toolCalls[index].tool,
|
|
155
|
+
parameters: toolCalls[index].parameters,
|
|
156
|
+
...result // Spread success/error and output/error
|
|
157
|
+
}));
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
for (const toolCall of toolCalls) {
|
|
161
|
+
const result = await executeTool(toolCall);
|
|
162
|
+
observations.push({
|
|
163
|
+
tool: toolCall.tool,
|
|
164
|
+
parameters: toolCall.parameters,
|
|
165
|
+
...result // Spread success/error and output/error
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return observations;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { BaseAgent } from './base_agent.js';
|
|
2
|
+
import { logger } from './logger.js';
|
|
3
|
+
import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
|
|
4
|
+
import { UserInputNode } from '../nodes/index.js';
|
|
5
|
+
export class RAORAgent extends BaseAgent {
|
|
6
|
+
async execAsync() {
|
|
7
|
+
const { goal } = this.params;
|
|
8
|
+
if (!goal) {
|
|
9
|
+
throw new Error("RAORAgent requires a 'goal' parameter.");
|
|
10
|
+
}
|
|
11
|
+
this.conversationHistory = [
|
|
12
|
+
{ role: "system", content: this.getSystemPrompt() },
|
|
13
|
+
{ role: "user", content: `Goal: ${goal}` },
|
|
14
|
+
];
|
|
15
|
+
let step = 0;
|
|
16
|
+
let finalOutput = null;
|
|
17
|
+
while (step < this.maxSteps) {
|
|
18
|
+
step++;
|
|
19
|
+
logger.info(`Agent Step ${step}`);
|
|
20
|
+
// Reason
|
|
21
|
+
this.conversationHistory.push({ role: "user", content: "Current Phase: REASON. Analyze the user's request and formulate a plan." });
|
|
22
|
+
const reasonResponse = await this.getLLMAction();
|
|
23
|
+
let parsedReasonResponse;
|
|
24
|
+
try {
|
|
25
|
+
parsedReasonResponse = this.parseLLMResponse(reasonResponse);
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
logger.error(`Error parsing LLM response in Reason phase: ${e.message}`);
|
|
29
|
+
this.conversationHistory.push({ role: "user", content: `
|
|
30
|
+
CRITICAL ERROR: Your last response was NOT valid JSON or did not follow the expected format.
|
|
31
|
+
Error details: ${e.message}
|
|
32
|
+
Your invalid response was:
|
|
33
|
+
'''${reasonResponse}'''
|
|
34
|
+
You MUST respond with a single JSON object containing 'thought' and 'tool_calls'. Do NOT generate any other text or code outside of this JSON structure. Re-evaluate your plan and provide a valid JSON response.
|
|
35
|
+
` });
|
|
36
|
+
continue; // Re-run the loop to allow the LLM to correct itself
|
|
37
|
+
}
|
|
38
|
+
const { thought, toolCalls, parallel } = parsedReasonResponse;
|
|
39
|
+
logger.thought(thought);
|
|
40
|
+
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought, tool_calls: toolCalls, parallel }) });
|
|
41
|
+
// Validate tool parameters for all tool calls
|
|
42
|
+
const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
|
|
43
|
+
if (validationErrors.length > 0) {
|
|
44
|
+
const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
|
|
45
|
+
logger.error(errorMessage);
|
|
46
|
+
this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
|
|
47
|
+
continue; // Re-run the loop to allow the LLM to correct itself
|
|
48
|
+
}
|
|
49
|
+
// Handle finish tool (check here before acting)
|
|
50
|
+
const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
|
|
51
|
+
if (finishToolCall) {
|
|
52
|
+
finalOutput = finishToolCall.parameters.output;
|
|
53
|
+
if (this.requireFinishConfirmation) {
|
|
54
|
+
const confirmNode = new UserInputNode();
|
|
55
|
+
confirmNode.setParams({
|
|
56
|
+
prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
|
|
57
|
+
});
|
|
58
|
+
const confirmFlow = new AsyncFlow(confirmNode);
|
|
59
|
+
const confirmation = await confirmFlow.runAsync({});
|
|
60
|
+
if (confirmation.toLowerCase() !== 'yes') {
|
|
61
|
+
logger.info("Agent finish denied by user. User input will be the next prompt.");
|
|
62
|
+
this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
|
|
63
|
+
continue; // Continue the loop
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
logger.final(finalOutput);
|
|
67
|
+
break; // Exit the main loop as agent is finished
|
|
68
|
+
}
|
|
69
|
+
// If no tool calls and not trying to finish, prompt LLM to generate tool calls
|
|
70
|
+
if (toolCalls.length === 0) {
|
|
71
|
+
this.conversationHistory.push({ role: "user", content: "Current Phase: REASON. Your previous response did not include any tool calls. If you intend to take action, you MUST include at least one tool call in your JSON response. Re-evaluate your plan and provide tool calls." });
|
|
72
|
+
continue; // Re-run the loop to force tool call generation
|
|
73
|
+
}
|
|
74
|
+
// Act
|
|
75
|
+
const observations = await this.executeToolCalls(toolCalls, parallel);
|
|
76
|
+
this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
|
|
77
|
+
// Check for tool errors and add specific instructions for reflection
|
|
78
|
+
const toolErrors = observations.filter(obs => obs.success === false);
|
|
79
|
+
if (toolErrors.length > 0) {
|
|
80
|
+
const errorMessages = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
|
|
81
|
+
this.conversationHistory.push({ role: "system", content: `
|
|
82
|
+
IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
|
|
83
|
+
${errorMessages}
|
|
84
|
+
|
|
85
|
+
Explain *why* these tools failed. Propose an alternative tool or a revised plan to achieve the goal without these tools, or suggest how to fix the underlying issue. Do NOT generate irrelevant code, random thoughts, or go off-topic. Focus solely on addressing these errors and getting back on track to achieve the user's goal. If you are stuck, consider using the 'user_input' or 'interactive_input' tool to ask the user for clarification.
|
|
86
|
+
` });
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
this.conversationHistory.push({ role: "user", content: "Current Phase: REFLECT. Evaluate if the result moves toward the goal and adjust plan if needed." });
|
|
90
|
+
}
|
|
91
|
+
const reflectResponse = await this.getLLMAction();
|
|
92
|
+
const { thought: reflectThought } = this.parseLLMResponse(reflectResponse);
|
|
93
|
+
logger.thought(reflectThought);
|
|
94
|
+
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: reflectThought }) });
|
|
95
|
+
}
|
|
96
|
+
if (step >= this.maxSteps && finalOutput === null) {
|
|
97
|
+
const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
|
|
98
|
+
logger.error(message);
|
|
99
|
+
finalOutput = message;
|
|
100
|
+
}
|
|
101
|
+
return finalOutput;
|
|
102
|
+
}
|
|
103
|
+
async executeToolCalls(toolCalls, parallel) {
|
|
104
|
+
const executeTool = async (toolCall) => {
|
|
105
|
+
const toolInstance = this.availableTools[toolCall.tool];
|
|
106
|
+
if (!toolInstance) {
|
|
107
|
+
return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
|
|
108
|
+
}
|
|
109
|
+
let toolOutput;
|
|
110
|
+
try {
|
|
111
|
+
logger.toolCall(toolCall.tool, toolCall.parameters);
|
|
112
|
+
if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
|
|
113
|
+
const flowName = toolCall.parameters.flow;
|
|
114
|
+
if (!this.flowRegistry[flowName]) {
|
|
115
|
+
throw new Error(`Flow '${flowName}' not found in registry.`);
|
|
116
|
+
}
|
|
117
|
+
toolCall.parameters.flow = this.flowRegistry[flowName];
|
|
118
|
+
}
|
|
119
|
+
toolInstance.setParams(toolCall.parameters);
|
|
120
|
+
const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
|
|
121
|
+
const toolFlow = new ToolFlowClass(toolInstance);
|
|
122
|
+
if (toolInstance instanceof AsyncNode) {
|
|
123
|
+
toolOutput = await toolFlow.runAsync({});
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
toolOutput = toolFlow.run({});
|
|
127
|
+
}
|
|
128
|
+
logger.toolResult(toolCall.tool, toolOutput);
|
|
129
|
+
if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
|
|
130
|
+
logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
|
|
131
|
+
const summarizeNode = new SummarizeNode();
|
|
132
|
+
summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
|
|
133
|
+
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
134
|
+
toolOutput = await summarizeFlow.runAsync({});
|
|
135
|
+
logger.info(`Summarized to ${toolOutput.length} chars.`);
|
|
136
|
+
}
|
|
137
|
+
return { success: true, output: toolOutput };
|
|
138
|
+
}
|
|
139
|
+
catch (e) {
|
|
140
|
+
return { success: false, error: `Error executing tool '${toolCall.tool}': ${e.message}` };
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
let observations = [];
|
|
144
|
+
if (parallel) {
|
|
145
|
+
const results = await Promise.all(toolCalls.map(executeTool));
|
|
146
|
+
observations = results.map((result, index) => ({
|
|
147
|
+
tool: toolCalls[index].tool,
|
|
148
|
+
parameters: toolCalls[index].parameters,
|
|
149
|
+
...result // Spread success/error and output/error
|
|
150
|
+
}));
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
for (const toolCall of toolCalls) {
|
|
154
|
+
const result = await executeTool(toolCall);
|
|
155
|
+
observations.push({
|
|
156
|
+
tool: toolCall.tool,
|
|
157
|
+
parameters: toolCall.parameters,
|
|
158
|
+
...result // Spread success/error and output/error
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return observations;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function getToolDefinitions(): any[];
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { CodeInterpreterNode } from '../../src/nodes/code_interpreter.js';
|
|
2
|
+
import { DataExtractorNode } from '../../src/nodes/data_extractor.js';
|
|
3
|
+
import { DatabaseNode } from '../../src/nodes/database.js';
|
|
4
|
+
import { EmbeddingNode } from '../../src/nodes/embedding.js';
|
|
5
|
+
import { GISNode } from '../../src/nodes/gis.js';
|
|
6
|
+
import { MemoryNode } from '../../src/nodes/memory.js';
|
|
7
|
+
import { SemanticMemoryNode } from '../../src/nodes/semantic_memory.js';
|
|
8
|
+
import { TransformNode } from '../../src/nodes/transform.js';
|
|
9
|
+
import { PDFProcessorNode } from '../../src/nodes/pdf_processor.js';
|
|
10
|
+
import { SpreadsheetNode } from '../../src/nodes/spreadsheet.js';
|
|
11
|
+
import { DataValidationNode } from '../../src/nodes/data_validation.js';
|
|
12
|
+
import { ShellCommandNode } from '../../src/nodes/shell.js';
|
|
13
|
+
import { ReadFileNode, WriteFileNode, AppendFileNode, ListDirectoryNode } from '../../src/nodes/filesystem.js';
|
|
14
|
+
import { DisplayImageNode } from '../../src/nodes/display_image.js';
|
|
15
|
+
import { HardwareInteractionNode } from '../../src/nodes/hardware_interaction.js';
|
|
16
|
+
import { ImageGalleryNode } from '../../src/nodes/image_gallery.js';
|
|
17
|
+
import { SpeechSynthesisNode } from '../../src/nodes/speech_synthesis.js';
|
|
18
|
+
import { MultimediaProcessingNode } from '../../src/nodes/multimedia_processing.js';
|
|
19
|
+
import { RemoteExecutionNode } from '../../src/nodes/remote_execution.js';
|
|
20
|
+
import { HttpRequestNode } from '../../src/nodes/http.js';
|
|
21
|
+
import { ScrapeURLNode } from '../../src/nodes/webscraper.js';
|
|
22
|
+
import { DuckDuckGoSearchNode, GoogleSearchNode } from '../../src/nodes/search.js';
|
|
23
|
+
import { BrowserControlNode } from '../../src/nodes/browser_control.js';
|
|
24
|
+
import { WebSocketsNode } from '../../src/nodes/websockets.js';
|
|
25
|
+
import { WebHookNode } from '../../src/nodes/webhook.js';
|
|
26
|
+
import { UserInputNode } from '../../src/nodes/user.js';
|
|
27
|
+
import { InteractiveInputNode } from '../../src/nodes/interactive_input.js';
|
|
28
|
+
import { SchedulerNode } from '../../src/nodes/scheduler.js';
|
|
29
|
+
import { SubFlowNode } from '../../src/nodes/subflow.js';
|
|
30
|
+
import { IteratorNode } from '../../src/nodes/iterator.js';
|
|
31
|
+
import { GitNode } from '../../src/nodes/git.js';
|
|
32
|
+
import { HuggingFaceLLMNode, OllamaLLMNode, DeepSeekLLMNode, OpenAILLMNode, GeminiLLMNode } from '../../src/nodes/llm.js';
|
|
33
|
+
import { OpenRouterLLMNode } from '../../src/nodes/openrouter_llm.js';
|
|
34
|
+
import { CreateIssueNode, GetIssueNode } from '../../src/nodes/github.js';
|
|
35
|
+
import { GetTopStoriesNode, GetItemNode } from '../../src/nodes/hackernews.js';
|
|
36
|
+
import { CreateChargeNode, GetBalanceNode } from '../../src/nodes/stripe.js';
|
|
37
|
+
import { SummarizeNode } from '../../src/nodes/summarize.js';
|
|
38
|
+
import { HttpServerNode } from '../../src/nodes/http_server.js';
|
|
39
|
+
import { InteractiveWebviewNode } from '../../src/nodes/interactive_webview.js';
|
|
40
|
+
import { WebviewNode } from '../../src/nodes/webview.js';
|
|
41
|
+
import qflowConfig from '../../qflow.config.js'; // Import the config file
|
|
42
|
+
import path from 'path';
|
|
43
|
+
import { fileURLToPath } from 'url';
|
|
44
|
+
// Get the directory name of the current module
|
|
45
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
46
|
+
const __dirname = path.dirname(__filename);
|
|
47
|
+
const projectRoot = path.resolve(__dirname, '../../'); // Adjust based on actual project structure
|
|
48
|
+
const coreToolClasses = [
|
|
49
|
+
CodeInterpreterNode,
|
|
50
|
+
DataExtractorNode,
|
|
51
|
+
DatabaseNode,
|
|
52
|
+
EmbeddingNode,
|
|
53
|
+
GISNode,
|
|
54
|
+
MemoryNode,
|
|
55
|
+
SemanticMemoryNode,
|
|
56
|
+
TransformNode,
|
|
57
|
+
PDFProcessorNode,
|
|
58
|
+
SpreadsheetNode,
|
|
59
|
+
DataValidationNode,
|
|
60
|
+
ShellCommandNode,
|
|
61
|
+
ReadFileNode,
|
|
62
|
+
WriteFileNode,
|
|
63
|
+
AppendFileNode,
|
|
64
|
+
ListDirectoryNode,
|
|
65
|
+
DisplayImageNode,
|
|
66
|
+
HardwareInteractionNode,
|
|
67
|
+
ImageGalleryNode,
|
|
68
|
+
SpeechSynthesisNode,
|
|
69
|
+
MultimediaProcessingNode,
|
|
70
|
+
RemoteExecutionNode,
|
|
71
|
+
HttpRequestNode,
|
|
72
|
+
ScrapeURLNode,
|
|
73
|
+
DuckDuckGoSearchNode,
|
|
74
|
+
GoogleSearchNode,
|
|
75
|
+
BrowserControlNode,
|
|
76
|
+
WebSocketsNode,
|
|
77
|
+
WebHookNode,
|
|
78
|
+
UserInputNode,
|
|
79
|
+
InteractiveInputNode,
|
|
80
|
+
SchedulerNode,
|
|
81
|
+
SubFlowNode,
|
|
82
|
+
IteratorNode,
|
|
83
|
+
GitNode,
|
|
84
|
+
HuggingFaceLLMNode,
|
|
85
|
+
OllamaLLMNode,
|
|
86
|
+
OpenRouterLLMNode,
|
|
87
|
+
DeepSeekLLMNode,
|
|
88
|
+
OpenAILLMNode,
|
|
89
|
+
GeminiLLMNode,
|
|
90
|
+
CreateIssueNode,
|
|
91
|
+
GetIssueNode,
|
|
92
|
+
GetTopStoriesNode,
|
|
93
|
+
GetItemNode,
|
|
94
|
+
CreateChargeNode,
|
|
95
|
+
GetBalanceNode,
|
|
96
|
+
SummarizeNode,
|
|
97
|
+
HttpServerNode,
|
|
98
|
+
InteractiveWebviewNode,
|
|
99
|
+
WebviewNode,
|
|
100
|
+
];
|
|
101
|
+
let customToolClasses = [];
|
|
102
|
+
// Dynamically import custom nodes from qflow.config.js
|
|
103
|
+
if (qflowConfig.customNodePaths && qflowConfig.customNodePaths.length > 0) {
|
|
104
|
+
for (const nodePath of qflowConfig.customNodePaths) {
|
|
105
|
+
try {
|
|
106
|
+
// Resolve the path relative to the project root
|
|
107
|
+
const absolutePath = path.resolve(projectRoot, nodePath);
|
|
108
|
+
// Dynamic import
|
|
109
|
+
const module = await import(absolutePath);
|
|
110
|
+
// Assuming the node class is the default export or a named export
|
|
111
|
+
// This might need refinement based on how users export their nodes
|
|
112
|
+
for (const key in module) {
|
|
113
|
+
const ExportedClass = module[key];
|
|
114
|
+
if (typeof ExportedClass === 'function' && ExportedClass.prototype instanceof AsyncNode && typeof ExportedClass.getToolDefinition === 'function') {
|
|
115
|
+
customToolClasses.push(ExportedClass);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
console.error(`Failed to load custom node from ${nodePath}:`, error);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export function getToolDefinitions() {
|
|
125
|
+
const definitions = [];
|
|
126
|
+
const allToolClasses = [...coreToolClasses, ...customToolClasses];
|
|
127
|
+
for (const ToolClass of allToolClasses) {
|
|
128
|
+
if (typeof ToolClass.getToolDefinition === 'function') {
|
|
129
|
+
definitions.push(ToolClass.getToolDefinition());
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
// Add special tools that don't directly map to a node
|
|
133
|
+
definitions.push({
|
|
134
|
+
name: "finish",
|
|
135
|
+
description: "Ends agent execution, returns final output.",
|
|
136
|
+
parameters: {
|
|
137
|
+
type: "object",
|
|
138
|
+
properties: {
|
|
139
|
+
output: {
|
|
140
|
+
type: "string",
|
|
141
|
+
description: "A summary of the final result or the reason for stopping."
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
required: ["output"]
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
return definitions;
|
|
148
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function setLogLevel(level: any): void;
|
|
2
|
+
export function log(message: any, nodeLoggingConfig: any, defaultOptions?: {}): void;
|
|
3
|
+
export namespace LogLevel {
|
|
4
|
+
let DEBUG: number;
|
|
5
|
+
let INFO: number;
|
|
6
|
+
let WARN: number;
|
|
7
|
+
let ERROR: number;
|
|
8
|
+
let NONE: number;
|
|
9
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
export const LogLevel = {
|
|
4
|
+
DEBUG: 0,
|
|
5
|
+
INFO: 1,
|
|
6
|
+
WARN: 2,
|
|
7
|
+
ERROR: 3,
|
|
8
|
+
NONE: 4,
|
|
9
|
+
};
|
|
10
|
+
let currentLogLevel = LogLevel.INFO;
|
|
11
|
+
export function setLogLevel(level) {
|
|
12
|
+
currentLogLevel = level;
|
|
13
|
+
}
|
|
14
|
+
// --- Handlers ---
|
|
15
|
+
class ConsoleLogHandler {
|
|
16
|
+
handle(message, level, timestamp) {
|
|
17
|
+
const levelString = Object.keys(LogLevel).find(key => LogLevel[key] === level);
|
|
18
|
+
console.log(`[${timestamp.toISOString()}] [${levelString}]`, message);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const fileHandlers = {};
|
|
22
|
+
class FileLogHandler {
|
|
23
|
+
constructor(filePath) {
|
|
24
|
+
this.filePath = filePath;
|
|
25
|
+
const dir = path.dirname(filePath);
|
|
26
|
+
if (!fs.existsSync(dir)) {
|
|
27
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
handle(message, level, timestamp) {
|
|
31
|
+
const levelString = Object.keys(LogLevel).find(key => LogLevel[key] === level);
|
|
32
|
+
const logMessage = `[${timestamp.toISOString()}] [${levelString}] ${JSON.stringify(message)}\n`;
|
|
33
|
+
fs.appendFileSync(this.filePath, logMessage);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
class EventLogHandler {
|
|
37
|
+
constructor(emitter) {
|
|
38
|
+
this.emitter = emitter;
|
|
39
|
+
}
|
|
40
|
+
handle(message, level, timestamp) {
|
|
41
|
+
if (this.emitter && typeof this.emitter.emit === 'function') {
|
|
42
|
+
this.emitter.emit('log', {
|
|
43
|
+
level: Object.keys(LogLevel).find(key => LogLevel[key] === level),
|
|
44
|
+
message,
|
|
45
|
+
timestamp,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
class RemoteLogHandler {
|
|
51
|
+
constructor(url) {
|
|
52
|
+
this.url = url;
|
|
53
|
+
}
|
|
54
|
+
handle(message, level, timestamp) {
|
|
55
|
+
const levelString = Object.keys(LogLevel).find(key => LogLevel[key] === level);
|
|
56
|
+
const logEntry = {
|
|
57
|
+
timestamp: timestamp.toISOString(),
|
|
58
|
+
level: levelString,
|
|
59
|
+
message: message
|
|
60
|
+
};
|
|
61
|
+
fetch(this.url, {
|
|
62
|
+
method: 'POST',
|
|
63
|
+
headers: { 'Content-Type': 'application/json' },
|
|
64
|
+
body: JSON.stringify(logEntry)
|
|
65
|
+
}).catch(err => console.error(`Failed to send log to ${this.url}`, err));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function log(message, nodeLoggingConfig, defaultOptions = {}) {
|
|
69
|
+
const options = { ...defaultOptions, ...nodeLoggingConfig };
|
|
70
|
+
const { type = 'info', method = 'console', params = {} } = options;
|
|
71
|
+
const level = LogLevel[type.toUpperCase()];
|
|
72
|
+
if (level === undefined || level < currentLogLevel) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const timestamp = new Date();
|
|
76
|
+
switch (method) {
|
|
77
|
+
case 'console':
|
|
78
|
+
new ConsoleLogHandler().handle(message, level, timestamp);
|
|
79
|
+
break;
|
|
80
|
+
case 'file':
|
|
81
|
+
if (!params.filePath) {
|
|
82
|
+
console.error('File logging requires a filePath in params.');
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (!fileHandlers[params.filePath]) {
|
|
86
|
+
fileHandlers[params.filePath] = new FileLogHandler(params.filePath);
|
|
87
|
+
}
|
|
88
|
+
fileHandlers[params.filePath].handle(message, level, timestamp);
|
|
89
|
+
break;
|
|
90
|
+
case 'event':
|
|
91
|
+
if (!params.emitter) {
|
|
92
|
+
console.error('Event logging requires an emitter in params.');
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
new EventLogHandler(params.emitter).handle(message, level, timestamp);
|
|
96
|
+
break;
|
|
97
|
+
case 'remote':
|
|
98
|
+
if (!params.url) {
|
|
99
|
+
console.error('Remote logging requires a url in params.');
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
new RemoteLogHandler(params.url).handle(message, level, timestamp);
|
|
103
|
+
break;
|
|
104
|
+
default:
|
|
105
|
+
console.error(`Invalid log method: ${method}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A specialized DeepSeekLLMNode for use within the AgentNode.
|
|
3
|
+
* It expects the full prompt (conversation history) to be provided directly via setParams.
|
|
4
|
+
*/
|
|
5
|
+
export class AgentDeepSeekLLMNode extends DeepSeekLLMNode {
|
|
6
|
+
execAsync(): Promise<any>;
|
|
7
|
+
postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A specialized OpenAILLMNode for use within the AgentNode.
|
|
11
|
+
* It expects the full prompt (conversation history) to be provided directly via setParams.
|
|
12
|
+
*/
|
|
13
|
+
export class AgentOpenAILLMNode extends OpenAILLMNode {
|
|
14
|
+
postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
|
|
15
|
+
}
|
|
16
|
+
export class AgentGeminiLLMNode extends GeminiLLMNode {
|
|
17
|
+
postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
|
|
18
|
+
}
|
|
19
|
+
export class AgentOllamaLLMNode extends OllamaLLMNode {
|
|
20
|
+
postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
|
|
21
|
+
}
|
|
22
|
+
export class AgentHuggingFaceLLMNode extends HuggingFaceLLMNode {
|
|
23
|
+
preparePrompt(shared: any): void;
|
|
24
|
+
execAsync(prepRes: any, shared: any): Promise<{}>;
|
|
25
|
+
postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
|
|
26
|
+
}
|
|
27
|
+
import { DeepSeekLLMNode } from './llm.js';
|
|
28
|
+
import { OpenAILLMNode } from './llm.js';
|
|
29
|
+
import { GeminiLLMNode } from './llm.js';
|
|
30
|
+
import { OllamaLLMNode } from './llm.js';
|
|
31
|
+
import { HuggingFaceLLMNode } from './llm.js';
|