@fractal-solutions/qflow 1.0.18 → 1.0.20
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 +1 -12
- package/dist/agent/agent.d.ts +14 -0
- package/dist/agent/agent.js +133 -0
- package/dist/agent/tools.d.ts +923 -0
- package/dist/agent/tools.js +427 -0
- package/dist/nodes/agent_llm.d.ts +23 -0
- package/dist/nodes/agent_llm.js +220 -0
- package/dist/nodes/code_interpreter.d.ts +9 -0
- package/dist/nodes/code_interpreter.js +115 -0
- package/dist/nodes/data_extractor.d.ts +5 -0
- package/dist/nodes/data_extractor.js +80 -0
- package/dist/nodes/embedding.d.ts +7 -0
- package/dist/nodes/embedding.js +44 -0
- package/dist/nodes/filesystem.d.ts +41 -0
- package/dist/nodes/filesystem.js +87 -0
- package/dist/nodes/http.d.ts +26 -0
- package/dist/nodes/http.js +66 -0
- package/dist/nodes/index.d.ts +15 -0
- package/dist/nodes/index.js +15 -0
- package/dist/nodes/llm.d.ts +6 -2
- package/dist/nodes/llm.js +47 -5
- package/dist/nodes/memory.d.ts +12 -0
- package/dist/nodes/memory.js +48 -0
- package/dist/nodes/search.d.ts +25 -0
- package/dist/nodes/search.js +77 -0
- package/dist/nodes/semantic_memory.d.ts +17 -0
- package/dist/nodes/semantic_memory.js +110 -0
- package/dist/nodes/shell.d.ts +11 -0
- package/dist/nodes/shell.js +29 -0
- package/dist/nodes/summarize.d.ts +12 -0
- package/dist/nodes/summarize.js +30 -0
- package/dist/nodes/transform.d.ts +5 -0
- package/dist/nodes/transform.js +31 -0
- package/dist/nodes/user.d.ts +11 -0
- package/dist/nodes/user.js +30 -0
- package/dist/nodes/webscraper.d.ts +1 -1
- package/dist/nodes/webscraper.js +7 -3
- package/dist/qflow.js +4 -12
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -132,7 +132,7 @@ The examples in [Basic Usage & Examples](#basic-usage--examples) below will cove
|
|
|
132
132
|
* [**Semantic Memory:**](#19-semantic-memory-node) For storing and retrieving memories based on semantic similarity (RAG) using Ollama.
|
|
133
133
|
* [**Memory:**](#15-memory-node-lightweight-rag) For lightweight, keyword-based long-term memory and 'RAG' (lightweight, dependency free option).
|
|
134
134
|
* [**Transform:**](#16-transform-node) For dynamic data manipulation and reformatting.
|
|
135
|
-
* [**CodeInterpreter:**](#14-code-interpreter-example) For executing dynamic code (in Python) within the workflow.
|
|
135
|
+
* [**CodeInterpreter:**](#14-code-interpreter-example) For executing dynamic code (in Python) within the workflow. Specific instructions on library use in [matplotlib example](#17-plotting-data-with-python-code-interpreter).
|
|
136
136
|
* [**Interactive Agent:**](#12-interactive-agent-example) An agent that takes a goal from user input and uses its tools to achieve it.
|
|
137
137
|
* [**Shell:**](#8-shell-command-example) For system-level interaction and execution.
|
|
138
138
|
* [**HTTP:**](#10-generic-http-request-example) For universal API access.
|
|
@@ -1009,17 +1009,6 @@ Follow these steps in *your project folder* where you are using `qflow`:
|
|
|
1009
1009
|
```
|
|
1010
1010
|
*Note: If you are not using Bun (which loads `.env` files by default), you might need a library like `dotenv` (e.g., `require('dotenv').config();`) in your application to load environment variables from the `.env` file.*
|
|
1011
1011
|
|
|
1012
|
-
If you use a Python virtual environment, you can specify its Python executable via an environment variable.
|
|
1013
|
-
|
|
1014
|
-
```bash
|
|
1015
|
-
# Example for installing matplotlib (preferably in a virtual environment)
|
|
1016
|
-
pip install matplotlib
|
|
1017
|
-
|
|
1018
|
-
# Example for setting the environment variable (if using a virtual environment)
|
|
1019
|
-
export QFLOW_PYTHON_INTERPRETER=/path/to/your/venv/bin/python
|
|
1020
|
-
# Or for Windows PowerShell
|
|
1021
|
-
# $env:QFLOW_PYTHON_INTERPRETER="C:\path\to\your\venv\Scripts\python.exe"
|
|
1022
|
-
```
|
|
1023
1012
|
|
|
1024
1013
|
```javascript
|
|
1025
1014
|
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export class AgentNode extends AsyncNode {
|
|
2
|
+
constructor(llmNode: any, availableTools: any, summarizeLLM: any);
|
|
3
|
+
llmNode: any;
|
|
4
|
+
availableTools: any;
|
|
5
|
+
summarizeLLM: any;
|
|
6
|
+
conversationHistory: any[];
|
|
7
|
+
maxSteps: number;
|
|
8
|
+
execAsync(): Promise<any>;
|
|
9
|
+
getSystemPrompt(): string;
|
|
10
|
+
getLLMAction(): Promise<any>;
|
|
11
|
+
parseLLMResponse(llmResponse: any): any;
|
|
12
|
+
postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
|
|
13
|
+
}
|
|
14
|
+
import { AsyncNode } from '../qflow.js';
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
|
|
2
|
+
import { getToolDefinitions } from './tools.js';
|
|
3
|
+
import { SummarizeNode } from '../nodes/summarize.js'; // Import SummarizeNode
|
|
4
|
+
export class AgentNode extends AsyncNode {
|
|
5
|
+
constructor(llmNode, availableTools, summarizeLLM) {
|
|
6
|
+
super();
|
|
7
|
+
if (!llmNode) {
|
|
8
|
+
throw new Error("AgentNode requires an LLMNode instance for reasoning.");
|
|
9
|
+
}
|
|
10
|
+
this.llmNode = llmNode;
|
|
11
|
+
this.availableTools = availableTools; // Map of tool_name -> qflow_node_instance
|
|
12
|
+
this.summarizeLLM = summarizeLLM; // LLM for summarization
|
|
13
|
+
this.conversationHistory = [];
|
|
14
|
+
this.maxSteps = 10; // Limit to prevent infinite loops
|
|
15
|
+
}
|
|
16
|
+
async execAsync() {
|
|
17
|
+
const { goal } = this.params;
|
|
18
|
+
if (!goal) {
|
|
19
|
+
throw new Error("AgentNode requires a 'goal' parameter.");
|
|
20
|
+
}
|
|
21
|
+
this.conversationHistory = [
|
|
22
|
+
{ role: "system", content: this.getSystemPrompt() },
|
|
23
|
+
{ role: "user", content: `Goal: ${goal}` }
|
|
24
|
+
];
|
|
25
|
+
let step = 0;
|
|
26
|
+
let finalOutput = null;
|
|
27
|
+
while (step < this.maxSteps) {
|
|
28
|
+
step++;
|
|
29
|
+
console.log(`\n--- Agent Step ${step} ---`);
|
|
30
|
+
// 1. Reason: Get LLM's next action
|
|
31
|
+
let llmResponse;
|
|
32
|
+
try {
|
|
33
|
+
llmResponse = await this.getLLMAction();
|
|
34
|
+
console.log(`LLM Raw Response: ${llmResponse}`);
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
console.error("Error getting LLM action:", e.message);
|
|
38
|
+
this.conversationHistory.push({ role: "user", content: `Error: Failed to get LLM response: ${e.message}` });
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
let thought, toolCall;
|
|
42
|
+
try {
|
|
43
|
+
const parsedResponse = this.parseLLMResponse(llmResponse);
|
|
44
|
+
thought = parsedResponse.thought;
|
|
45
|
+
toolCall = parsedResponse.tool;
|
|
46
|
+
}
|
|
47
|
+
catch (e) {
|
|
48
|
+
console.error("Error parsing LLM response:", e.message);
|
|
49
|
+
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' object. Error: ${e.message}. Your last response was: ${llmResponse}` });
|
|
50
|
+
continue; // Ask LLM to try again
|
|
51
|
+
}
|
|
52
|
+
this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought, tool: toolCall }) });
|
|
53
|
+
if (toolCall.tool === "finish") {
|
|
54
|
+
finalOutput = toolCall.parameters.output;
|
|
55
|
+
console.log(`Agent finished. Output: ${finalOutput}`);
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
// 2. Act: Execute the tool
|
|
59
|
+
const toolInstance = this.availableTools[toolCall.tool];
|
|
60
|
+
if (!toolInstance) {
|
|
61
|
+
const errorMessage = `Error: Tool '${toolCall.tool}' not found. Available tools: ${Object.keys(this.availableTools).join(', ')}.`;
|
|
62
|
+
console.error(errorMessage);
|
|
63
|
+
this.conversationHistory.push({ role: "user", content: errorMessage });
|
|
64
|
+
continue; // Ask LLM to try again
|
|
65
|
+
}
|
|
66
|
+
let toolOutput;
|
|
67
|
+
try {
|
|
68
|
+
toolInstance.setParams(toolCall.parameters);
|
|
69
|
+
const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
|
|
70
|
+
const toolFlow = new ToolFlowClass(toolInstance);
|
|
71
|
+
if (toolInstance instanceof AsyncNode) {
|
|
72
|
+
toolOutput = await toolFlow.runAsync({});
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
toolOutput = toolFlow.run({});
|
|
76
|
+
}
|
|
77
|
+
console.log(`Tool '${toolCall.tool}' executed successfully.`);
|
|
78
|
+
// Summarize large outputs before adding to history
|
|
79
|
+
if (this.summarizeLLM && typeof toolOutput === 'string' && toolOutput.length > 1000) { // Summarize if output is string and > 1000 chars
|
|
80
|
+
console.log(`Summarizing large tool output (${toolOutput.length} chars)...`);
|
|
81
|
+
const summarizeNode = new SummarizeNode();
|
|
82
|
+
summarizeNode.setParams({ text: toolOutput, llmNode: this.summarizeLLM });
|
|
83
|
+
const summarizeFlow = new AsyncFlow(summarizeNode);
|
|
84
|
+
toolOutput = await summarizeFlow.runAsync({});
|
|
85
|
+
console.log(`Summarized to ${toolOutput.length} chars.`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
catch (e) {
|
|
89
|
+
toolOutput = `Error executing tool '${toolCall.tool}': ${e.message}`;
|
|
90
|
+
console.error(toolOutput);
|
|
91
|
+
}
|
|
92
|
+
// 3. Observe: Add tool output to history
|
|
93
|
+
this.conversationHistory.push({ role: "user", content: `Observation: ${JSON.stringify(toolOutput)}` });
|
|
94
|
+
}
|
|
95
|
+
if (step >= this.maxSteps && finalOutput === null) {
|
|
96
|
+
console.warn("Agent reached max steps without finishing.");
|
|
97
|
+
finalOutput = "Agent reached max steps without finishing. Last observation: " + JSON.stringify(this.conversationHistory[this.conversationHistory.length - 1]);
|
|
98
|
+
}
|
|
99
|
+
return finalOutput;
|
|
100
|
+
}
|
|
101
|
+
getSystemPrompt() {
|
|
102
|
+
const toolDefinitions = getToolDefinitions();
|
|
103
|
+
const toolDescriptions = toolDefinitions.map(tool => {
|
|
104
|
+
const params = JSON.stringify(tool.parameters);
|
|
105
|
+
return `### Tool: ${tool.name}\nDescription: ${tool.description}\nParameters: ${params}`;
|
|
106
|
+
}).join('\n\n');
|
|
107
|
+
return `You are an autonomous agent designed to achieve a goal by selecting and using tools. Your responses must be in a specific JSON format.\n\nAvailable Tools:\n${toolDescriptions}\n\nYour response must be a single JSON object with two keys: 'thought' and 'tool'.\n'thought': A string explaining your reasoning process and plan.\n'tool': An object with two keys: 'tool' (the name of the tool to call) and 'parameters' (an object containing the parameters for that tool).\n\nExample response:\n{\n "thought": "I need to find information about X, so I will use the duckduckgo_search tool.",\n "tool": {\n "tool": "duckduckgo_search",\n "parameters": {\n "query": "X information"\n }\n }\n}\n\nWhen you have achieved the goal or cannot proceed, use the 'finish' tool.\nExample finish response:\n{\n "thought": "I have successfully achieved the goal.",\n "tool": {\n "tool": "finish",\n "parameters": {\n "output": "The final result of the goal."\n }\n}\n\nBegin!`;
|
|
108
|
+
}
|
|
109
|
+
async getLLMAction() {
|
|
110
|
+
// The LLM expects a stringified array of messages
|
|
111
|
+
this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
|
|
112
|
+
const llmResult = await this.llmNode.runAsync({});
|
|
113
|
+
return llmResult;
|
|
114
|
+
}
|
|
115
|
+
parseLLMResponse(llmResponse) {
|
|
116
|
+
// Remove markdown code block wrapper if present
|
|
117
|
+
const cleanedResponse = llmResponse.replace(/^```json\n|\n```$/g, '').trim();
|
|
118
|
+
try {
|
|
119
|
+
const parsed = JSON.parse(cleanedResponse);
|
|
120
|
+
if (parsed.thought && parsed.tool && parsed.tool.tool && parsed.tool.parameters !== undefined) {
|
|
121
|
+
return parsed;
|
|
122
|
+
}
|
|
123
|
+
throw new Error("Missing required keys in LLM response (thought, tool.tool, tool.parameters).");
|
|
124
|
+
}
|
|
125
|
+
catch (e) {
|
|
126
|
+
throw new Error(`Invalid JSON or unexpected format: ${e.message}. Cleaned Response: ${cleanedResponse}`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async postAsync(shared, prepRes, execRes) {
|
|
130
|
+
shared.agentOutput = execRes;
|
|
131
|
+
return 'default';
|
|
132
|
+
}
|
|
133
|
+
}
|