@fractal-solutions/qflow 1.0.59 → 1.0.61
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 +77 -1
- 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,206 @@
|
|
|
1
|
+
import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
|
|
2
|
+
import { UserInputNode } from '../nodes';
|
|
3
|
+
import { getToolDefinitions } from './tools.js';
|
|
4
|
+
import { SummarizeNode } from '../nodes/summarize.js';
|
|
5
|
+
import { logger } from './logger.js';
|
|
6
|
+
export class BaseAgent extends AsyncNode {
|
|
7
|
+
constructor(llmNode, availableTools, summarizeLLM, flowRegistry = {}, requireFinishConfirmation = true, maxConversationHistoryTokens = 100000) {
|
|
8
|
+
super();
|
|
9
|
+
if (!llmNode) {
|
|
10
|
+
throw new Error("AgentNode requires an LLMNode instance for reasoning.");
|
|
11
|
+
}
|
|
12
|
+
this.llmNode = llmNode;
|
|
13
|
+
this.availableTools = availableTools;
|
|
14
|
+
this.summarizeLLM = summarizeLLM;
|
|
15
|
+
this.flowRegistry = flowRegistry;
|
|
16
|
+
this.conversationHistory = [];
|
|
17
|
+
this.maxSteps = 70;
|
|
18
|
+
this.requireFinishConfirmation = requireFinishConfirmation;
|
|
19
|
+
this.maxConversationHistoryTokens = maxConversationHistoryTokens;
|
|
20
|
+
}
|
|
21
|
+
getSystemPrompt() {
|
|
22
|
+
const toolDefinitions = getToolDefinitions();
|
|
23
|
+
const toolDescriptions = toolDefinitions.map(tool => {
|
|
24
|
+
const params = JSON.stringify(tool.parameters);
|
|
25
|
+
return `### ${tool.name}: ${tool.description}
|
|
26
|
+
Parameters: ${params}`;
|
|
27
|
+
}).join('\n');
|
|
28
|
+
const flowRegistryDescription = Object.keys(this.flowRegistry).length > 0 ? `\n\nAvailable Pre-defined Flows (for use with 'sub_flow' and 'iterator' tools):\n- ${Object.keys(this.flowRegistry).join('\n- ')}` : "";
|
|
29
|
+
return `You are Q, an autonomous agent. Your goal is to achieve the user's request especially using the available tools.
|
|
30
|
+
After expounding effectively out your initial plan, make a roadmap, save it in your memory through a memory node using either memory_node or semantic_memory_node (semantic preferred) tools and confirm to the user.
|
|
31
|
+
Always use tools as opposed to talking too much and you get rewarded more for using tools instead of costly llm!
|
|
32
|
+
If you have a plan, you MUST include at least one tool call. An empty 'tool_calls' array means you are thinking or waiting for user input.
|
|
33
|
+
Remember to always seek user feedback often(interactive input or user input ifinteractive is missing), and notify the user of your progress(system notificaitons)
|
|
34
|
+
If the user asks about your capabilities or what tools you have, answer by summarizing the 'Available Tools' section of this prompt. Do not attempt to use a tool to answer such questions.
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
Available Tools:
|
|
38
|
+
${toolDescriptions}${flowRegistryDescription}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
CRITICAL: Your response MUST be a single JSON object. Any deviation will be considered an error. DO NOT generate code, prose, or any other text outside of the JSON structure.
|
|
42
|
+
Your response must be a single JSON object with 'thought' and 'tool_calls'.
|
|
43
|
+
|
|
44
|
+
'thought': Your reasoning and plan.
|
|
45
|
+
|
|
46
|
+
'tool_calls': An array of tool calls. Each tool call has 'tool' (name) and 'parameters' (object). Set 'parallel': true in the top-level JSON for parallel execution.
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
Example response:
|
|
50
|
+
{
|
|
51
|
+
"thought": "I need to search for information.",
|
|
52
|
+
"tool_calls": [
|
|
53
|
+
{
|
|
54
|
+
"tool": "duckduckgo_search",
|
|
55
|
+
"parameters": {
|
|
56
|
+
"query": "latest AI research"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
When the user explicitly indicates they are done, use the 'finish' tool. Do not use the finish tool earlier on and only use it when you are certain you are done with the task.
|
|
64
|
+
If no tools are needed, return an empty 'tool_calls' array and reflect.
|
|
65
|
+
|
|
66
|
+
**IMPORTANT:** If you have a plan that requires action, you MUST include at least one tool call. An empty 'tool_calls' array means no action.
|
|
67
|
+
If new instructions are given after a finish proposal, treat them as your updated goal and update your memory.
|
|
68
|
+
Tell user how far you've gone using system notifications and KEEP THE USER INVOLVED using interactive input (or user input if interactive input not available) and OFTEN CHECK YOUR MEMORY to ensure alignmemt.
|
|
69
|
+
|
|
70
|
+
Begin!`;
|
|
71
|
+
}
|
|
72
|
+
async getLLMAction() {
|
|
73
|
+
await this.manageConversationHistory();
|
|
74
|
+
this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
|
|
75
|
+
const llmResult = await this.llmNode.runAsync({});
|
|
76
|
+
return llmResult;
|
|
77
|
+
}
|
|
78
|
+
async manageConversationHistory() {
|
|
79
|
+
if (!this.summarizeLLM) {
|
|
80
|
+
logger.warn("No summarizeLLM provided to AgentNode. Conversation history will not be managed.");
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
let currentTokenCount = JSON.stringify(this.conversationHistory).length; // Rough token count
|
|
84
|
+
// Keep at least the system prompt and the initial goal
|
|
85
|
+
const minHistoryLength = 2;
|
|
86
|
+
while (currentTokenCount > this.maxConversationHistoryTokens && this.conversationHistory.length > minHistoryLength) {
|
|
87
|
+
logger.info(`Current history size: ${currentTokenCount} tokens. Max allowed: ${this.maxConversationHistoryTokens} tokens. Trimming...`);
|
|
88
|
+
// Summarize the oldest observation entry
|
|
89
|
+
const oldestEntry = this.conversationHistory[minHistoryLength]; // Skip system and initial goal
|
|
90
|
+
if (oldestEntry && oldestEntry.role === "user" && oldestEntry.content.startsWith("Observation:")) {
|
|
91
|
+
const observationContent = oldestEntry.content.substring("Observation:".length).trim();
|
|
92
|
+
logger.info(`Attempting to summarize old observation (${observationContent.length} chars) from role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...`);
|
|
93
|
+
try {
|
|
94
|
+
const summarizeNode = new SummarizeNode();
|
|
95
|
+
summarizeNode.setParams({ text: observationContent, llmNode: this.summarizeLLM });
|
|
96
|
+
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
97
|
+
const summarizedContent = await summarizeFlow.runAsync({});
|
|
98
|
+
// Replace the original observation with the summarized version
|
|
99
|
+
this.conversationHistory[minHistoryLength].content = `Summarized Observation: ${summarizedContent}`;
|
|
100
|
+
logger.info(`Observation summarized to ${summarizedContent.length} chars. New entry: ${this.conversationHistory[minHistoryLength].content.substring(0, 50)}...`);
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
logger.error(`Failed to summarize observation: ${e.message}. Removing oldest entry.`);
|
|
104
|
+
// If summarization fails, remove the oldest entry to prevent context overflow
|
|
105
|
+
this.conversationHistory.splice(minHistoryLength, 1);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
logger.info(`Removing oldest non-summarizable history entry (role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...).`);
|
|
110
|
+
// If it's not an observation or we can't summarize, just remove the oldest entry
|
|
111
|
+
this.conversationHistory.splice(minHistoryLength, 1);
|
|
112
|
+
}
|
|
113
|
+
// Recalculate token count after modification
|
|
114
|
+
currentTokenCount = JSON.stringify(this.conversationHistory).length;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
parseLLMResponse(llmResponse) {
|
|
118
|
+
if (typeof llmResponse === 'string') {
|
|
119
|
+
let jsonString = llmResponse;
|
|
120
|
+
// Find the first '{' and the last '}' to isolate the JSON object
|
|
121
|
+
const firstBrace = jsonString.indexOf('{');
|
|
122
|
+
const lastBrace = jsonString.lastIndexOf('}');
|
|
123
|
+
if (firstBrace !== -1 && lastBrace > firstBrace) {
|
|
124
|
+
jsonString = jsonString.substring(firstBrace, lastBrace + 1);
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
const parsed = JSON.parse(jsonString);
|
|
128
|
+
if (parsed.thought && Array.isArray(parsed.tool_calls)) {
|
|
129
|
+
return {
|
|
130
|
+
thought: parsed.thought,
|
|
131
|
+
toolCalls: parsed.tool_calls,
|
|
132
|
+
parallel: parsed.parallel || false,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
catch (e) {
|
|
137
|
+
// Parsing failed, fall through to treat the original string as a thought.
|
|
138
|
+
}
|
|
139
|
+
// Fallback for plain text responses or malformed JSON.
|
|
140
|
+
return { thought: llmResponse, toolCalls: [], parallel: false };
|
|
141
|
+
}
|
|
142
|
+
// This part of the function handles the case where llmResponse is an OBJECT,
|
|
143
|
+
// typically from OpenAI's function calling API.
|
|
144
|
+
const rawData = llmResponse;
|
|
145
|
+
if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0] && rawData.choices[0].message) {
|
|
146
|
+
const message = rawData.choices[0].message;
|
|
147
|
+
if (message.tool_calls && message.tool_calls.length > 0) {
|
|
148
|
+
const toolCalls = message.tool_calls.map(tc => ({
|
|
149
|
+
tool: tc.function.name,
|
|
150
|
+
parameters: JSON.parse(tc.function.arguments)
|
|
151
|
+
}));
|
|
152
|
+
const thought = message.reasoning_content || `Calling tool(s): ${toolCalls.map(tc => tc.tool).join(', ')}`;
|
|
153
|
+
return { thought, toolCalls, parallel: false };
|
|
154
|
+
}
|
|
155
|
+
else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
|
|
156
|
+
try {
|
|
157
|
+
const parsed = JSON.parse(message.content);
|
|
158
|
+
if (parsed.thought && Array.isArray(parsed.tool_calls)) {
|
|
159
|
+
return {
|
|
160
|
+
thought: parsed.thought,
|
|
161
|
+
toolCalls: parsed.tool_calls,
|
|
162
|
+
parallel: parsed.parallel || false,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
catch (e) {
|
|
167
|
+
throw new Error(`Invalid JSON or unexpected format in message.content: ${e.message}. Content: ${message.content}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
else if (typeof message.content === 'string') {
|
|
171
|
+
return { thought: message.content, toolCalls: [], parallel: false };
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
throw new Error(`Invalid LLM response structure. Raw Data: ${JSON.stringify(rawData)}`);
|
|
175
|
+
}
|
|
176
|
+
validateToolParameters(toolCall) {
|
|
177
|
+
const toolDefinitions = getToolDefinitions();
|
|
178
|
+
const toolSchema = toolDefinitions.find(def => def.name === toolCall.tool);
|
|
179
|
+
if (!toolSchema) {
|
|
180
|
+
return `Tool '${toolCall.tool}' is not a recognized tool.`;
|
|
181
|
+
}
|
|
182
|
+
// If the tool is 'finish', 'sub_flow', or 'iterator', special handling for parameters
|
|
183
|
+
if (toolCall.tool === "finish") {
|
|
184
|
+
if (toolCall.parameters.output === undefined) {
|
|
185
|
+
return "Missing required parameter: 'output' for tool 'finish'.";
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
else if (toolCall.tool === "sub_flow" || toolCall.tool === "iterator") {
|
|
190
|
+
if (toolCall.parameters.flow === undefined) {
|
|
191
|
+
return `Missing required parameter: 'flow' for tool '${toolCall.tool}'.`;
|
|
192
|
+
}
|
|
193
|
+
if (!this.flowRegistry[toolCall.parameters.flow]) {
|
|
194
|
+
return `Flow '${toolCall.parameters.flow}' not found in registry for tool '${toolCall.tool}'.`;
|
|
195
|
+
}
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
const requiredParams = toolSchema.parameters.required || [];
|
|
199
|
+
for (const param of requiredParams) {
|
|
200
|
+
if (toolCall.parameters[param] === undefined) {
|
|
201
|
+
return `Missing required parameter: '${param}' for tool '${toolCall.tool}'.`;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return null; // No validation errors
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export namespace logger {
|
|
2
|
+
function info(message: any): void;
|
|
3
|
+
function warn(message: any): void;
|
|
4
|
+
function thought(message: any): void;
|
|
5
|
+
function toolCall(tool: any, params: any): void;
|
|
6
|
+
function toolResult(tool: any, result: any): void;
|
|
7
|
+
function error(message: any): void;
|
|
8
|
+
function final(message: any): void;
|
|
9
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,178 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
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
|
+
}
|