@fractal-solutions/qflow 1.0.44 → 1.0.46
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/dist/agent/agent.js +11 -5
- package/dist/agent/base_agent.d.ts +21 -0
- package/dist/agent/base_agent.js +206 -0
- package/dist/agent/lpavrl_agent.d.ts +5 -0
- package/dist/agent/lpavrl_agent.js +178 -0
- package/dist/agent/ooda_agent.d.ts +5 -0
- package/dist/agent/ooda_agent.js +167 -0
- package/dist/agent/pema_agent.d.ts +5 -0
- package/dist/agent/pema_agent.js +171 -0
- package/dist/agent/raor_agent.d.ts +5 -0
- package/dist/agent/raor_agent.js +164 -0
- package/dist/agent/tools.d.ts +594 -0
- package/dist/agent/tools.js +67 -0
- package/dist/nodes/index.d.ts +6 -0
- package/dist/nodes/index.js +6 -0
- package/dist/nodes/interactive_input.js +1 -1
- package/dist/nodes/s3.d.ts +6 -0
- package/dist/nodes/s3.js +38 -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
|
+
}
|