@fractal-solutions/qflow 1.0.62 → 1.0.63
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/package.json +1 -1
- package/dist/agent/agent.d.ts +0 -23
- package/dist/agent/agent.js +0 -365
- package/dist/agent/base_agent.d.ts +0 -21
- package/dist/agent/base_agent.js +0 -206
- package/dist/agent/logger.d.ts +0 -9
- package/dist/agent/logger.js +0 -45
- package/dist/agent/lpavrl_agent.d.ts +0 -5
- package/dist/agent/lpavrl_agent.js +0 -178
- package/dist/agent/ooda_agent.d.ts +0 -5
- package/dist/agent/ooda_agent.js +0 -167
- package/dist/agent/pema_agent.d.ts +0 -5
- package/dist/agent/pema_agent.js +0 -171
- package/dist/agent/raor_agent.d.ts +0 -5
- package/dist/agent/raor_agent.js +0 -164
- package/dist/agent/tools.d.ts +0 -5378
- package/dist/agent/tools.js +0 -1174
- package/dist/logger.d.ts +0 -9
- package/dist/logger.js +0 -107
- package/dist/nodes/agent_llm.d.ts +0 -31
- package/dist/nodes/agent_llm.js +0 -302
- package/dist/nodes/browser_control.d.ts +0 -4
- package/dist/nodes/browser_control.js +0 -73
- package/dist/nodes/code_interpreter.d.ts +0 -9
- package/dist/nodes/code_interpreter.js +0 -121
- package/dist/nodes/data_extractor.d.ts +0 -5
- package/dist/nodes/data_extractor.js +0 -81
- package/dist/nodes/data_validation.d.ts +0 -9
- package/dist/nodes/data_validation.js +0 -48
- package/dist/nodes/database.d.ts +0 -6
- package/dist/nodes/database.js +0 -89
- package/dist/nodes/display_image.d.ts +0 -4
- package/dist/nodes/display_image.js +0 -47
- package/dist/nodes/embedding.d.ts +0 -7
- package/dist/nodes/embedding.js +0 -45
- package/dist/nodes/filesystem.d.ts +0 -41
- package/dist/nodes/filesystem.js +0 -88
- package/dist/nodes/gis.d.ts +0 -37
- package/dist/nodes/gis.js +0 -106
- package/dist/nodes/git.d.ts +0 -4
- package/dist/nodes/git.js +0 -55
- package/dist/nodes/github.d.ts +0 -27
- package/dist/nodes/github.js +0 -75
- package/dist/nodes/hackernews.d.ts +0 -19
- package/dist/nodes/hackernews.js +0 -47
- package/dist/nodes/hardware_interaction.d.ts +0 -8
- package/dist/nodes/hardware_interaction.js +0 -98
- package/dist/nodes/http.d.ts +0 -26
- package/dist/nodes/http.js +0 -67
- package/dist/nodes/http_server.d.ts +0 -17
- package/dist/nodes/http_server.js +0 -190
- package/dist/nodes/image_gallery.d.ts +0 -8
- package/dist/nodes/image_gallery.js +0 -100
- package/dist/nodes/index.d.ts +0 -48
- package/dist/nodes/index.js +0 -48
- package/dist/nodes/interactive_input.d.ts +0 -4
- package/dist/nodes/interactive_input.js +0 -71
- package/dist/nodes/interactive_webview.d.ts +0 -19
- package/dist/nodes/interactive_webview.js +0 -310
- package/dist/nodes/iterator.d.ts +0 -5
- package/dist/nodes/iterator.js +0 -23
- package/dist/nodes/llm.d.ts +0 -18
- package/dist/nodes/llm.js +0 -215
- package/dist/nodes/memory.d.ts +0 -12
- package/dist/nodes/memory.js +0 -48
- package/dist/nodes/multimedia_processing.d.ts +0 -10
- package/dist/nodes/multimedia_processing.js +0 -80
- package/dist/nodes/openrouter_llm.d.ts +0 -8
- package/dist/nodes/openrouter_llm.js +0 -124
- package/dist/nodes/pdf_processor.d.ts +0 -4
- package/dist/nodes/pdf_processor.js +0 -75
- package/dist/nodes/remote_execution.d.ts +0 -4
- package/dist/nodes/remote_execution.js +0 -83
- package/dist/nodes/s3.d.ts +0 -6
- package/dist/nodes/s3.js +0 -38
- package/dist/nodes/scheduler.d.ts +0 -20
- package/dist/nodes/scheduler.js +0 -98
- package/dist/nodes/search.d.ts +0 -25
- package/dist/nodes/search.js +0 -78
- package/dist/nodes/semantic_memory.d.ts +0 -17
- package/dist/nodes/semantic_memory.js +0 -111
- package/dist/nodes/shell.d.ts +0 -11
- package/dist/nodes/shell.js +0 -29
- package/dist/nodes/speech_synthesis.d.ts +0 -45
- package/dist/nodes/speech_synthesis.js +0 -142
- package/dist/nodes/spreadsheet.d.ts +0 -10
- package/dist/nodes/spreadsheet.js +0 -241
- package/dist/nodes/stripe.d.ts +0 -23
- package/dist/nodes/stripe.js +0 -69
- package/dist/nodes/subflow.d.ts +0 -5
- package/dist/nodes/subflow.js +0 -16
- package/dist/nodes/summarize.d.ts +0 -12
- package/dist/nodes/summarize.js +0 -31
- package/dist/nodes/system_notification.d.ts +0 -4
- package/dist/nodes/system_notification.js +0 -50
- package/dist/nodes/transform.d.ts +0 -5
- package/dist/nodes/transform.js +0 -32
- package/dist/nodes/user.d.ts +0 -11
- package/dist/nodes/user.js +0 -32
- package/dist/nodes/webhook.d.ts +0 -15
- package/dist/nodes/webhook.js +0 -125
- package/dist/nodes/webscraper.d.ts +0 -11
- package/dist/nodes/webscraper.js +0 -33
- package/dist/nodes/websockets.d.ts +0 -4
- package/dist/nodes/websockets.js +0 -73
- package/dist/nodes/webview.d.ts +0 -12
- package/dist/nodes/webview.js +0 -27
- package/dist/qflow.d.ts +0 -69
- package/dist/qflow.js +0 -320
package/dist/agent/logger.js
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
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
|
-
warn: (message) => console.log(colorize(`[WARN] ${message}`, colors.yellow)),
|
|
16
|
-
thought: (message) => {
|
|
17
|
-
console.log("---------------------");
|
|
18
|
-
console.log(colorize("🤔 Thought", colors.yellow));
|
|
19
|
-
console.log(colorize(message, colors.grey));
|
|
20
|
-
console.log("---------------------");
|
|
21
|
-
},
|
|
22
|
-
toolCall: (tool, params) => {
|
|
23
|
-
console.log(colorize("\n🛠️ Tool Call", colors.green));
|
|
24
|
-
console.log(colorize(`Tool: ${tool}`, colors.magenta));
|
|
25
|
-
console.log(colorize(`Params: ${JSON.stringify(params, null, 2)}`, colors.magenta));
|
|
26
|
-
console.log("---------------------");
|
|
27
|
-
},
|
|
28
|
-
toolResult: (tool, result) => {
|
|
29
|
-
console.log(colorize("\n✅ Tool Result", colors.green));
|
|
30
|
-
console.log(colorize(`Tool: ${tool}`, colors.magenta));
|
|
31
|
-
console.log(colorize(`Result: ${JSON.stringify(result, null, 2)}`, colors.grey));
|
|
32
|
-
console.log("---------------------");
|
|
33
|
-
},
|
|
34
|
-
error: (message) => {
|
|
35
|
-
console.log(colorize("\n❌ Error", colors.red));
|
|
36
|
-
console.log(colorize(message, colors.red));
|
|
37
|
-
console.log("---------------------");
|
|
38
|
-
},
|
|
39
|
-
final: (message) => {
|
|
40
|
-
console.log("\n---------------------");
|
|
41
|
-
console.log(colorize("🎉 Final Output", colors.yellow));
|
|
42
|
-
console.log(colorize(message, colors.cyan));
|
|
43
|
-
console.log("---------------------");
|
|
44
|
-
}
|
|
45
|
-
};
|
|
@@ -1,178 +0,0 @@
|
|
|
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 LPAVRLAgent extends BaseAgent {
|
|
6
|
-
async execAsync() {
|
|
7
|
-
const { goal } = this.params;
|
|
8
|
-
if (!goal) {
|
|
9
|
-
throw new Error("LPAVRLAgent 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
|
-
// Listen
|
|
21
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: LISTEN. Understand the user’s current request and context." });
|
|
22
|
-
const listenResponse = await this.getLLMAction();
|
|
23
|
-
const { thought: listenThought } = this.parseLLMResponse(listenResponse);
|
|
24
|
-
logger.thought(listenThought);
|
|
25
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: listenThought }) });
|
|
26
|
-
// Plan
|
|
27
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: PLAN. Break it into steps with rationale." });
|
|
28
|
-
const planResponse = await this.getLLMAction();
|
|
29
|
-
let parsedPlanResponse;
|
|
30
|
-
try {
|
|
31
|
-
parsedPlanResponse = this.parseLLMResponse(planResponse);
|
|
32
|
-
}
|
|
33
|
-
catch (e) {
|
|
34
|
-
logger.error(`Error parsing LLM response in Plan phase: ${e.message}`);
|
|
35
|
-
this.conversationHistory.push({ role: "user", content: `
|
|
36
|
-
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` });
|
|
37
|
-
continue; // Re-run the loop to allow the LLM to correct itself
|
|
38
|
-
}
|
|
39
|
-
const { thought: planThought, toolCalls, parallel } = parsedPlanResponse;
|
|
40
|
-
logger.thought(planThought);
|
|
41
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: planThought, tool_calls: toolCalls, parallel }) });
|
|
42
|
-
// Validate tool parameters for all tool calls
|
|
43
|
-
const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
|
|
44
|
-
if (validationErrors.length > 0) {
|
|
45
|
-
const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
|
|
46
|
-
logger.error(errorMessage);
|
|
47
|
-
this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
|
|
48
|
-
continue; // Re-run the loop to allow the LLM to correct itself
|
|
49
|
-
}
|
|
50
|
-
// Handle finish tool (check here before acting)
|
|
51
|
-
const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
|
|
52
|
-
if (finishToolCall) {
|
|
53
|
-
finalOutput = finishToolCall.parameters.output;
|
|
54
|
-
if (this.requireFinishConfirmation) {
|
|
55
|
-
const confirmNode = new UserInputNode();
|
|
56
|
-
confirmNode.setParams({
|
|
57
|
-
prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
|
|
58
|
-
});
|
|
59
|
-
const confirmFlow = new AsyncFlow(confirmNode);
|
|
60
|
-
const confirmation = await confirmFlow.runAsync({});
|
|
61
|
-
if (confirmation.toLowerCase() !== 'yes') {
|
|
62
|
-
logger.info("Agent finish denied by user. User input will be the next prompt.");
|
|
63
|
-
this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
|
|
64
|
-
continue; // Continue the loop
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
logger.final(finalOutput);
|
|
68
|
-
break; // Exit the main loop as agent is finished
|
|
69
|
-
}
|
|
70
|
-
// If no tool calls and not trying to finish, prompt LLM to generate tool calls
|
|
71
|
-
if (toolCalls.length === 0) {
|
|
72
|
-
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." });
|
|
73
|
-
continue; // Re-run the loop to force tool call generation
|
|
74
|
-
}
|
|
75
|
-
// Act
|
|
76
|
-
const observations = await this.executeToolCalls(toolCalls, parallel);
|
|
77
|
-
this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
|
|
78
|
-
// Check for tool errors and add specific instructions for reflection
|
|
79
|
-
const toolErrors = observations.filter(obs => obs.success === false);
|
|
80
|
-
if (toolErrors.length > 0) {
|
|
81
|
-
const errorMessages = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
|
|
82
|
-
this.conversationHistory.push({ role: "system", content: `
|
|
83
|
-
IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
|
|
84
|
-
${errorMessages}
|
|
85
|
-
|
|
86
|
-
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.
|
|
87
|
-
` });
|
|
88
|
-
}
|
|
89
|
-
else {
|
|
90
|
-
// Visualize
|
|
91
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: VISUALIZE. Present progress or results in an understandable form." });
|
|
92
|
-
}
|
|
93
|
-
const visualizeResponse = await this.getLLMAction();
|
|
94
|
-
const { thought: visualizeThought } = this.parseLLMResponse(visualizeResponse);
|
|
95
|
-
logger.thought(visualizeThought);
|
|
96
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: visualizeThought }) });
|
|
97
|
-
// Reflect
|
|
98
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: REFLECT. Judge results and align with the original intent." });
|
|
99
|
-
const reflectResponse = await this.getLLMAction();
|
|
100
|
-
const { thought: reflectThought } = this.parseLLMResponse(reflectResponse);
|
|
101
|
-
logger.thought(reflectThought);
|
|
102
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: reflectThought }) });
|
|
103
|
-
// Learn
|
|
104
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: LEARN. Update knowledge or strategy for future tasks." });
|
|
105
|
-
const learnResponse = await this.getLLMAction();
|
|
106
|
-
const { thought: learnThought } = this.parseLLMResponse(learnResponse);
|
|
107
|
-
logger.thought(learnThought);
|
|
108
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: learnThought }) });
|
|
109
|
-
}
|
|
110
|
-
if (step >= this.maxSteps && finalOutput === null) {
|
|
111
|
-
const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
|
|
112
|
-
logger.error(message);
|
|
113
|
-
finalOutput = message;
|
|
114
|
-
}
|
|
115
|
-
return finalOutput;
|
|
116
|
-
}
|
|
117
|
-
async executeToolCalls(toolCalls, parallel) {
|
|
118
|
-
const executeTool = async (toolCall) => {
|
|
119
|
-
const toolInstance = this.availableTools[toolCall.tool];
|
|
120
|
-
if (!toolInstance) {
|
|
121
|
-
return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
|
|
122
|
-
}
|
|
123
|
-
let toolOutput;
|
|
124
|
-
try {
|
|
125
|
-
logger.toolCall(toolCall.tool, toolCall.parameters);
|
|
126
|
-
if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
|
|
127
|
-
const flowName = toolCall.parameters.flow;
|
|
128
|
-
if (!this.flowRegistry[flowName]) {
|
|
129
|
-
throw new Error(`Flow '${flowName}' not found in registry.`);
|
|
130
|
-
}
|
|
131
|
-
toolCall.parameters.flow = this.flowRegistry[flowName];
|
|
132
|
-
}
|
|
133
|
-
toolInstance.setParams(toolCall.parameters);
|
|
134
|
-
const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
|
|
135
|
-
const toolFlow = new ToolFlowClass(toolInstance);
|
|
136
|
-
if (toolInstance instanceof AsyncNode) {
|
|
137
|
-
toolOutput = await toolFlow.runAsync({});
|
|
138
|
-
}
|
|
139
|
-
else {
|
|
140
|
-
toolOutput = toolFlow.run({});
|
|
141
|
-
}
|
|
142
|
-
logger.toolResult(toolCall.tool, toolOutput);
|
|
143
|
-
if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
|
|
144
|
-
logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
|
|
145
|
-
const summarizeNode = new SummarizeNode();
|
|
146
|
-
summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
|
|
147
|
-
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
148
|
-
toolOutput = await summarizeFlow.runAsync({});
|
|
149
|
-
logger.info(`Summarized to ${toolOutput.length} chars.`);
|
|
150
|
-
}
|
|
151
|
-
return { success: true, output: toolOutput };
|
|
152
|
-
}
|
|
153
|
-
catch (e) {
|
|
154
|
-
return { success: false, error: `Error executing tool '${toolCall.tool}': ${e.message}` };
|
|
155
|
-
}
|
|
156
|
-
};
|
|
157
|
-
let observations = [];
|
|
158
|
-
if (parallel) {
|
|
159
|
-
const results = await Promise.all(toolCalls.map(executeTool));
|
|
160
|
-
observations = results.map((result, index) => ({
|
|
161
|
-
tool: toolCalls[index].tool,
|
|
162
|
-
parameters: toolCalls[index].parameters,
|
|
163
|
-
...result // Spread success/error and output/error
|
|
164
|
-
}));
|
|
165
|
-
}
|
|
166
|
-
else {
|
|
167
|
-
for (const toolCall of toolCalls) {
|
|
168
|
-
const result = await executeTool(toolCall);
|
|
169
|
-
observations.push({
|
|
170
|
-
tool: toolCall.tool,
|
|
171
|
-
parameters: toolCall.parameters,
|
|
172
|
-
...result // Spread success/error and output/error
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
return observations;
|
|
177
|
-
}
|
|
178
|
-
}
|
package/dist/agent/ooda_agent.js
DELETED
|
@@ -1,167 +0,0 @@
|
|
|
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 OODAAgent extends BaseAgent {
|
|
6
|
-
async execAsync() {
|
|
7
|
-
const { goal } = this.params;
|
|
8
|
-
if (!goal) {
|
|
9
|
-
throw new Error("OODAAgent 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
|
-
// Observe
|
|
21
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: OBSERVE. Summarize the latest data from the environment." });
|
|
22
|
-
const observeResponse = await this.getLLMAction();
|
|
23
|
-
const { thought: observeThought } = this.parseLLMResponse(observeResponse);
|
|
24
|
-
logger.thought(observeThought);
|
|
25
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: observeThought }) });
|
|
26
|
-
// Orient
|
|
27
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: ORIENT. Interpret data in context of history and goal." });
|
|
28
|
-
const orientResponse = await this.getLLMAction();
|
|
29
|
-
const { thought: orientThought } = this.parseLLMResponse(orientResponse);
|
|
30
|
-
logger.thought(orientThought);
|
|
31
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: orientThought }) });
|
|
32
|
-
// Decide
|
|
33
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: DECIDE. Select the best action now." });
|
|
34
|
-
const decideResponse = await this.getLLMAction();
|
|
35
|
-
let parsedDecideResponse;
|
|
36
|
-
try {
|
|
37
|
-
parsedDecideResponse = this.parseLLMResponse(decideResponse);
|
|
38
|
-
}
|
|
39
|
-
catch (e) {
|
|
40
|
-
logger.error(`Error parsing LLM response in Decide phase: ${e.message}`);
|
|
41
|
-
this.conversationHistory.push({ role: "user", content: `
|
|
42
|
-
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${decideResponse}\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` });
|
|
43
|
-
continue; // Re-run the loop to allow the LLM to correct itself
|
|
44
|
-
}
|
|
45
|
-
const { thought: decideThought, toolCalls, parallel } = parsedDecideResponse;
|
|
46
|
-
logger.thought(decideThought);
|
|
47
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought: decideThought, tool_calls: toolCalls, parallel }) });
|
|
48
|
-
// Validate tool parameters for all tool calls
|
|
49
|
-
const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
|
|
50
|
-
if (validationErrors.length > 0) {
|
|
51
|
-
const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
|
|
52
|
-
logger.error(errorMessage);
|
|
53
|
-
this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
|
|
54
|
-
continue; // Re-run the loop to allow the LLM to correct itself
|
|
55
|
-
}
|
|
56
|
-
// Handle finish tool (check here before acting)
|
|
57
|
-
const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
|
|
58
|
-
if (finishToolCall) {
|
|
59
|
-
finalOutput = finishToolCall.parameters.output;
|
|
60
|
-
if (this.requireFinishConfirmation) {
|
|
61
|
-
const confirmNode = new UserInputNode();
|
|
62
|
-
confirmNode.setParams({
|
|
63
|
-
prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
|
|
64
|
-
});
|
|
65
|
-
const confirmFlow = new AsyncFlow(confirmNode);
|
|
66
|
-
const confirmation = await confirmFlow.runAsync({});
|
|
67
|
-
if (confirmation.toLowerCase() !== 'yes') {
|
|
68
|
-
logger.info("Agent finish denied by user. User input will be the next prompt.");
|
|
69
|
-
this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan and continue working.` });
|
|
70
|
-
continue; // Continue the loop
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
logger.final(finalOutput);
|
|
74
|
-
break; // Exit the main loop as agent is finished
|
|
75
|
-
}
|
|
76
|
-
// If no tool calls and not trying to finish, prompt LLM to generate tool calls
|
|
77
|
-
if (toolCalls.length === 0) {
|
|
78
|
-
this.conversationHistory.push({ role: "user", content: "Current Phase: DECIDE. 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." });
|
|
79
|
-
continue; // Re-run the loop to force tool call generation
|
|
80
|
-
}
|
|
81
|
-
// Act
|
|
82
|
-
const observations = await this.executeToolCalls(toolCalls, parallel);
|
|
83
|
-
this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
|
|
84
|
-
// Check for tool errors and add specific instructions for reflection
|
|
85
|
-
const toolErrors = observations.filter(obs => obs.success === false);
|
|
86
|
-
if (toolErrors.length > 0) {
|
|
87
|
-
const errorMessages = toolErrors.map(err => `Tool: ${err.tool}, Parameters: ${JSON.stringify(err.parameters)}, Error: ${err.error}`).join('\n');
|
|
88
|
-
this.conversationHistory.push({ role: "system", content: `
|
|
89
|
-
IMPORTANT: One or more tool calls failed. Analyze the following errors carefully:
|
|
90
|
-
${errorMessages}
|
|
91
|
-
|
|
92
|
-
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.
|
|
93
|
-
` });
|
|
94
|
-
}
|
|
95
|
-
else {
|
|
96
|
-
// No specific reflect phase for OODA after act, it loops back to observe
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
if (step >= this.maxSteps && finalOutput === null) {
|
|
100
|
-
const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
|
|
101
|
-
logger.error(message);
|
|
102
|
-
finalOutput = message;
|
|
103
|
-
}
|
|
104
|
-
return finalOutput;
|
|
105
|
-
}
|
|
106
|
-
async executeToolCalls(toolCalls, parallel) {
|
|
107
|
-
const executeTool = async (toolCall) => {
|
|
108
|
-
const toolInstance = this.availableTools[toolCall.tool];
|
|
109
|
-
if (!toolInstance) {
|
|
110
|
-
return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
|
|
111
|
-
}
|
|
112
|
-
let toolOutput;
|
|
113
|
-
try {
|
|
114
|
-
logger.toolCall(toolCall.tool, toolCall.parameters);
|
|
115
|
-
if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
|
|
116
|
-
const flowName = toolCall.parameters.flow;
|
|
117
|
-
if (!this.flowRegistry[flowName]) {
|
|
118
|
-
throw new Error(`Flow '${flowName}' not found in registry.`);
|
|
119
|
-
}
|
|
120
|
-
toolCall.parameters.flow = this.flowRegistry[flowName];
|
|
121
|
-
}
|
|
122
|
-
toolInstance.setParams(toolCall.parameters);
|
|
123
|
-
const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
|
|
124
|
-
const toolFlow = new ToolFlowClass(toolInstance);
|
|
125
|
-
if (toolInstance instanceof AsyncNode) {
|
|
126
|
-
toolOutput = await toolFlow.runAsync({});
|
|
127
|
-
}
|
|
128
|
-
else {
|
|
129
|
-
toolOutput = toolFlow.run({});
|
|
130
|
-
}
|
|
131
|
-
logger.toolResult(toolCall.tool, toolOutput);
|
|
132
|
-
if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
|
|
133
|
-
logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
|
|
134
|
-
const summarizeNode = new SummarizeNode();
|
|
135
|
-
summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
|
|
136
|
-
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
137
|
-
toolOutput = await summarizeFlow.runAsync({});
|
|
138
|
-
logger.info(`Summarized to ${toolOutput.length} chars.`);
|
|
139
|
-
}
|
|
140
|
-
return { success: true, output: toolOutput };
|
|
141
|
-
}
|
|
142
|
-
catch (e) {
|
|
143
|
-
return { success: false, error: `Error executing tool '${toolCall.tool}': ${e.message}` };
|
|
144
|
-
}
|
|
145
|
-
};
|
|
146
|
-
let observations = [];
|
|
147
|
-
if (parallel) {
|
|
148
|
-
const results = await Promise.all(toolCalls.map(executeTool));
|
|
149
|
-
observations = results.map((result, index) => ({
|
|
150
|
-
tool: toolCalls[index].tool,
|
|
151
|
-
parameters: toolCalls[index].parameters,
|
|
152
|
-
...result // Spread success/error and output/error
|
|
153
|
-
}));
|
|
154
|
-
}
|
|
155
|
-
else {
|
|
156
|
-
for (const toolCall of toolCalls) {
|
|
157
|
-
const result = await executeTool(toolCall);
|
|
158
|
-
observations.push({
|
|
159
|
-
tool: toolCall.tool,
|
|
160
|
-
parameters: toolCall.parameters,
|
|
161
|
-
...result // Spread success/error and output/error
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
return observations;
|
|
166
|
-
}
|
|
167
|
-
}
|
package/dist/agent/pema_agent.js
DELETED
|
@@ -1,171 +0,0 @@
|
|
|
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
|
-
}
|