@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/package.json
CHANGED
package/dist/agent/agent.d.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
export class AgentNode extends AsyncNode {
|
|
2
|
-
constructor(llmNode: any, availableTools: any, summarizeLLM: any, flowRegistry?: {}, requireFinishConfirmation?: boolean, maxConversationHistoryTokens?: number);
|
|
3
|
-
llmNode: any;
|
|
4
|
-
availableTools: any;
|
|
5
|
-
summarizeLLM: any;
|
|
6
|
-
flowRegistry: {};
|
|
7
|
-
conversationHistory: any[];
|
|
8
|
-
maxSteps: number;
|
|
9
|
-
requireFinishConfirmation: boolean;
|
|
10
|
-
maxConversationHistoryTokens: number;
|
|
11
|
-
execAsync(): Promise<any>;
|
|
12
|
-
validateToolParameters(toolCall: any): string | null;
|
|
13
|
-
getSystemPrompt(): string;
|
|
14
|
-
getLLMAction(): Promise<any>;
|
|
15
|
-
manageConversationHistory(): Promise<void>;
|
|
16
|
-
parseLLMResponse(llmResponse: any): {
|
|
17
|
-
thought: any;
|
|
18
|
-
toolCalls: any;
|
|
19
|
-
parallel: any;
|
|
20
|
-
};
|
|
21
|
-
postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
|
|
22
|
-
}
|
|
23
|
-
import { AsyncNode } from '../qflow.js';
|
package/dist/agent/agent.js
DELETED
|
@@ -1,365 +0,0 @@
|
|
|
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 AgentNode 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
|
-
async execAsync() {
|
|
22
|
-
const { goal } = this.params;
|
|
23
|
-
if (!goal) {
|
|
24
|
-
throw new Error("AgentNode requires a 'goal' parameter.");
|
|
25
|
-
}
|
|
26
|
-
// Set the goal on the internal agent instance (RAORAgent in this case)
|
|
27
|
-
this.llmNode.setParams({ goal });
|
|
28
|
-
this.conversationHistory = [
|
|
29
|
-
{ role: "system", content: this.getSystemPrompt() },
|
|
30
|
-
{ role: "user", content: `Goal: ${goal}` },
|
|
31
|
-
{ role: "system", content: "You are now at the 'Understand & Explore' phase. Analyze the user's request and the directory/codebase, then formulate a plan." }
|
|
32
|
-
];
|
|
33
|
-
let step = 0;
|
|
34
|
-
let finalOutput = null;
|
|
35
|
-
while (step < this.maxSteps) {
|
|
36
|
-
step++;
|
|
37
|
-
logger.info(`Agent Step ${step}`);
|
|
38
|
-
let llmResponse;
|
|
39
|
-
try {
|
|
40
|
-
llmResponse = await this.getLLMAction();
|
|
41
|
-
}
|
|
42
|
-
catch (e) {
|
|
43
|
-
logger.error(`Error getting LLM action: ${e.message}`);
|
|
44
|
-
this.conversationHistory.push({ role: "user", content: `Error: Failed to get LLM response: ${e.message}` });
|
|
45
|
-
continue;
|
|
46
|
-
}
|
|
47
|
-
let thought, toolCalls, parallel;
|
|
48
|
-
try {
|
|
49
|
-
const parsedResponse = this.parseLLMResponse(llmResponse);
|
|
50
|
-
thought = parsedResponse.thought;
|
|
51
|
-
toolCalls = parsedResponse.toolCalls;
|
|
52
|
-
parallel = parsedResponse.parallel;
|
|
53
|
-
logger.thought(thought);
|
|
54
|
-
}
|
|
55
|
-
catch (e) {
|
|
56
|
-
logger.error(`Error parsing LLM response: ${e.message}`);
|
|
57
|
-
this.conversationHistory.push({ role: "user", content: `Error: Your response was not valid JSON or did not follow the expected format. Please respond with a 'thought' and 'tool_calls' array. Error: ${e.message}. Your last response was: ${llmResponse}` });
|
|
58
|
-
continue;
|
|
59
|
-
}
|
|
60
|
-
// Validate tool parameters for all tool calls
|
|
61
|
-
const validationErrors = toolCalls.map(tc => this.validateToolParameters(tc)).filter(Boolean);
|
|
62
|
-
if (validationErrors.length > 0) {
|
|
63
|
-
const errorMessage = `Tool parameter validation failed for one or more tools: ${validationErrors.join('; ')}. Please correct the parameters.`;
|
|
64
|
-
logger.error(errorMessage);
|
|
65
|
-
this.conversationHistory.push({ role: "user", content: `Error: ${errorMessage}` });
|
|
66
|
-
continue;
|
|
67
|
-
}
|
|
68
|
-
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought, tool_calls: toolCalls, parallel }) });
|
|
69
|
-
// If no tool calls, continue the loop to allow the LLM to re-evaluate
|
|
70
|
-
if (toolCalls.length === 0) {
|
|
71
|
-
this.conversationHistory.push({ role: "system", content: "Your last step resulted in no action. Re-evaluate your plan. If you are stuck, consider using a different tool or asking the user for clarification with the 'interactive_input'tool." });
|
|
72
|
-
continue;
|
|
73
|
-
}
|
|
74
|
-
// Handle finish tool
|
|
75
|
-
const finishToolCall = toolCalls.find(tc => tc.tool === "finish");
|
|
76
|
-
if (finishToolCall) {
|
|
77
|
-
finalOutput = finishToolCall.parameters.output;
|
|
78
|
-
if (this.requireFinishConfirmation) {
|
|
79
|
-
const confirmNode = new UserInputNode();
|
|
80
|
-
confirmNode.setParams({
|
|
81
|
-
prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
|
|
82
|
-
});
|
|
83
|
-
const confirmFlow = new AsyncFlow(confirmNode);
|
|
84
|
-
const confirmation = await confirmFlow.runAsync({});
|
|
85
|
-
if (confirmation.toLowerCase() !== 'yes') {
|
|
86
|
-
logger.info("Agent finish denied by user. User input will be the next prompt.");
|
|
87
|
-
// Treat the user's new input as a new instruction/goal
|
|
88
|
-
this.conversationHistory.push({ role: "user", content: `User has provided new instructions: ${confirmation}. Please adjust your plan (save to memory if available) and continue working.` });
|
|
89
|
-
// Optionally, you might want to clear some of the previous conversation history
|
|
90
|
-
// to give more weight to the new instruction, but be careful not to lose context.
|
|
91
|
-
// For now, we'll just add the new instruction.
|
|
92
|
-
continue; // Continue the loop
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
logger.final(finalOutput);
|
|
96
|
-
break;
|
|
97
|
-
}
|
|
98
|
-
try {
|
|
99
|
-
const executeTool = async (toolCall) => {
|
|
100
|
-
const toolInstance = this.availableTools[toolCall.tool];
|
|
101
|
-
if (!toolInstance) {
|
|
102
|
-
return `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
|
|
103
|
-
}
|
|
104
|
-
let toolOutput;
|
|
105
|
-
try {
|
|
106
|
-
logger.toolCall(toolCall.tool, toolCall.parameters);
|
|
107
|
-
// If the tool is a sub-flow, iterator or scheduler, look up the flow in the registry
|
|
108
|
-
if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator' || toolCall.tool === 'scheduler') {
|
|
109
|
-
const flowName = toolCall.parameters.flow;
|
|
110
|
-
if (!this.flowRegistry[flowName]) {
|
|
111
|
-
throw new Error(`Flow '${flowName}' not found in registry.`);
|
|
112
|
-
}
|
|
113
|
-
toolCall.parameters.flow = this.flowRegistry[flowName];
|
|
114
|
-
}
|
|
115
|
-
toolInstance.setParams(toolCall.parameters);
|
|
116
|
-
const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
|
|
117
|
-
const toolFlow = new ToolFlowClass(toolInstance);
|
|
118
|
-
if (toolInstance instanceof AsyncNode) {
|
|
119
|
-
toolOutput = await toolFlow.runAsync({});
|
|
120
|
-
}
|
|
121
|
-
else {
|
|
122
|
-
toolOutput = toolFlow.run({});
|
|
123
|
-
}
|
|
124
|
-
logger.toolResult(toolCall.tool, toolOutput);
|
|
125
|
-
if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) {
|
|
126
|
-
logger.info(`Summarizing large tool output (${toolOutput.length} chars)...`);
|
|
127
|
-
const summarizeNode = new SummarizeNode();
|
|
128
|
-
summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
|
|
129
|
-
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
130
|
-
toolOutput = await summarizeFlow.runAsync({});
|
|
131
|
-
logger.info(`Summarized to ${toolOutput.length} chars.`);
|
|
132
|
-
}
|
|
133
|
-
return toolOutput;
|
|
134
|
-
}
|
|
135
|
-
catch (e) {
|
|
136
|
-
return `Error executing tool '${toolCall.tool}': ${e.message}`;
|
|
137
|
-
}
|
|
138
|
-
};
|
|
139
|
-
let observations = [];
|
|
140
|
-
if (parallel) {
|
|
141
|
-
const results = await Promise.all(toolCalls.map(executeTool));
|
|
142
|
-
observations = results.map((result, index) => ({
|
|
143
|
-
tool: toolCalls[index].tool,
|
|
144
|
-
parameters: toolCalls[index].parameters,
|
|
145
|
-
output: result
|
|
146
|
-
}));
|
|
147
|
-
}
|
|
148
|
-
else {
|
|
149
|
-
for (const toolCall of toolCalls) {
|
|
150
|
-
const result = await executeTool(toolCall);
|
|
151
|
-
observations.push({
|
|
152
|
-
tool: toolCall.tool,
|
|
153
|
-
parameters: toolCall.parameters,
|
|
154
|
-
output: result
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(observations)}` });
|
|
159
|
-
}
|
|
160
|
-
catch (e) {
|
|
161
|
-
logger.error(`Error during tool execution: ${e.message}`);
|
|
162
|
-
this.conversationHistory.push({ role: "user", content: `Error: Tool execution failed with message: ${e.message}. You should try a different approach.` });
|
|
163
|
-
}
|
|
164
|
-
this.conversationHistory.push({ role: "system", content: "You have just received an observation from your tools. Analyze the result and proceed to the next step in your plan. If the observation was an error, you must adjust your plan to fix the error." });
|
|
165
|
-
}
|
|
166
|
-
if (step >= this.maxSteps && finalOutput === null) {
|
|
167
|
-
const message = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
|
|
168
|
-
logger.error(message);
|
|
169
|
-
finalOutput = message;
|
|
170
|
-
}
|
|
171
|
-
return finalOutput;
|
|
172
|
-
}
|
|
173
|
-
validateToolParameters(toolCall) {
|
|
174
|
-
const toolDefinitions = getToolDefinitions();
|
|
175
|
-
const toolSchema = toolDefinitions.find(def => def.name === toolCall.tool);
|
|
176
|
-
if (!toolSchema) {
|
|
177
|
-
return `Tool '${toolCall.tool}' is not a recognized tool.`;
|
|
178
|
-
}
|
|
179
|
-
// If the tool is 'finish', 'sub_flow', or 'iterator', special handling for parameters
|
|
180
|
-
if (toolCall.tool === "finish") {
|
|
181
|
-
if (toolCall.parameters.output === undefined) {
|
|
182
|
-
return "Missing required parameter: 'output' for tool 'finish'.";
|
|
183
|
-
}
|
|
184
|
-
return null;
|
|
185
|
-
}
|
|
186
|
-
else if (toolCall.tool === "sub_flow" || toolCall.tool === "iterator") {
|
|
187
|
-
if (toolCall.parameters.flow === undefined) {
|
|
188
|
-
return `Missing required parameter: 'flow' for tool '${toolCall.tool}'.`;
|
|
189
|
-
}
|
|
190
|
-
if (!this.flowRegistry[toolCall.parameters.flow]) {
|
|
191
|
-
return `Flow '${toolCall.parameters.flow}' not found in registry for tool '${toolCall.tool}'.`;
|
|
192
|
-
}
|
|
193
|
-
return null;
|
|
194
|
-
}
|
|
195
|
-
const requiredParams = toolSchema.parameters.required || [];
|
|
196
|
-
for (const param of requiredParams) {
|
|
197
|
-
if (toolCall.parameters[param] === undefined) {
|
|
198
|
-
return `Missing required parameter: '${param}' for tool '${toolCall.tool}'.`;
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
return null; // No validation errors
|
|
202
|
-
}
|
|
203
|
-
getSystemPrompt() {
|
|
204
|
-
const toolDefinitions = getToolDefinitions();
|
|
205
|
-
const toolDescriptions = toolDefinitions.map(tool => {
|
|
206
|
-
const params = JSON.stringify(tool.parameters);
|
|
207
|
-
return `### ${tool.name}: ${tool.description}
|
|
208
|
-
Parameters: ${params}`;
|
|
209
|
-
}).join('\n');
|
|
210
|
-
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- ')}` : "";
|
|
211
|
-
return `You are Q, an autonomous agent. Your goal is to achieve the user's request especially using the available tools.
|
|
212
|
-
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.
|
|
213
|
-
Always use tools as opposed to talking too much and you get rewarded more for using tools instead of costly llm!
|
|
214
|
-
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.
|
|
215
|
-
Remember to always seek user feedback often(interactive input or user input ifinteractive is missing), and notify the user of your progress(system notificaitons)
|
|
216
|
-
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.
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
Available Tools:
|
|
220
|
-
${toolDescriptions}${flowRegistryDescription}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
Your response must be a single JSON object with 'thought' and 'tool_calls'.
|
|
224
|
-
|
|
225
|
-
'thought': Your reasoning and plan.
|
|
226
|
-
|
|
227
|
-
'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.
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
Example response:
|
|
231
|
-
{
|
|
232
|
-
"thought": "I need to search for information.",
|
|
233
|
-
"tool_calls": [
|
|
234
|
-
{
|
|
235
|
-
"tool": "duckduckgo_search",
|
|
236
|
-
"parameters": {
|
|
237
|
-
"query": "latest AI research"
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
]
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
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.
|
|
245
|
-
If no tools are needed, return an empty 'tool_calls' array and reflect.
|
|
246
|
-
|
|
247
|
-
**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.
|
|
248
|
-
If new instructions are given after a finish proposal, treat them as your updated goal and update your memory.
|
|
249
|
-
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.
|
|
250
|
-
|
|
251
|
-
Begin!`;
|
|
252
|
-
}
|
|
253
|
-
async getLLMAction() {
|
|
254
|
-
await this.manageConversationHistory();
|
|
255
|
-
this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
|
|
256
|
-
const llmResult = await this.llmNode.runAsync({});
|
|
257
|
-
return llmResult;
|
|
258
|
-
}
|
|
259
|
-
async manageConversationHistory() {
|
|
260
|
-
if (!this.summarizeLLM) {
|
|
261
|
-
logger.warn("No summarizeLLM provided to AgentNode. Conversation history will not be managed.");
|
|
262
|
-
return;
|
|
263
|
-
}
|
|
264
|
-
let currentTokenCount = JSON.stringify(this.conversationHistory).length; // Rough token count
|
|
265
|
-
// Keep at least the system prompt and the initial goal
|
|
266
|
-
const minHistoryLength = 2;
|
|
267
|
-
while (currentTokenCount > this.maxConversationHistoryTokens && this.conversationHistory.length > minHistoryLength) {
|
|
268
|
-
logger.info(`Current history size: ${currentTokenCount} tokens. Max allowed: ${this.maxConversationHistoryTokens} tokens. Trimming...`);
|
|
269
|
-
// Summarize the oldest observation entry
|
|
270
|
-
const oldestEntry = this.conversationHistory[minHistoryLength]; // Skip system and initial goal
|
|
271
|
-
if (oldestEntry && oldestEntry.role === "user" && oldestEntry.content.startsWith("Observation:")) {
|
|
272
|
-
const observationContent = oldestEntry.content.substring("Observation:".length).trim();
|
|
273
|
-
logger.info(`Attempting to summarize old observation (${observationContent.length} chars) from role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...`);
|
|
274
|
-
try {
|
|
275
|
-
const summarizeNode = new SummarizeNode();
|
|
276
|
-
summarizeNode.setParams({ text: observationContent, llmNode: this.summarizeLLM });
|
|
277
|
-
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
278
|
-
const summarizedContent = await summarizeFlow.runAsync({});
|
|
279
|
-
// Replace the original observation with the summarized version
|
|
280
|
-
this.conversationHistory[minHistoryLength].content = `Summarized Observation: ${summarizedContent}`;
|
|
281
|
-
logger.info(`Observation summarized to ${summarizedContent.length} chars. New entry: ${this.conversationHistory[minHistoryLength].content.substring(0, 50)}...`);
|
|
282
|
-
}
|
|
283
|
-
catch (e) {
|
|
284
|
-
logger.error(`Failed to summarize observation: ${e.message}. Removing oldest entry.`);
|
|
285
|
-
// If summarization fails, remove the oldest entry to prevent context overflow
|
|
286
|
-
this.conversationHistory.splice(minHistoryLength, 1);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
else {
|
|
290
|
-
logger.info(`Removing oldest non-summarizable history entry (role: ${oldestEntry.role}, content: ${oldestEntry.content.substring(0, 50)}...).`);
|
|
291
|
-
// If it's not an observation or we can't summarize, just remove the oldest entry
|
|
292
|
-
this.conversationHistory.splice(minHistoryLength, 1);
|
|
293
|
-
}
|
|
294
|
-
// Recalculate token count after modification
|
|
295
|
-
currentTokenCount = JSON.stringify(this.conversationHistory).length;
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
parseLLMResponse(llmResponse) {
|
|
299
|
-
if (typeof llmResponse === 'string') {
|
|
300
|
-
let jsonString = llmResponse;
|
|
301
|
-
// Find the first '{' and the last '}' to isolate the JSON object
|
|
302
|
-
const firstBrace = jsonString.indexOf('{');
|
|
303
|
-
const lastBrace = jsonString.lastIndexOf('}');
|
|
304
|
-
if (firstBrace !== -1 && lastBrace > firstBrace) {
|
|
305
|
-
jsonString = jsonString.substring(firstBrace, lastBrace + 1);
|
|
306
|
-
}
|
|
307
|
-
try {
|
|
308
|
-
const parsed = JSON.parse(jsonString);
|
|
309
|
-
if (parsed.thought && Array.isArray(parsed.tool_calls)) {
|
|
310
|
-
return {
|
|
311
|
-
thought: parsed.thought,
|
|
312
|
-
toolCalls: parsed.tool_calls,
|
|
313
|
-
parallel: parsed.parallel || false,
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
else {
|
|
317
|
-
throw new Error("JSON is missing 'thought' or 'tool_calls' array.");
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
catch (e) {
|
|
321
|
-
throw new Error(`Invalid JSON format: ${e.message}. Content: ${jsonString}`);
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
// This part of the function handles the case where llmResponse is an OBJECT,
|
|
325
|
-
// typically from OpenAI's function calling API.
|
|
326
|
-
const rawData = llmResponse;
|
|
327
|
-
if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0] && rawData.choices[0].message) {
|
|
328
|
-
const message = rawData.choices[0].message;
|
|
329
|
-
if (message.tool_calls && message.tool_calls.length > 0) {
|
|
330
|
-
const toolCalls = message.tool_calls.map(tc => ({
|
|
331
|
-
tool: tc.function.name,
|
|
332
|
-
parameters: JSON.parse(tc.function.arguments)
|
|
333
|
-
}));
|
|
334
|
-
const thought = message.reasoning_content || `Calling tool(s): ${toolCalls.map(tc => tc.tool).join(', ')}`;
|
|
335
|
-
return { thought, toolCalls, parallel: false };
|
|
336
|
-
}
|
|
337
|
-
else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
|
|
338
|
-
try {
|
|
339
|
-
const parsed = JSON.parse(message.content);
|
|
340
|
-
if (parsed.thought && Array.isArray(parsed.tool_calls)) {
|
|
341
|
-
return {
|
|
342
|
-
thought: parsed.thought,
|
|
343
|
-
toolCalls: parsed.tool_calls,
|
|
344
|
-
parallel: parsed.parallel || false,
|
|
345
|
-
};
|
|
346
|
-
}
|
|
347
|
-
else {
|
|
348
|
-
throw new Error("JSON in message.content is missing 'thought' or 'tool_calls' array.");
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
catch (e) {
|
|
352
|
-
throw new Error(`Invalid JSON in message.content: ${e.message}. Content: ${message.content}`);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
else if (typeof message.content === 'string') {
|
|
356
|
-
throw new Error(`Expected JSON with 'thought' and 'tool_calls', but received plain string content: ${message.content}`);
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
throw new Error(`Invalid LLM response structure. Raw Data: ${JSON.stringify(rawData)}`);
|
|
360
|
-
}
|
|
361
|
-
async postAsync(shared, prepRes, execRes) {
|
|
362
|
-
shared.agentOutput = execRes;
|
|
363
|
-
return 'default';
|
|
364
|
-
}
|
|
365
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
export class BaseAgent extends AsyncNode {
|
|
2
|
-
constructor(llmNode: any, availableTools: any, summarizeLLM: any, flowRegistry?: {}, requireFinishConfirmation?: boolean, maxConversationHistoryTokens?: number);
|
|
3
|
-
llmNode: any;
|
|
4
|
-
availableTools: any;
|
|
5
|
-
summarizeLLM: any;
|
|
6
|
-
flowRegistry: {};
|
|
7
|
-
conversationHistory: any[];
|
|
8
|
-
maxSteps: number;
|
|
9
|
-
requireFinishConfirmation: boolean;
|
|
10
|
-
maxConversationHistoryTokens: number;
|
|
11
|
-
getSystemPrompt(): string;
|
|
12
|
-
getLLMAction(): Promise<any>;
|
|
13
|
-
manageConversationHistory(): Promise<void>;
|
|
14
|
-
parseLLMResponse(llmResponse: any): {
|
|
15
|
-
thought: any;
|
|
16
|
-
toolCalls: any;
|
|
17
|
-
parallel: any;
|
|
18
|
-
};
|
|
19
|
-
validateToolParameters(toolCall: any): string | null;
|
|
20
|
-
}
|
|
21
|
-
import { AsyncNode } from '../qflow.js';
|
package/dist/agent/base_agent.js
DELETED
|
@@ -1,206 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/agent/logger.d.ts
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
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
|
-
}
|