@fractal-solutions/qflow 1.0.45 → 1.0.47
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 +10 -1400
- package/dist/agent/agent.js +11 -5
- package/dist/agent/base_agent.d.ts +21 -0
- package/dist/agent/base_agent.js +206 -0
- package/dist/agent/lpavrl_agent.d.ts +5 -0
- package/dist/agent/lpavrl_agent.js +178 -0
- package/dist/agent/ooda_agent.d.ts +5 -0
- package/dist/agent/ooda_agent.js +167 -0
- package/dist/agent/pema_agent.d.ts +5 -0
- package/dist/agent/pema_agent.js +171 -0
- package/dist/agent/raor_agent.d.ts +5 -0
- package/dist/agent/raor_agent.js +164 -0
- package/dist/agent/tools.d.ts +594 -0
- package/dist/agent/tools.js +67 -0
- package/dist/nodes/index.d.ts +6 -0
- package/dist/nodes/index.js +6 -0
- package/dist/nodes/interactive_input.js +1 -1
- package/dist/nodes/s3.d.ts +6 -0
- package/dist/nodes/s3.js +38 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -22,6 +22,12 @@ npm install @fractal-solutions/qflow
|
|
|
22
22
|
bun add @fractal-solutions/qflow
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
+
To get started quickly with a new project, you can use the `create-qflow` tool:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
bunx create-qflow@latest <project-name>
|
|
29
|
+
```
|
|
30
|
+
|
|
25
31
|
## Module Imports
|
|
26
32
|
|
|
27
33
|
`qflow` provides different entry points for its core functionalities and built-in nodes to keep your imports clean and specific.
|
|
@@ -40,1203 +46,20 @@ bun add @fractal-solutions/qflow
|
|
|
40
46
|
|
|
41
47
|
## Core Abstractions
|
|
42
48
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
### Shared State (`shared` object)
|
|
46
|
-
|
|
47
|
-
A central, mutable JavaScript object that is passed through the entire flow. Nodes can read from and write to this `shared` object, making it the primary mechanism for passing data and context between different nodes in a workflow. This is particularly useful for accumulating results or maintaining state across multiple steps.
|
|
48
|
-
|
|
49
|
-
### Node
|
|
50
|
-
|
|
51
|
-
The fundamental building block of any `qflow` workflow. A `Node` represents a single, atomic operation or step in your flow.
|
|
52
|
-
|
|
53
|
-
* `prep(shared)`: Prepares data for execution. Receives the `shared` object.
|
|
54
|
-
* `exec(prepRes)`: Executes the node's primary logic.
|
|
55
|
-
* `post(shared, prepRes, execRes)`: Processes the result of `exec`. Receives the `shared` object.
|
|
56
|
-
* `setParams(params)`: Configures the node with specific parameters. Parameters are accessible via `this.params`.
|
|
57
|
-
* `next(node, action = "default")`: Chains this node to another, defining the next step in the flow.
|
|
58
|
-
|
|
59
|
-
**Asynchronous Nodes (`AsyncNode`, `AsyncBatchNode`, `AsyncParallelBatchNode`)**
|
|
60
|
-
For operations that involve I/O or are inherently asynchronous, `qflow` provides `AsyncNode` and its variants. These nodes leverage `async`/`await` for non-blocking execution. When working within `AsyncFlow`s, it's crucial to implement the `async` versions of the lifecycle methods:
|
|
61
|
-
* `prepAsync(shared)`
|
|
62
|
-
* `execAsync(prepRes, shared)`
|
|
63
|
-
* `postAsync(shared, prepRes, execRes)`
|
|
64
|
-
* `preparePrompt(shared)` (specifically for LLM nodes, allowing prompt construction based on `shared` state)
|
|
65
|
-
|
|
66
|
-
These `async` methods ensure proper awaiting and data propagation within asynchronous workflows.
|
|
67
|
-
|
|
68
|
-
### Flow
|
|
69
|
-
|
|
70
|
-
A `Flow` orchestrates the execution of a sequence of `Node`s. It defines the overall path and manages the transitions between nodes.
|
|
71
|
-
|
|
72
|
-
* `start(startNode)`: Sets the initial node for the flow. (Note: In practice, you often pass the start node directly to the `Flow` constructor for conciseness).
|
|
73
|
-
* `_orch(shared, params)` / `_orchAsync(shared, params)`: Internal methods used to run the flow, especially when passing initial parameters to the starting node. For most use cases, `flow.run(sharedState)` or `await flow.runAsync(sharedState)` is sufficient.
|
|
74
|
-
|
|
75
|
-
**Batch Flows (`BatchFlow`, `AsyncBatchFlow`, `AsyncParallelBatchFlow`)**
|
|
76
|
-
These specialized flows are designed to process collections of items. They run a sub-flow for each item in the batch. `AsyncParallelBatchFlow` is particularly useful for concurrently processing batch items, significantly speeding up operations.
|
|
49
|
+
For a detailed explanation of the core abstractions, see the [Core Abstractions documentation](documentation/core_abstractions.md).
|
|
77
50
|
|
|
78
51
|
## Agents
|
|
79
52
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
### What Can We Do Now That We Have Agents?
|
|
83
|
-
|
|
84
|
-
Here are some key capabilities and applications unlocked by having agents:
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
1. **Autonomous Goal Achievement:** Agents can now take high-level, open-ended goals (e.g.,
|
|
88
|
-
"Research the best AI frameworks for 2025") and dynamically break them down into
|
|
89
|
-
sub-tasks, selecting and executing the appropriate tools (web search, web scraper, LLM
|
|
90
|
-
for summarization) to achieve the objective.
|
|
91
|
-
2. **Complex Problem Solving:** Agents can tackle multi-step problems that require iterative
|
|
92
|
-
reasoning, external information gathering, and dynamic decision-making based on
|
|
93
|
-
observations. They can adapt their plan as they go.
|
|
94
|
-
3. **Self-Correction and Robustness:** With the **"Reason -> Act -> Observe"** loop, agents can
|
|
95
|
-
identify when a tool fails or produces unexpected results. They can then use their LLM
|
|
96
|
-
reasoning to diagnose the problem and attempt alternative strategies or tools.
|
|
97
|
-
4. **Dynamic Workflow Generation:** Instead of you explicitly defining every step of a workflow,
|
|
98
|
-
the agent generates its own execution path at runtime, choosing tools as needed. This
|
|
99
|
-
makes qflow highly adaptable to unforeseen circumstances.
|
|
100
|
-
5. **Enhanced Automation:** Automate tasks that previously required human intervention, complex
|
|
101
|
-
branching logic, or rigid, brittle scripts. Agents can handle variability and
|
|
102
|
-
uncertainty.
|
|
103
|
-
6. **Interactive Assistants:** Combined with the UserInputNode, agents can become truly
|
|
104
|
-
interactive. They can ask clarifying questions, seek approval for critical actions, or
|
|
105
|
-
provide progress updates, making them more collaborative.
|
|
106
|
-
7. **Data Analysis and Reporting:** Agents can gather data from various sources (web, files,
|
|
107
|
-
APIs), process it, and then synthesize
|
|
108
|
-
findings into structured reports or summaries.
|
|
109
|
-
8. **Research and Information Synthesis:** Agents can research topics, scrape relevant pages,
|
|
110
|
-
and synthesize information into comprehensive answers or documents, acting as automated
|
|
111
|
-
research assistants.
|
|
53
|
+
For a detailed explanation of the agents, see the [Agents documentation](documentation/agents.md).
|
|
112
54
|
|
|
113
55
|
## Integrated Nodes and their Examples
|
|
114
56
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
* [**LLMs (DeepSeek, OpenAI, Gemini, Ollama, Hugging Face, OpenRouter):**](#7-inter-node-communication-with-shared-state-advanced-example) The core of agentic behavior.
|
|
118
|
-
* For agents, use specialized LLM nodes like `AgentDeepSeekLLMNode`, `AgentOpenAILLMNode`, `AgentOllamaLLMNode`.
|
|
119
|
-
* [**Hugging Face Models:**](https://github.com/fractal-solutions/qflow/blob/main/examples/huggingface_chat_llm.js) Leverage Hugging Face's free Inference API (OpenAI-compatible endpoint) by using `HuggingFaceLLMNode` and [`AgentHuggingFaceLLMNode`](https://github.com/fractal-solutions/qflow/blob/main/examples/agent_huggingface_llm_test.js) with `baseUrl: 'https://router.huggingface.co/v1'` and your Hugging Face API token. Ensure you specify the correct `model` ID (e.g., `openai/gpt-oss-20b:novita`).
|
|
120
|
-
* [**OpenRouter Models:**](https://github.com/fractal-solutions/qflow/blob/main/examples/agent_openrouter_llm_test.js) Utilize OpenRouter's unified API by using `OpenRouterLLMNode` and [`AgentOpenRouterLLMNode`](https://github.com/fractal-solutions/qflow/blob/main/examples/agent_openrouter_llm_test.js) with your OpenRouter API key and desired model (e.g., `openai/gpt-4o`).
|
|
121
|
-
* [**Agent:**](#12-interactive-agent-example) Orchestrating tools and LLM reasoning to achieve complex goals.
|
|
122
|
-
* [**Embedding:**](#18-embedding-node) For generating vector embeddings from text using Ollama.
|
|
123
|
-
* [**Semantic Memory:**](#19-semantic-memory-node) For storing and retrieving memories based on semantic similarity (RAG) using Ollama. A slightly more advanced RAG is implemented as [RAG with user query input](https://github.com/fractal-solutions/qflow/blob/main/examples/rag_user_input.js).
|
|
124
|
-
* [**Memory:**](#15-memory-node-lightweight-rag) For lightweight, keyword-based long-term memory and 'RAG' (lightweight, dependency free option).
|
|
125
|
-
* [**Transform:**](#16-transform-node) For dynamic data manipulation and reformatting.
|
|
126
|
-
* [**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).
|
|
127
|
-
* [**Interactive Agent:**](#12-interactive-agent-example) An agent that takes a goal from user input and uses its tools to achieve it.
|
|
128
|
-
* [**Shell:**](#8-shell-command-example) For system-level interaction and execution.
|
|
129
|
-
* [**HTTP:**](#10-generic-http-request-example) For universal API access.
|
|
130
|
-
* [**FileSystem:**](#9-file-system-example) For reading and writing local data.
|
|
131
|
-
* [**Web Search:**](#11-web-search-example) Discovering information on the web using either:
|
|
132
|
-
* `DuckDuckGoSearchNode`: API-key-free, using DuckDuckGo's HTML interface.
|
|
133
|
-
* `GoogleSearchNode`: Requires a Google API Key and Custom Search Engine ID for more robust results.
|
|
134
|
-
* [**WebScraper:**](https://github.com/fractal-solutions/qflow/blob/main/examples/webscraper_test.js) For targeted web scraping.
|
|
135
|
-
* [**BrowserControl:**](https://github.com/fractal-solutions/qflow/blob/main/examples/browser_control_test.js) For controlling a web browser with Playwright.
|
|
136
|
-
* [**Git:**](https://github.com/fractal-solutions/qflow/blob/main/examples/git_example.js) For performing Git operations.
|
|
137
|
-
* [**WebSockets:**](https://github.com/fractal-solutions/qflow/blob/main/examples/websockets_test.js) For real-time, two-way communication with web services.
|
|
138
|
-
* [**DataExtractor:**](#13-data-extraction-example) For targeted data extraction.
|
|
139
|
-
* [**PDF Processor:**](https://github.com/fractal-solutions/qflow/blob/main/examples/pdf_processor_example.js) For extracting text and images from PDF documents.
|
|
140
|
-
* **Prerequisite:** Requires `poppler-utils` to be installed on your system.
|
|
141
|
-
* **Linux (Debian/Ubuntu):** `sudo apt-get install poppler-utils`
|
|
142
|
-
* **Linux (Arch/Manjaro):** `sudo pacman -S poppler`
|
|
143
|
-
* **macOS:** `brew install poppler`
|
|
144
|
-
* **Windows:** Install Poppler for Windows and add its executables to your system's PATH.
|
|
145
|
-
* [**GIS:**](https://github.com/fractal-solutions/qflow/blob/main/examples/gis_example.js) For Geographic Information System operations like geocoding and reverse geocoding. Supports multiple providers (OpenStreetMap, Google Maps).
|
|
146
|
-
* **OpenStreetMap:** Free and open-source. No API key required.
|
|
147
|
-
* **Google Maps:** Requires a `GOOGLE_MAPS_API_KEY` environment variable.
|
|
148
|
-
* [**Display Image:**](https://github.com/fractal-solutions/qflow/blob/main/examples/display_image_test.js) For opening image files using the system's default image viewer. Useful for agents to show generated plots or other visual output.
|
|
149
|
-
* [**Image Gallery:**](https://github.com/fractal-solutions/qflow/blob/main/examples/image_gallery_example.js) Generates an HTML gallery from multiple image files and opens it in a web browser. Useful for displaying multiple plots or images in a single view.
|
|
150
|
-
* [**Hardware Interaction:**](https://github.com/fractal-solutions/qflow/blob/main/examples/hardware_interaction_example.js) For communicating with local hardware via serial port (UART).
|
|
151
|
-
* **Prerequisite:** Uses the `serialport` library. This library has native components and may require build tools (Python, C/C++ compiler).
|
|
152
|
-
* **Permissions:** On Linux, your user might need to be added to the `dialout` group (`sudo usermod -a -G dialout $USER`, then log out and back in).
|
|
153
|
-
* [**Speech Synthesis:**](https://github.com/fractal-solutions/qflow/blob/main/examples/speech_synthesis_example.js) Converts text to spoken audio using OS capabilities or cloud APIs.
|
|
154
|
-
* **Prerequisites:**
|
|
155
|
-
* **macOS:** Built-in (`say` command).
|
|
156
|
-
* **Linux:** `espeak` (`sudo apt install espeak` or `sudo pacman -S alsa-utils`).
|
|
157
|
-
* **Google Cloud TTS:** Requires `GOOGLE_TTS_API_KEY` environment variable.
|
|
158
|
-
* [**Multimedia Processing:**](https://github.com/fractal-solutions/qflow/blob/main/examples/multimedia_processing_example.js) Performs various operations on audio and video files using `ffmpeg` (e.g., convert formats, trim, extract audio/frames).
|
|
159
|
-
* **Prerequisite:** Requires `ffmpeg` to be installed on your system.
|
|
160
|
-
* **Linux (Debian/Ubuntu):** `sudo apt install ffmpeg`
|
|
161
|
-
* **Linux (Arch/Manjaro):** `sudo pacman -S ffmpeg`
|
|
162
|
-
* **macOS:** `brew install ffmpeg`
|
|
163
|
-
* **Windows:** Download and install `ffmpeg` and add it to your system's PATH.
|
|
164
|
-
* [**Remote Execution:**](https://github.com/fractal-solutions/qflow/blob/main/examples/remote_execution_example.js) Executes commands on remote machines via SSH.
|
|
165
|
-
* **Prerequisite:** Uses the `ssh2` library. This library has native components and may require build tools (Python, C/C++ compiler).
|
|
166
|
-
* [**Data Validation:**](https://github.com/fractal-solutions/qflow/blob/main/examples/data_validation_example.js) Validates structured data against JSON Schemas.
|
|
167
|
-
* **Prerequisite:** Uses the `ajv` library.
|
|
168
|
-
* [**WebHook:**](https://github.com/fractal-solutions/qflow/blob/main/examples/webhook_example.js) Exposes an HTTP endpoint to receive webhooks, enabling event-driven flows.
|
|
169
|
-
* [**Scheduler:**](https://github.com/fractal-solutions/qflow/blob/main/examples/scheduler_example.js) Schedules `qflow` flows for future or recurring execution.
|
|
170
|
-
* **Prerequisite:** Uses the `node-cron` library.
|
|
171
|
-
* [**System Notification:**](https://github.com/fractal-solutions/qflow/blob/main/examples/system_notification_test.js) For displaying system-level notifications across different operating systems.
|
|
172
|
-
* [**Interactive Input:**](https://github.com/fractal-solutions/qflow/blob/main/examples/interactive_input_test.js) For getting user input via a GUI popup (cross-platform).
|
|
173
|
-
* [**User Input:**](https://github.com/fractal-solutions/qflow/blob/main/examples/user_input_test.js) For human-in-the-loop control.
|
|
174
|
-
* **GitHub:** Creating and managing issues.
|
|
175
|
-
* **HackerNews:** Fetching top stories and item details.
|
|
176
|
-
* **Stripe:** Creating charges and retrieving account balances.
|
|
57
|
+
For a detailed explanation of the integrated nodes and their examples, see the [Integrated Nodes documentation](documentation/integrated_nodes.md).
|
|
177
58
|
|
|
178
|
-
These examples are a great resource for understanding how to leverage `qflow` to its full potential.
|
|
179
|
-
|
|
180
|
-
For a detailed list of all tools available to the `AgentNode` and their parameters, see the [Available Tools for Agents](#available-tools-for-agents) section.
|
|
181
59
|
|
|
182
60
|
## Basic Usage & Examples
|
|
183
61
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
A basic example of defining and running a single node.
|
|
187
|
-
|
|
188
|
-
```javascript
|
|
189
|
-
import { Node } from '@fractal-solutions/qflow';
|
|
190
|
-
|
|
191
|
-
class MySimpleNode extends Node {
|
|
192
|
-
prep(shared) {
|
|
193
|
-
console.log('Preparing data...');
|
|
194
|
-
return shared.inputData * 2;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
exec(prepRes) {
|
|
198
|
-
console.log('Executing with prepared data:', prepRes);
|
|
199
|
-
return prepRes + 10;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
post(shared, prepRes, execRes) {
|
|
203
|
-
console.log('Post-processing result:', execRes);
|
|
204
|
-
return { finalResult: execRes, originalInput: shared.inputData };
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
const node = new MySimpleNode();
|
|
209
|
-
const result = node.run({ inputData: 5 });
|
|
210
|
-
console.log('Node run result:', result);
|
|
211
|
-
// Expected output:
|
|
212
|
-
// Preparing data...
|
|
213
|
-
// Executing with prepared data: 10
|
|
214
|
-
// Post-processing result: 20
|
|
215
|
-
// Node run result: { finalResult: 20, originalInput: 5 }
|
|
216
|
-
```
|
|
217
|
-
|
|
218
|
-
### 2. Simple Flow
|
|
219
|
-
|
|
220
|
-
Chaining multiple nodes together to form a basic workflow.
|
|
221
|
-
|
|
222
|
-
```javascript
|
|
223
|
-
import { Node, Flow } from '@fractal-solutions/qflow';
|
|
224
|
-
|
|
225
|
-
let count = 0;
|
|
226
|
-
|
|
227
|
-
class MessageNode extends Node {
|
|
228
|
-
exec() {
|
|
229
|
-
count++;
|
|
230
|
-
console.log(`New Message ${count}`);
|
|
231
|
-
return `default`;
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
class TimeNode extends Node {
|
|
236
|
-
exec() {
|
|
237
|
-
console.log(`Time ${Date.now()}`);
|
|
238
|
-
return `default`;
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
const m1 = new MessageNode();
|
|
243
|
-
const t1 = new TimeNode();
|
|
244
|
-
const m2 = new MessageNode();
|
|
245
|
-
|
|
246
|
-
m1.next(t1);
|
|
247
|
-
t1.next(m2);
|
|
248
|
-
|
|
249
|
-
const flow = new Flow(m1);
|
|
250
|
-
flow.run({});
|
|
251
|
-
// Expected output (approximate):
|
|
252
|
-
// New Message 1
|
|
253
|
-
// Time <timestamp>
|
|
254
|
-
// New Message 2
|
|
255
|
-
```
|
|
256
|
-
|
|
257
|
-
### 3. Conditional Flow
|
|
258
|
-
|
|
259
|
-
Using `transition()` for dynamic branching based on an action. This example demonstrates configuring a node using `setParams` for a cleaner API.
|
|
260
|
-
|
|
261
|
-
```javascript
|
|
262
|
-
import { Node, Flow } from '@fractal-solutions/qflow';
|
|
263
|
-
|
|
264
|
-
class ConditionalNode extends Node {
|
|
265
|
-
exec() {
|
|
266
|
-
// Access shouldGoLeft from this.params, which is set via setParams
|
|
267
|
-
if (this.params.shouldGoLeft) {
|
|
268
|
-
console.log('ConditionalNode: Going left');
|
|
269
|
-
return 'left';
|
|
270
|
-
} else {
|
|
271
|
-
console.log('ConditionalNode: Going right');
|
|
272
|
-
return 'right';
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// Helper node for conditional transition test
|
|
278
|
-
function MessageNode(message) {
|
|
279
|
-
return new (class extends Node {
|
|
280
|
-
exec() {
|
|
281
|
-
console.log(message);
|
|
282
|
-
return 'default';
|
|
283
|
-
}
|
|
284
|
-
})();
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
const conditionalNode = new ConditionalNode();
|
|
288
|
-
conditionalNode.setParams({ shouldGoLeft: true }); // Configure via setParams
|
|
289
|
-
|
|
290
|
-
const leftNode = MessageNode('Went Left');
|
|
291
|
-
const rightNode = MessageNode('Went Right');
|
|
292
|
-
|
|
293
|
-
conditionalNode.next(leftNode, 'left');
|
|
294
|
-
conditionalNode.next(rightNode, 'right');
|
|
295
|
-
|
|
296
|
-
const conditionalFlow = new Flow(conditionalNode);
|
|
297
|
-
conditionalFlow.run({});
|
|
298
|
-
// Expected output:
|
|
299
|
-
// ConditionalNode: Going left
|
|
300
|
-
// Went Left
|
|
301
|
-
|
|
302
|
-
const conditionalNode2 = new ConditionalNode();
|
|
303
|
-
conditionalNode2.setParams({ shouldGoLeft: false }); // Configure via setParams
|
|
304
|
-
|
|
305
|
-
conditionalNode2.next(leftNode, 'left');
|
|
306
|
-
conditionalNode2.next(rightNode, 'right');
|
|
307
|
-
const conditionalFlow2 = new Flow(conditionalNode2);
|
|
308
|
-
conditionalFlow2.run({});
|
|
309
|
-
// Expected output:
|
|
310
|
-
// ConditionalNode: Going right
|
|
311
|
-
// Went Right
|
|
312
|
-
```
|
|
313
|
-
|
|
314
|
-
### 4. Asynchronous Flow
|
|
315
|
-
|
|
316
|
-
Handling asynchronous operations within a flow.
|
|
317
|
-
|
|
318
|
-
```javascript
|
|
319
|
-
import { AsyncNode, AsyncFlow } from '@fractal-solutions/qflow';
|
|
320
|
-
|
|
321
|
-
class MyAsyncNode extends AsyncNode {
|
|
322
|
-
async execAsync() {
|
|
323
|
-
console.log('AsyncNode: Starting...');
|
|
324
|
-
await new Promise(resolve => setTimeout(resolve, 100));
|
|
325
|
-
console.log('AsyncNode: Finished!');
|
|
326
|
-
return 'default';
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
const asyncNode1 = new MyAsyncNode();
|
|
331
|
-
const asyncNode2 = new MyAsyncNode();
|
|
332
|
-
asyncNode1.next(asyncNode2);
|
|
333
|
-
|
|
334
|
-
const asyncFlow = new AsyncFlow(asyncNode1);
|
|
335
|
-
await asyncFlow.runAsync({});
|
|
336
|
-
// Expected output:
|
|
337
|
-
// AsyncNode: Starting...
|
|
338
|
-
// AsyncNode: Finished!
|
|
339
|
-
// AsyncNode: Starting...
|
|
340
|
-
// AsyncNode: Finished!
|
|
341
|
-
```
|
|
342
|
-
|
|
343
|
-
### 5. Batch Processing
|
|
344
|
-
|
|
345
|
-
Processing multiple items through a flow.
|
|
346
|
-
|
|
347
|
-
```javascript
|
|
348
|
-
import { Node, BatchFlow, AsyncParallelBatchFlow, AsyncNode } from '@fractal-solutions/qflow';
|
|
349
|
-
|
|
350
|
-
// Synchronous Batch Flow
|
|
351
|
-
console.log('\n--- Running Synchronous Batch Flow ---');
|
|
352
|
-
|
|
353
|
-
class MyBatchNode extends Node {
|
|
354
|
-
exec() {
|
|
355
|
-
console.log(`BatchNode: Processing item ${this.params.item}`);
|
|
356
|
-
return 'default';
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
const batchNode = new MyBatchNode();
|
|
361
|
-
const batchFlow = new BatchFlow(batchNode);
|
|
362
|
-
batchFlow.prep = () => [ { item: 1 }, { item: 2 }, { item: 3 } ];
|
|
363
|
-
batchFlow.run({});
|
|
364
|
-
// Expected output:
|
|
365
|
-
// BatchNode: Processing item 1
|
|
366
|
-
// BatchNode: Processing item 2
|
|
367
|
-
// BatchNode: Processing item 3
|
|
368
|
-
|
|
369
|
-
// Asynchronous Parallel Batch Flow
|
|
370
|
-
console.log('\n--- Running Asynchronous Parallel Batch Flow ---');
|
|
371
|
-
|
|
372
|
-
class MyAsyncParallelBatchNode extends AsyncNode {
|
|
373
|
-
async execAsync() {
|
|
374
|
-
console.log(`AsyncParallelBatchNode: Starting item ${this.params.item}`);
|
|
375
|
-
await new Promise(resolve => setTimeout(resolve, Math.random() * 100));
|
|
376
|
-
console.log(`AsyncParallelBatchNode: Finished item ${this.params.item}`);
|
|
377
|
-
return 'default';
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
const asyncParallelBatchNode = new MyAsyncParallelBatchNode();
|
|
382
|
-
const asyncParallelBatchFlow = new AsyncParallelBatchFlow(asyncParallelBatchNode);
|
|
383
|
-
asyncParallelBatchFlow.prepAsync = async () => [ { item: 1 }, { item: 2 }, { item: 3 }, { item: 4 }, { item: 5 } ];
|
|
384
|
-
await asyncParallelBatchFlow.runAsync({});
|
|
385
|
-
// Expected output (order may vary due to parallel execution):
|
|
386
|
-
// AsyncParallelBatchNode: Starting item 1
|
|
387
|
-
// AsyncParallelBatchNode: Starting item 2
|
|
388
|
-
// ...
|
|
389
|
-
// AsyncParallelBatchNode: Finished item 1
|
|
390
|
-
// AsyncParallelBatchNode: Finished item 2
|
|
391
|
-
// ...
|
|
392
|
-
```
|
|
393
|
-
|
|
394
|
-
### 6. Retry Mechanism
|
|
395
|
-
|
|
396
|
-
Configuring a node to retry on failure.
|
|
397
|
-
|
|
398
|
-
```javascript
|
|
399
|
-
import { Node, Flow } from '@fractal-solutions/qflow';
|
|
400
|
-
|
|
401
|
-
let retryCount = 0;
|
|
402
|
-
class RetryNode extends Node {
|
|
403
|
-
constructor() {
|
|
404
|
-
super(3, 0.1); // 3 retries, 0.1s wait
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
exec() {
|
|
408
|
-
retryCount++;
|
|
409
|
-
if (retryCount < 3) {
|
|
410
|
-
console.log(`RetryNode: Failing, attempt ${retryCount}`);
|
|
411
|
-
throw new Error('Failed!');
|
|
412
|
-
} else {
|
|
413
|
-
console.log('RetryNode: Succeeded!');
|
|
414
|
-
return 'default';
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
execFallback(prepRes, error) {
|
|
419
|
-
console.log('RetryNode: Fallback executed');
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
const retryNode = new RetryNode();
|
|
424
|
-
const retryFlow = new Flow(retryNode);
|
|
425
|
-
retryFlow.run({});
|
|
426
|
-
// Expected output:
|
|
427
|
-
// RetryNode: Failing, attempt 1
|
|
428
|
-
// RetryNode: Failing, attempt 2
|
|
429
|
-
// RetryNode: Succeeded!
|
|
430
|
-
```
|
|
431
|
-
|
|
432
|
-
### 7. Inter-Node Communication with Shared State (Advanced Example)
|
|
433
|
-
|
|
434
|
-
Demonstrates how to pass data between nodes using the `shared` object, particularly important in asynchronous workflows. This example showcases two LLM nodes interacting, where the output of the first influences the input of the second.
|
|
435
|
-
|
|
436
|
-
```javascript
|
|
437
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
438
|
-
import { DeepSeekLLMNode } from '@fractal-solutions/qflow/nodes';
|
|
439
|
-
|
|
440
|
-
// Node representing the "Apologist" personality
|
|
441
|
-
class ApologistNode extends DeepSeekLLMNode {
|
|
442
|
-
// preparePrompt now receives the shared object
|
|
443
|
-
preparePrompt(shared) {
|
|
444
|
-
const { topic } = this.params;
|
|
445
|
-
this.params.prompt = `You are an eloquent apologist. Your task is to defend the following topic with a concise, positive, and persuasive argument, no more than 3 sentences: "${topic}"`;
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
// postAsync is used to ensure shared state is updated after async execution
|
|
449
|
-
async postAsync(shared, prepRes, execRes) {
|
|
450
|
-
shared.apologistArgument = execRes; // Store the argument in shared state
|
|
451
|
-
return 'default'; // Signal default transition
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
// Node representing the "Heretic" personality
|
|
456
|
-
class HereticNode extends DeepSeekLLMNode {
|
|
457
|
-
// preparePrompt now receives the shared object
|
|
458
|
-
preparePrompt(shared) {
|
|
459
|
-
const { apologistArgument } = shared; // Access the argument from shared state
|
|
460
|
-
|
|
461
|
-
if (!apologistArgument) {
|
|
462
|
-
throw new Error("Apologist's argument is missing from shared state. Cannot critique.");
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
this.params.prompt = `You are a skeptical heretic. Your task is to critically analyze and briefly refute or find a flaw in the following argument, no more than 3 sentences: "${apologistArgument}"`;
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
// postAsync is used to ensure shared state is updated after async execution
|
|
469
|
-
async postAsync(shared, prepRes, execRes) {
|
|
470
|
-
shared.hereticCritique = execRes; // Store the critique in shared state
|
|
471
|
-
return execRes; // Return the critique as the node's result
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
(async () => {
|
|
476
|
-
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY; // Ensure this is set in .env or env vars
|
|
477
|
-
|
|
478
|
-
if (!DEEPSEEK_API_KEY) {
|
|
479
|
-
console.warn("WARNING: DeepSeek API key is not set. Please configure it to run this example.");
|
|
480
|
-
return;
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
console.log('--- Starting Apologist vs. Heretic LLM Workflow ---');
|
|
484
|
-
|
|
485
|
-
const topicInput = prompt("Enter a topic for the Apologist to defend (e.g., 'The benefits of remote work'):\nYour topic: ");
|
|
486
|
-
|
|
487
|
-
if (!topicInput) {
|
|
488
|
-
console.log("No topic provided. Exiting.");
|
|
489
|
-
return;
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
const apologist = new ApologistNode();
|
|
493
|
-
apologist.setParams({ apiKey: DEEPSEEK_API_KEY, topic: topicInput });
|
|
494
|
-
|
|
495
|
-
const heretic = new HereticNode();
|
|
496
|
-
heretic.setParams({ apiKey: DEEPSEEK_API_KEY });
|
|
497
|
-
|
|
498
|
-
apologist.next(heretic);
|
|
499
|
-
|
|
500
|
-
const debateFlow = new AsyncFlow(apologist);
|
|
501
|
-
|
|
502
|
-
try {
|
|
503
|
-
const sharedState = {}; // Initialize an empty shared state object
|
|
504
|
-
await debateFlow.runAsync(sharedState); // Run the flow, passing the shared state
|
|
505
|
-
|
|
506
|
-
console.log('\n--- The Debate Unfolds ---');
|
|
507
|
-
console.log('Topic:', topicInput);
|
|
508
|
-
console.log('\nApologist\'s Argument:');
|
|
509
|
-
console.log(sharedState.apologistArgument);
|
|
510
|
-
console.log('\nHeretic\'s Critique:');
|
|
511
|
-
console.log(sharedState.hereticCritique);
|
|
512
|
-
console.log('\n--- Workflow Finished ---');
|
|
513
|
-
|
|
514
|
-
} catch (error) {
|
|
515
|
-
console.error('--- Workflow Failed ---', error);
|
|
516
|
-
}
|
|
517
|
-
})();
|
|
518
|
-
|
|
519
|
-
```
|
|
520
|
-
|
|
521
|
-
### 8. Shell Command Example
|
|
522
|
-
|
|
523
|
-
Executing a shell command and printing the output.
|
|
524
|
-
|
|
525
|
-
```javascript
|
|
526
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
527
|
-
import { ShellCommandNode } from '@fractal-solutions/qflow/nodes';
|
|
528
|
-
|
|
529
|
-
const listFiles = new ShellCommandNode();
|
|
530
|
-
listFiles.setParams({ command: 'ls -l' });
|
|
531
|
-
|
|
532
|
-
listFiles.postAsync = async (shared, prepRes, execRes) => {
|
|
533
|
-
console.log('--- File Listing ---');
|
|
534
|
-
console.log(execRes.stdout);
|
|
535
|
-
return 'default';
|
|
536
|
-
};
|
|
537
|
-
|
|
538
|
-
const flow = new AsyncFlow(listFiles);
|
|
539
|
-
await flow.runAsync({});
|
|
540
|
-
```
|
|
541
|
-
|
|
542
|
-
### 9. File System Example
|
|
543
|
-
|
|
544
|
-
Writing to a file and then reading it back.
|
|
545
|
-
|
|
546
|
-
```javascript
|
|
547
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
548
|
-
import { WriteFileNode, ReadFileNode } from '@fractal-solutions/qflow/nodes';
|
|
549
|
-
|
|
550
|
-
const writeFile = new WriteFileNode();
|
|
551
|
-
writeFile.setParams({ filePath: './hello.txt', content: 'Hello, qflow!\n' });
|
|
552
|
-
|
|
553
|
-
const readFile = new ReadFileNode();
|
|
554
|
-
readFile.setParams({ filePath: './hello.txt' });
|
|
555
|
-
|
|
556
|
-
readFile.postAsync = async (shared, prepRes, execRes) => {
|
|
557
|
-
console.log('--- File Content ---');
|
|
558
|
-
console.log(execRes);
|
|
559
|
-
return 'default';
|
|
560
|
-
};
|
|
561
|
-
|
|
562
|
-
writeFile.next(readFile);
|
|
563
|
-
|
|
564
|
-
const flow = new AsyncFlow(writeFile);
|
|
565
|
-
await flow.runAsync({});
|
|
566
|
-
```
|
|
567
|
-
|
|
568
|
-
### 10. Generic HTTP Request Example
|
|
569
|
-
|
|
570
|
-
Making a GET request to a public API and printing the response.
|
|
571
|
-
|
|
572
|
-
```javascript
|
|
573
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
574
|
-
import { HttpRequestNode } from '@fractal-solutions/qflow/nodes';
|
|
575
|
-
|
|
576
|
-
const getPost = new HttpRequestNode();
|
|
577
|
-
getPost.setParams({
|
|
578
|
-
url: 'https://jsonplaceholder.typicode.com/posts/1',
|
|
579
|
-
method: 'GET'
|
|
580
|
-
});
|
|
581
|
-
|
|
582
|
-
getPost.postAsync = async (shared, prepRes, execRes) => {
|
|
583
|
-
console.log('--- API Response ---');
|
|
584
|
-
console.log('Status:', execRes.status);
|
|
585
|
-
console.log('Body:', execRes.body);
|
|
586
|
-
return 'default';
|
|
587
|
-
};
|
|
588
|
-
|
|
589
|
-
const flow = new AsyncFlow(getPost);
|
|
590
|
-
await flow.runAsync({});
|
|
591
|
-
```
|
|
592
|
-
|
|
593
|
-
### 11. Web Search Example
|
|
594
|
-
|
|
595
|
-
Performing web searches using both a free metasearch engine and a commercial API.
|
|
596
|
-
|
|
597
|
-
```javascript
|
|
598
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
599
|
-
import { DuckDuckGoSearchNode, GoogleSearchNode } from '@fractal-solutions/qflow/nodes';
|
|
600
|
-
|
|
601
|
-
// Example 1: Using DuckDuckGo (no API key needed)
|
|
602
|
-
const ddgSearch = new DuckDuckGoSearchNode();
|
|
603
|
-
ddgSearch.setParams({ query: 'qflow library github' });
|
|
604
|
-
ddgSearch.postAsync = async (shared, prepRes, execRes) => {
|
|
605
|
-
console.log('\n--- DuckDuckGo Search Results ---');
|
|
606
|
-
execRes.slice(0, 5).forEach(r => console.log(`- ${r.title}: ${r.link}`));
|
|
607
|
-
return 'default';
|
|
608
|
-
};
|
|
609
|
-
|
|
610
|
-
// Example 2: Using Google Custom Search (requires API key and CSE ID)
|
|
611
|
-
const googleSearch = new GoogleSearchNode();
|
|
612
|
-
googleSearch.setParams({
|
|
613
|
-
query: 'qflow framework benefits',
|
|
614
|
-
apiKey: process.env.GOOGLE_API_KEY, // Set this env var
|
|
615
|
-
cseId: process.env.GOOGLE_CSE_ID // Set this env var
|
|
616
|
-
});
|
|
617
|
-
googleSearch.postAsync = async (shared, prepRes, execRes) => {
|
|
618
|
-
console.log('\n--- Google Search Results ---');
|
|
619
|
-
execRes.slice(0, 5).forEach(r => console.log(`- ${r.title}: ${r.link}`));
|
|
620
|
-
return 'default';
|
|
621
|
-
};
|
|
622
|
-
|
|
623
|
-
// Chain them or run independently
|
|
624
|
-
const flow1 = new AsyncFlow(ddgSearch);
|
|
625
|
-
await flow1.runAsync({});
|
|
626
|
-
|
|
627
|
-
// Uncomment the following lines to run the Google Search example
|
|
628
|
-
// const flow2 = new AsyncFlow(googleSearch);
|
|
629
|
-
// await flow2.runAsync({});
|
|
630
|
-
```
|
|
631
|
-
|
|
632
|
-
### 12. Interactive Agent Example
|
|
633
|
-
|
|
634
|
-
An agent that takes a goal from user input and uses its tools to achieve it.
|
|
635
|
-
|
|
636
|
-
```javascript
|
|
637
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
638
|
-
import {
|
|
639
|
-
AgentDeepSeekLLMNode,
|
|
640
|
-
DuckDuckGoSearchNode,
|
|
641
|
-
ShellCommandNode,
|
|
642
|
-
ReadFileNode,
|
|
643
|
-
WriteFileNode,
|
|
644
|
-
HttpRequestNode,
|
|
645
|
-
ScrapeURLNode,
|
|
646
|
-
UserInputNode,
|
|
647
|
-
AgentNode,
|
|
648
|
-
CodeInterpreterNode,
|
|
649
|
-
MemoryNode,
|
|
650
|
-
TransformNode
|
|
651
|
-
} from '@fractal-solutions/qflow/nodes';
|
|
652
|
-
|
|
653
|
-
// Ensure your DeepSeek API Key is set as an environment variable
|
|
654
|
-
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
|
|
655
|
-
|
|
656
|
-
(async () => {
|
|
657
|
-
if (!DEEPSEEK_API_KEY) {
|
|
658
|
-
console.warn("WARNING: DEEPSEEK_API_KEY is not set. Please set it to run the Interactive Agent example.");
|
|
659
|
-
return;
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
console.log('--- Running Interactive Agent Test Workflow ---');
|
|
663
|
-
|
|
664
|
-
// 1. Node to get the goal from the user
|
|
665
|
-
const getGoalNode = new UserInputNode();
|
|
666
|
-
getGoalNode.setParams({ prompt: 'Please enter the agent\'s goal: ' });
|
|
667
|
-
|
|
668
|
-
// 2. Instantiate the LLM for the agent's reasoning
|
|
669
|
-
const agentLLM = new AgentDeepSeekLLMNode();
|
|
670
|
-
agentLLM.setParams({ apiKey: DEEPSEEK_API_KEY });
|
|
671
|
-
|
|
672
|
-
// 3. Instantiate the tools the agent can use
|
|
673
|
-
const duckduckgoSearch = new DuckDuckGoSearchNode();
|
|
674
|
-
const shellCommand = new ShellCommandNode();
|
|
675
|
-
const readFile = new ReadFileNode();
|
|
676
|
-
const writeFile = new WriteFileNode();
|
|
677
|
-
const httpRequest = new HttpRequestNode();
|
|
678
|
-
const webScraper = new ScrapeURLNode();
|
|
679
|
-
const userInput = new UserInputNode(); // Agent can also ask for user input
|
|
680
|
-
const codeInterpreter = new CodeInterpreterNode(); // Agent can execute code
|
|
681
|
-
const memoryNode = new MemoryNode(); // Agent can store and retrieve memories
|
|
682
|
-
const transformNode = new TransformNode(); // Agent can transform data
|
|
683
|
-
|
|
684
|
-
// Map tool names to their instances
|
|
685
|
-
const availableTools = {
|
|
686
|
-
duckduckgo_search: duckduckgoSearch,
|
|
687
|
-
shell_command: shellCommand,
|
|
688
|
-
read_file: readFile,
|
|
689
|
-
write_file: writeFile,
|
|
690
|
-
http_request: httpRequest,
|
|
691
|
-
web_scraper: webScraper,
|
|
692
|
-
user_input: userInput,
|
|
693
|
-
code_interpreter: codeInterpreter,
|
|
694
|
-
memory_node: memoryNode,
|
|
695
|
-
transform_node: transformNode,
|
|
696
|
-
// Add other tools as needed
|
|
697
|
-
};
|
|
698
|
-
|
|
699
|
-
// 4. Instantiate the AgentNode
|
|
700
|
-
const agent = new AgentNode(agentLLM, availableTools);
|
|
701
|
-
// The goal will be set dynamically from the UserInputNode's output
|
|
702
|
-
agent.prepAsync = async (shared) => {
|
|
703
|
-
agent.setParams({ goal: shared.userInput });
|
|
704
|
-
};
|
|
705
|
-
|
|
706
|
-
// 5. Chain the nodes: Get Goal -> Agent
|
|
707
|
-
getGoalNode.next(agent);
|
|
708
|
-
|
|
709
|
-
// 6. Create and run the flow
|
|
710
|
-
const interactiveAgentFlow = new AsyncFlow(getGoalNode);
|
|
711
|
-
|
|
712
|
-
try {
|
|
713
|
-
const finalResult = await interactiveAgentFlow.runAsync({});
|
|
714
|
-
console.log('\n--- Interactive Agent Test Workflow Finished ---');
|
|
715
|
-
console.log('Final Agent Output:', finalResult);
|
|
716
|
-
} catch (error) {
|
|
717
|
-
console.error('\n--- Interactive Agent Test Workflow Failed ---', error);
|
|
718
|
-
}
|
|
719
|
-
})();
|
|
720
|
-
```
|
|
721
|
-
|
|
722
|
-
### 13. Data Extraction Example
|
|
723
|
-
|
|
724
|
-
Extracting structured data from HTML, JSON, or plain text.
|
|
725
|
-
|
|
726
|
-
```javascript
|
|
727
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
728
|
-
import { DataExtractorNode, WebScraperNode } from '@fractal-solutions/qflow/nodes';
|
|
729
|
-
|
|
730
|
-
(async () => {
|
|
731
|
-
console.log('--- Running DataExtractorNode Test Workflow ---');
|
|
732
|
-
|
|
733
|
-
// Example 1: Extracting from HTML (using WebScraperNode to get HTML)
|
|
734
|
-
console.log('\n--- HTML Extraction Example ---');
|
|
735
|
-
const scrapeNode = new WebScraperNode();
|
|
736
|
-
scrapeNode.setParams({ url: 'https://www.example.com' });
|
|
737
|
-
|
|
738
|
-
const extractHtmlNode = new DataExtractorNode();
|
|
739
|
-
extractHtmlNode.setParams({
|
|
740
|
-
type: 'html',
|
|
741
|
-
selector: 'h1' // Extract the text from the first h1 tag
|
|
742
|
-
});
|
|
743
|
-
|
|
744
|
-
scrapeNode.next(extractHtmlNode);
|
|
745
|
-
|
|
746
|
-
extractHtmlNode.postAsync = async (shared, prepRes, execRes) => {
|
|
747
|
-
console.log('Extracted HTML (h1 content):', execRes);
|
|
748
|
-
return 'default';
|
|
749
|
-
};
|
|
750
|
-
|
|
751
|
-
const htmlFlow = new AsyncFlow(scrapeNode);
|
|
752
|
-
try {
|
|
753
|
-
await htmlFlow.runAsync({});
|
|
754
|
-
} catch (error) {
|
|
755
|
-
console.error('HTML Extraction Flow Failed:', error);
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
// Example 2: Extracting from JSON
|
|
759
|
-
console.log('\n--- JSON Extraction Example ---');
|
|
760
|
-
const jsonContent = JSON.stringify({
|
|
761
|
-
user: {
|
|
762
|
-
id: 123,
|
|
763
|
-
name: 'John Doe',
|
|
764
|
-
contact: {
|
|
765
|
-
email: 'john.doe@example.com',
|
|
766
|
-
phone: '123-456-7890'
|
|
767
|
-
},
|
|
768
|
-
roles: ['admin', 'editor']
|
|
769
|
-
},
|
|
770
|
-
products: [
|
|
771
|
-
{ id: 1, name: 'Laptop', price: 1200 },
|
|
772
|
-
{ id: 2, name: 'Mouse', price: 25 }
|
|
773
|
-
]
|
|
774
|
-
}, null, 2);
|
|
775
|
-
|
|
776
|
-
const extractJsonNode = new DataExtractorNode();
|
|
777
|
-
extractJsonNode.setParams({
|
|
778
|
-
input: jsonContent,
|
|
779
|
-
type: 'json',
|
|
780
|
-
jsonPath: 'user.contact.email' // Extract email from nested JSON
|
|
781
|
-
});
|
|
782
|
-
|
|
783
|
-
extractJsonNode.postAsync = async (shared, prepRes, execRes) => {
|
|
784
|
-
console.log('Extracted JSON (user email):', execRes);
|
|
785
|
-
return 'default';
|
|
786
|
-
};
|
|
787
|
-
|
|
788
|
-
const jsonFlow = new AsyncFlow(extractJsonNode);
|
|
789
|
-
try {
|
|
790
|
-
await jsonFlow.runAsync({});
|
|
791
|
-
} catch (error) {
|
|
792
|
-
console.error('JSON Extraction Flow Failed:', error);
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
// Example 3: Extracting from Text (Regex)
|
|
796
|
-
console.log('\n--- Text Extraction Example (Regex) ---');
|
|
797
|
-
const textContent = "User IDs: user_123, user_456, admin_789. Emails: test@example.com, another@domain.org.";
|
|
798
|
-
|
|
799
|
-
const extractTextNode = new DataExtractorNode();
|
|
800
|
-
extractTextNode.setParams({
|
|
801
|
-
input: textContent,
|
|
802
|
-
type: 'text',
|
|
803
|
-
regex: 'user_(\\d+)', // Extract numbers after 'user_'
|
|
804
|
-
group: 1 // Capture group 1
|
|
805
|
-
});
|
|
806
|
-
|
|
807
|
-
extractTextNode.postAsync = async (shared, prepRes, execRes) => {
|
|
808
|
-
console.log('Extracted Text (User IDs):', execRes);
|
|
809
|
-
return 'default';
|
|
810
|
-
};
|
|
811
|
-
|
|
812
|
-
const textFlow = new AsyncFlow(extractTextNode);
|
|
813
|
-
try {
|
|
814
|
-
await textFlow.runAsync({});
|
|
815
|
-
} catch (error) {
|
|
816
|
-
console.error('Text Extraction Flow Failed:', error);
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
console.log('\n--- DataExtractorNode Test Workflow Finished ---');
|
|
820
|
-
})();
|
|
821
|
-
|
|
822
|
-
```
|
|
823
|
-
|
|
824
|
-
### 14. Code Interpreter Example
|
|
825
|
-
|
|
826
|
-
Executing Python code within the workflow.
|
|
827
|
-
|
|
828
|
-
```javascript
|
|
829
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
830
|
-
import { CodeInterpreterNode } from '@fractal-solutions/qflow/nodes';
|
|
831
|
-
|
|
832
|
-
(async () => {
|
|
833
|
-
const pythonCode = `
|
|
834
|
-
print("Hello from the Code Interpreter!")
|
|
835
|
-
result = 10 + 20
|
|
836
|
-
print(f"The sum is: {result}")
|
|
837
|
-
`;
|
|
838
|
-
|
|
839
|
-
const codeInterpreter = new CodeInterpreterNode();
|
|
840
|
-
codeInterpreter.setParams({
|
|
841
|
-
code: pythonCode,
|
|
842
|
-
timeout: 5000, // Max 5 seconds for execution
|
|
843
|
-
requireConfirmation: false // Set to false to bypass user confirmation
|
|
844
|
-
});
|
|
845
|
-
|
|
846
|
-
codeInterpreter.postAsync = async (shared, prepRes, execRes) => {
|
|
847
|
-
console.log('--- Code Interpreter Output ---');
|
|
848
|
-
console.log('Stdout:', execRes.stdout);
|
|
849
|
-
console.log('Stderr:', execRes.stderr);
|
|
850
|
-
console.log('Exit Code:', execRes.exitCode);
|
|
851
|
-
return 'default';
|
|
852
|
-
};
|
|
853
|
-
|
|
854
|
-
const flow = new AsyncFlow(codeInterpreter);
|
|
855
|
-
try {
|
|
856
|
-
await flow.runAsync({});
|
|
857
|
-
} catch (error) {
|
|
858
|
-
console.error('Code Interpreter Flow Failed:', error);
|
|
859
|
-
}
|
|
860
|
-
})();
|
|
861
|
-
```
|
|
862
|
-
|
|
863
|
-
### 15. Memory Node (Lightweight RAG)
|
|
864
|
-
|
|
865
|
-
Storing and retrieving text-based memories for lightweight Retrieval-Augmented Generation (RAG).
|
|
866
|
-
|
|
867
|
-
```javascript
|
|
868
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
869
|
-
import { MemoryNode, DeepSeekLLMNode } from '@fractal-solutions/qflow/nodes';
|
|
870
|
-
|
|
871
|
-
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
|
|
872
|
-
|
|
873
|
-
(async () => {
|
|
874
|
-
if (!DEEPSEEK_API_KEY) {
|
|
875
|
-
console.warn("WARNING: DEEPSEEK_API_KEY is not set. Please set it to run the MemoryNode RAG example.");
|
|
876
|
-
return;
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
console.log('--- Running MemoryNode RAG Example ---');
|
|
880
|
-
|
|
881
|
-
// 1. Store a memory
|
|
882
|
-
const storeMemory = new MemoryNode();
|
|
883
|
-
storeMemory.setParams({
|
|
884
|
-
action: 'store',
|
|
885
|
-
content: 'The capital of France is Paris. It is known for the Eiffel Tower.',
|
|
886
|
-
id: 'france_capital'
|
|
887
|
-
});
|
|
888
|
-
await new AsyncFlow(storeMemory).runAsync({});
|
|
889
|
-
console.log('Memory stored.');
|
|
890
|
-
|
|
891
|
-
// 2. Store another memory for RAG
|
|
892
|
-
const storeRagMemory = new MemoryNode();
|
|
893
|
-
storeRagMemory.setParams({
|
|
894
|
-
action: 'store',
|
|
895
|
-
content: 'The primary function of a CPU is to execute instructions that make up a computer program.',
|
|
896
|
-
id: 'cpu_function'
|
|
897
|
-
});
|
|
898
|
-
await new AsyncFlow(storeRagMemory).runAsync({});
|
|
899
|
-
console.log('Another memory stored.');
|
|
900
|
-
|
|
901
|
-
// 3. Retrieve relevant memories based on a query
|
|
902
|
-
const ragRetrieve = new MemoryNode();
|
|
903
|
-
ragRetrieve.setParams({
|
|
904
|
-
action: 'retrieve',
|
|
905
|
-
query: 'computer program'
|
|
906
|
-
});
|
|
907
|
-
|
|
908
|
-
// 4. Use an LLM to answer a question based on retrieved memories
|
|
909
|
-
const ragLLM = new DeepSeekLLMNode();
|
|
910
|
-
ragLLM.preparePrompt = (shared) => {
|
|
911
|
-
const retrievedContent = shared.memoryResult.map(mem => mem.content).join('\n\n');
|
|
912
|
-
ragLLM.setParams({
|
|
913
|
-
apiKey: DEEPSEEK_API_KEY,
|
|
914
|
-
prompt: `Based on the following context, answer the question:\n\nContext:\n${retrievedContent}\n\nQuestion: What is the main role of a CPU?`,
|
|
915
|
-
keyword: 'rag_llm'
|
|
916
|
-
});
|
|
917
|
-
};
|
|
918
|
-
|
|
919
|
-
ragRetrieve.next(ragLLM);
|
|
920
|
-
|
|
921
|
-
const ragFlow = new AsyncFlow(ragRetrieve);
|
|
922
|
-
try {
|
|
923
|
-
const ragResult = await ragFlow.runAsync({});
|
|
924
|
-
console.log('\n--- RAG Example LLM Response ---');
|
|
925
|
-
console.log(ragResult);
|
|
926
|
-
} catch (error) {
|
|
927
|
-
console.error('RAG Flow Failed:', error);
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
console.log('\n--- MemoryNode RAG Example Finished ---');
|
|
931
|
-
})();
|
|
932
|
-
```
|
|
933
|
-
|
|
934
|
-
### 16. Transform Node
|
|
935
|
-
|
|
936
|
-
Dynamically transforming data using custom JavaScript functions.
|
|
937
|
-
|
|
938
|
-
```javascript
|
|
939
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
940
|
-
import { TransformNode } from '@fractal-solutions/qflow/nodes';
|
|
941
|
-
|
|
942
|
-
(async () => {
|
|
943
|
-
console.log('--- Running TransformNode Example ---');
|
|
944
|
-
|
|
945
|
-
// Example 1: Map an array of numbers
|
|
946
|
-
const numbers = [1, 2, 3];
|
|
947
|
-
const doubleNumbers = new TransformNode();
|
|
948
|
-
doubleNumbers.setParams({
|
|
949
|
-
input: numbers,
|
|
950
|
-
transformFunction: '(data) => data.map(x => x * 2)'
|
|
951
|
-
});
|
|
952
|
-
|
|
953
|
-
const flow1 = new AsyncFlow(doubleNumbers);
|
|
954
|
-
try {
|
|
955
|
-
const result = await flow1.runAsync({});
|
|
956
|
-
console.log('Doubled Numbers:', result); // Expected: [2, 4, 6]
|
|
957
|
-
} catch (error) {
|
|
958
|
-
console.error('Transform Flow 1 Failed:', error);
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
// Example 2: Filter an array of objects
|
|
962
|
-
const users = [
|
|
963
|
-
{ name: 'Alice', active: true },
|
|
964
|
-
{ name: 'Bob', active: false },
|
|
965
|
-
{ name: 'Charlie', active: true }
|
|
966
|
-
];
|
|
967
|
-
const activeUsers = new TransformNode();
|
|
968
|
-
activeUsers.setParams({
|
|
969
|
-
input: users,
|
|
970
|
-
transformFunction: '(data) => data.filter(user => user.active)'
|
|
971
|
-
});
|
|
972
|
-
|
|
973
|
-
const flow2 = new AsyncFlow(activeUsers);
|
|
974
|
-
try {
|
|
975
|
-
const result = await flow2.runAsync({});
|
|
976
|
-
console.log('Active Users:', result); // Expected: [{ name: 'Alice', active: true }, { name: 'Charlie', active: true }]
|
|
977
|
-
} catch (error) {
|
|
978
|
-
console.error('Transform Flow 2 Failed:', error);
|
|
979
|
-
}
|
|
980
|
-
|
|
981
|
-
// Example 3: Extract a specific property from an object
|
|
982
|
-
const product = { id: 1, name: 'Laptop', price: 1200 };
|
|
983
|
-
const productName = new TransformNode();
|
|
984
|
-
productName.setParams({
|
|
985
|
-
input: product,
|
|
986
|
-
transformFunction: '(data) => data.name'
|
|
987
|
-
});
|
|
988
|
-
|
|
989
|
-
const flow3 = new AsyncFlow(productName);
|
|
990
|
-
try {
|
|
991
|
-
const result = await flow3.runAsync({});
|
|
992
|
-
console.log('Product Name:', result); // Expected: 'Laptop'
|
|
993
|
-
} catch (error) {
|
|
994
|
-
console.error('Transform Flow 3 Failed:', error);
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
console.log('\n--- TransformNode Example Finished ---');
|
|
998
|
-
})();
|
|
999
|
-
```
|
|
1000
|
-
|
|
1001
|
-
### 17. Plotting Data with Python Code Interpreter
|
|
1002
|
-
|
|
1003
|
-
Demonstrates using the `CodeInterpreterNode` to execute Python code for data visualization, saving the output to a file.
|
|
1004
|
-
|
|
1005
|
-
**Prerequisites:** To run this example, you need Python and `matplotlib` installed. It is highly recommended to use a Python [virtual environment](https://docs.python.org/3/library/venv.html) to manage your Python dependencies.
|
|
1006
|
-
|
|
1007
|
-
Follow these steps in *your project folder* where you are using `qflow`:
|
|
1008
|
-
|
|
1009
|
-
1. **Create a Python Virtual Environment:**
|
|
1010
|
-
```bash
|
|
1011
|
-
python3 -m venv .venv
|
|
1012
|
-
```
|
|
1013
|
-
|
|
1014
|
-
2. **Activate the Virtual Environment:**
|
|
1015
|
-
* On Linux/macOS:
|
|
1016
|
-
```bash
|
|
1017
|
-
source .venv/bin/activate
|
|
1018
|
-
```
|
|
1019
|
-
* On Windows (Command Prompt):
|
|
1020
|
-
```bash
|
|
1021
|
-
.venv\Scripts\activate.bat
|
|
1022
|
-
```
|
|
1023
|
-
* On Windows (PowerShell):
|
|
1024
|
-
```powershell
|
|
1025
|
-
.venv\Scripts\Activate.ps1
|
|
1026
|
-
```
|
|
1027
|
-
|
|
1028
|
-
3. **Install `matplotlib` (and any other Python libraries) within the activated environment:**
|
|
1029
|
-
```bash
|
|
1030
|
-
pip install matplotlib
|
|
1031
|
-
```
|
|
1032
|
-
|
|
1033
|
-
4. **Configure the Python Interpreter Path:**
|
|
1034
|
-
Create or update a `.env` file in your project's root directory (where your `qflow` application runs) and add the following line, pointing to the Python executable within your virtual environment:
|
|
1035
|
-
```bash
|
|
1036
|
-
QFLOW_PYTHON_INTERPRETER=/path/to/your/project/.venv/bin/python
|
|
1037
|
-
# Example for Windows:
|
|
1038
|
-
# QFLOW_PYTHON_INTERPRETER=C:\path\to\your\project\.venv\Scripts\python.exe
|
|
1039
|
-
```
|
|
1040
|
-
*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.*
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
```javascript
|
|
1044
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
1045
|
-
import { CodeInterpreterNode, WriteFileNode } from '@fractal-solutions/qflow/nodes';
|
|
1046
|
-
import path from 'path';
|
|
1047
|
-
import os from 'os';
|
|
1048
|
-
|
|
1049
|
-
(async () => {
|
|
1050
|
-
console.log('--- Running Plot Data with Python CodeInterpreter Example ---');
|
|
1051
|
-
|
|
1052
|
-
// 1. Define sample data
|
|
1053
|
-
const dataToPlot = {
|
|
1054
|
-
x: [1, 2, 3, 4, 5],
|
|
1055
|
-
y: [2, 4, 5, 4, 6]
|
|
1056
|
-
};
|
|
1057
|
-
|
|
1058
|
-
// Define temporary file paths
|
|
1059
|
-
const tempDir = os.tmpdir();
|
|
1060
|
-
const dataFileName = `plot_data_${Date.now()}.json`;
|
|
1061
|
-
const plotFileName = `sample_plot_${Date.now()}.png`;
|
|
1062
|
-
const dataFilePath = path.join(tempDir, dataFileName);
|
|
1063
|
-
const plotFilePath = path.join(tempDir, plotFileName);
|
|
1064
|
-
|
|
1065
|
-
// 2. Python script for plotting
|
|
1066
|
-
const pythonPlotScript = `
|
|
1067
|
-
import matplotlib.pyplot as plt
|
|
1068
|
-
import json
|
|
1069
|
-
import sys
|
|
1070
|
-
|
|
1071
|
-
# Get data file path and output plot path from command line arguments
|
|
1072
|
-
data_file_path = sys.argv[1]
|
|
1073
|
-
output_plot_path = sys.argv[2]
|
|
1074
|
-
|
|
1075
|
-
# Read data from the specified JSON file
|
|
1076
|
-
with open(data_file_path, 'r') as f:
|
|
1077
|
-
data = json.load(f)
|
|
1078
|
-
|
|
1079
|
-
x_data = data['x']
|
|
1080
|
-
y_data = data['y']
|
|
1081
|
-
|
|
1082
|
-
# Create the plot
|
|
1083
|
-
plt.figure(figsize=(8, 6))
|
|
1084
|
-
plt.plot(x_data, y_data, marker='o', linestyle='-', color='b')
|
|
1085
|
-
plt.title('Sample Data Plot')
|
|
1086
|
-
plt.xlabel('X-axis')
|
|
1087
|
-
plt.ylabel('Y-axis')
|
|
1088
|
-
plt.grid(True)
|
|
1089
|
-
|
|
1090
|
-
# Save the plot
|
|
1091
|
-
plt.savefig(output_plot_path)
|
|
1092
|
-
print(f"Plot saved to {output_plot_path}")
|
|
1093
|
-
`;
|
|
1094
|
-
|
|
1095
|
-
// 3. Write data to a temporary JSON file
|
|
1096
|
-
const writeDataNode = new WriteFileNode();
|
|
1097
|
-
writeDataNode.setParams({
|
|
1098
|
-
filePath: dataFilePath,
|
|
1099
|
-
content: JSON.stringify(dataToPlot)
|
|
1100
|
-
});
|
|
1101
|
-
|
|
1102
|
-
// 4. Run the Python script using CodeInterpreterNode
|
|
1103
|
-
const plotNode = new CodeInterpreterNode();
|
|
1104
|
-
plotNode.setParams({
|
|
1105
|
-
code: pythonPlotScript,
|
|
1106
|
-
args: [dataFilePath, plotFilePath], // Pass data file and output plot paths as arguments
|
|
1107
|
-
timeout: 15000, // Increased timeout for plotting
|
|
1108
|
-
requireConfirmation: false, // No confirmation needed for this automated task
|
|
1109
|
-
interpreterPath: process.env.QFLOW_PYTHON_INTERPRETER || 'python' // Allow user to specify Python interpreter path, defaults to 'python'
|
|
1110
|
-
});
|
|
1111
|
-
|
|
1112
|
-
// 5. Chain the nodes
|
|
1113
|
-
writeDataNode.next(plotNode);
|
|
1114
|
-
|
|
1115
|
-
// 6. Run the flow
|
|
1116
|
-
const flow = new AsyncFlow(writeDataNode);
|
|
1117
|
-
try {
|
|
1118
|
-
await flow.runAsync({});
|
|
1119
|
-
console.log(`\nPlotting workflow finished. Check for plot at: ${plotFilePath}`);
|
|
1120
|
-
} catch (error) {
|
|
1121
|
-
console.error('Plotting Workflow Failed:', error);
|
|
1122
|
-
}
|
|
1123
|
-
})();
|
|
1124
|
-
```
|
|
1125
|
-
|
|
1126
|
-
### 18. Embedding Node
|
|
1127
|
-
|
|
1128
|
-
Generates vector embeddings for text using a local Ollama server. Essential for semantic search and RAG.
|
|
1129
|
-
|
|
1130
|
-
**Prerequisites:** Ensure you have [Ollama](https://ollama.ai/) installed and an embedding model pulled (e.g., `ollama pull nomic-embed-text`).
|
|
1131
|
-
|
|
1132
|
-
```javascript
|
|
1133
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
1134
|
-
import { EmbeddingNode } from '@fractal-solutions/qflow/nodes';
|
|
1135
|
-
|
|
1136
|
-
(async () => {
|
|
1137
|
-
console.log('--- Running EmbeddingNode Example ---');
|
|
1138
|
-
|
|
1139
|
-
const textToEmbed = "Hello, world! This is a test sentence.";
|
|
1140
|
-
const embedNode = new EmbeddingNode();
|
|
1141
|
-
embedNode.setParams({
|
|
1142
|
-
text: textToEmbed,
|
|
1143
|
-
model: 'nomic-embed-text', // Ensure this model is pulled in Ollama
|
|
1144
|
-
baseUrl: 'http://localhost:11434' // Default Ollama URL
|
|
1145
|
-
});
|
|
1146
|
-
|
|
1147
|
-
embedNode.postAsync = async (shared, prepRes, execRes) => {
|
|
1148
|
-
console.log('Embedding Result (first 5 dimensions):', execRes.embedding.slice(0, 5));
|
|
1149
|
-
console.log('Embedding Length:', execRes.embedding.length);
|
|
1150
|
-
return 'default';
|
|
1151
|
-
};
|
|
1152
|
-
|
|
1153
|
-
const flow = new AsyncFlow(embedNode);
|
|
1154
|
-
try {
|
|
1155
|
-
await flow.runAsync({});
|
|
1156
|
-
} catch (error) {
|
|
1157
|
-
console.error('Embedding Flow Failed:', error);
|
|
1158
|
-
}
|
|
1159
|
-
|
|
1160
|
-
console.log('\n--- EmbeddingNode Example Finished ---');
|
|
1161
|
-
})();
|
|
1162
|
-
```
|
|
1163
|
-
|
|
1164
|
-
### 19. Semantic Memory Node
|
|
1165
|
-
|
|
1166
|
-
Stores and retrieves text-based memories using vector embeddings for semantic search. This enables agents to have a more advanced, meaning-based long-term memory.
|
|
1167
|
-
|
|
1168
|
-
**Prerequisites:** Requires [Ollama](https://ollama.ai/) and an embedding model (e.g., `ollama pull nomic-embed-text`).
|
|
1169
|
-
|
|
1170
|
-
```javascript
|
|
1171
|
-
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
1172
|
-
import { SemanticMemoryNode, DeepSeekLLMNode } from '@fractal-solutions/qflow/nodes';
|
|
1173
|
-
|
|
1174
|
-
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
|
|
1175
|
-
|
|
1176
|
-
(async () => {
|
|
1177
|
-
if (!DEEPSEEK_API_KEY) {
|
|
1178
|
-
console.warn("WARNING: DEEPSEEK_API_KEY is not set. Please set it to run the SemanticMemoryNode RAG example.");
|
|
1179
|
-
return;
|
|
1180
|
-
}
|
|
1181
|
-
|
|
1182
|
-
console.log('--- Running SemanticMemoryNode RAG Example ---');
|
|
1183
|
-
|
|
1184
|
-
// 1. Store a semantic memory
|
|
1185
|
-
const storeSemanticMemory = new SemanticMemoryNode();
|
|
1186
|
-
storeSemanticMemory.setParams({
|
|
1187
|
-
action: 'store',
|
|
1188
|
-
content: 'The capital of France is Paris. It is known for the Eiffel Tower and its romantic atmosphere.',
|
|
1189
|
-
id: 'france_capital_sem',
|
|
1190
|
-
metadata: { source: 'wikipedia', topic: 'geography' }
|
|
1191
|
-
});
|
|
1192
|
-
await new AsyncFlow(storeSemanticMemory).runAsync({});
|
|
1193
|
-
console.log('Semantic memory stored.');
|
|
1194
|
-
|
|
1195
|
-
// 2. Store another memory for RAG
|
|
1196
|
-
const storeRagSemanticMemory = new SemanticMemoryNode();
|
|
1197
|
-
storeRagSemanticMemory.setParams({
|
|
1198
|
-
action: 'store',
|
|
1199
|
-
content: 'Quantum computing uses quantum-mechanical phenomena like superposition and entanglement to perform computations.',
|
|
1200
|
-
id: 'quantum_comp_intro',
|
|
1201
|
-
metadata: { topic: 'physics' }
|
|
1202
|
-
});
|
|
1203
|
-
await new AsyncFlow(storeRagSemanticMemory).runAsync({});
|
|
1204
|
-
console.log('Another semantic memory stored.');
|
|
1205
|
-
|
|
1206
|
-
// 3. Retrieve relevant semantic memories based on a query
|
|
1207
|
-
const ragRetrieveSemantic = new SemanticMemoryNode();
|
|
1208
|
-
ragRetrieveSemantic.setParams({
|
|
1209
|
-
action: 'retrieve',
|
|
1210
|
-
query: 'city of love',
|
|
1211
|
-
topK: 1
|
|
1212
|
-
});
|
|
1213
|
-
|
|
1214
|
-
// 4. Use an LLM to answer a question based on retrieved memories
|
|
1215
|
-
const ragLLM = new DeepSeekLLMNode();
|
|
1216
|
-
ragLLM.setParams({ apiKey: DEEPSEEK_API_KEY });
|
|
1217
|
-
|
|
1218
|
-
ragRetrieveSemantic.next(ragLLM);
|
|
1219
|
-
|
|
1220
|
-
ragLLM.preparePrompt = (shared) => {
|
|
1221
|
-
const retrievedContent = shared.semanticMemoryResult.map(mem => mem.content).join('\n\n');
|
|
1222
|
-
ragLLM.setParams({
|
|
1223
|
-
prompt: `Based on the following context, answer the question:\n\nContext:\n${retrievedContent}\n\nQuestion: Explain quantum computing in simple terms.`,
|
|
1224
|
-
keyword: 'semantic_rag_llm'
|
|
1225
|
-
});
|
|
1226
|
-
};
|
|
1227
|
-
|
|
1228
|
-
const ragFlow = new AsyncFlow(ragRetrieveSemantic);
|
|
1229
|
-
try {
|
|
1230
|
-
const ragResult = await ragFlow.runAsync({});
|
|
1231
|
-
console.log('\n--- Semantic RAG Example LLM Response ---');
|
|
1232
|
-
console.log(ragResult);
|
|
1233
|
-
} catch (error) {
|
|
1234
|
-
console.error('RAG Flow Failed:', error);
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
console.log('\n--- SemanticMemoryNode RAG Example Finished ---');
|
|
1238
|
-
})();
|
|
1239
|
-
```
|
|
62
|
+
See [documentation/examples.md](documentation/examples.md) for a full list of examples.
|
|
1240
63
|
|
|
1241
64
|
|
|
1242
65
|
|
|
@@ -1349,218 +172,5 @@ test("Node should handle parameters via setParams", () => {
|
|
|
1349
172
|
|
|
1350
173
|
We welcome contributions! Please see our GitHub repository for more details on how to contribute.
|
|
1351
174
|
|
|
1352
|
-
---
|
|
1353
|
-
|
|
1354
|
-
## Available Tools for Agents
|
|
1355
|
-
|
|
1356
|
-
The `AgentNode` can be equipped with a variety of tools to perform a wide range of tasks. Below is a list of the built-in tools and their functionalities.
|
|
1357
|
-
|
|
1358
|
-
### Core Tools
|
|
1359
|
-
|
|
1360
|
-
* **finish**: Ends the agent's execution and returns a final output.
|
|
1361
|
-
* `output`: A summary of the final result or the reason for stopping.
|
|
1362
|
-
* **user_input**: Prompts the user for input and waits for their response.
|
|
1363
|
-
* `prompt`: The message to display to the user.
|
|
1364
|
-
* **interactive_input**: Prompts the user for input via a GUI popup (cross-platform).
|
|
1365
|
-
* `prompt`: The message to display in the input dialog.
|
|
1366
|
-
* `title`: Optional. The title of the input dialog. Defaults to 'QFlow Input'.
|
|
1367
|
-
* `defaultValue`: Optional. The default value to pre-fill in the input field.
|
|
1368
|
-
|
|
1369
|
-
### File System
|
|
1370
|
-
|
|
1371
|
-
* **read_file**: Reads the content of a specified file.
|
|
1372
|
-
* `filePath`: The absolute path to the file to read.
|
|
1373
|
-
* **write_file**: Writes content to a specified file.
|
|
1374
|
-
* `filePath`: The absolute path to the file to write to.
|
|
1375
|
-
* `content`: The content to write to the file.
|
|
1376
|
-
* **append_file**: Appends content to an existing file.
|
|
1377
|
-
* `filePath`: The absolute path to the file to append to.
|
|
1378
|
-
* `content`: The content to append to the file.
|
|
1379
|
-
* **list_directory**: Lists the files and subdirectories within a specified directory.
|
|
1380
|
-
* `directoryPath`: The absolute path to the directory to list.
|
|
1381
|
-
|
|
1382
|
-
### Web
|
|
1383
|
-
|
|
1384
|
-
* **duckduckgo_search**: Performs a web search using DuckDuckGo.
|
|
1385
|
-
* `query`: The search query.
|
|
1386
|
-
* **google_search**: Performs a web search using the Google Custom Search API.
|
|
1387
|
-
* `query`: The search query.
|
|
1388
|
-
* `apiKey`: Your Google API Key.
|
|
1389
|
-
* `cseId`: Your Custom Search Engine ID.
|
|
1390
|
-
* **http_request**: Makes a generic HTTP request to any URL.
|
|
1391
|
-
* `url`: The full URL of the API endpoint.
|
|
1392
|
-
* `method`: The HTTP method to use (e.g., 'GET', 'POST').
|
|
1393
|
-
* `headers`: Custom headers for the request.
|
|
1394
|
-
* `body`: The request payload.
|
|
1395
|
-
* `auth`: Authentication configuration.
|
|
1396
|
-
* **web_scraper**: Fetches the HTML content of a given URL.
|
|
1397
|
-
* `url`: The URL to scrape.
|
|
1398
|
-
* **browser_control**: Controls a web browser to navigate pages, interact with elements, and take screenshots.
|
|
1399
|
-
* `action`: The browser action to perform.
|
|
1400
|
-
* `url`: The URL to navigate to (for 'goto' action).
|
|
1401
|
-
* `selector`: A CSS selector to target an element (for 'click' and 'type' actions).
|
|
1402
|
-
* `text`: The text to type into an input field (for 'type' action).
|
|
1403
|
-
* `path`: The file path to save a screenshot (for 'screenshot' action).
|
|
1404
|
-
|
|
1405
|
-
### Data & Code
|
|
1406
|
-
|
|
1407
|
-
* **data_extractor**: Extracts structured data from HTML, JSON, or plain text.
|
|
1408
|
-
* `input`: The content string from which to extract data.
|
|
1409
|
-
* `type`: The type of content to extract from (html, json, or text).
|
|
1410
|
-
* `selector`: A CSS selector to target elements (for HTML).
|
|
1411
|
-
* `jsonPath`: A dot-notation path to extract data (for JSON).
|
|
1412
|
-
* `regex`: A regular expression to match and extract data (for text).
|
|
1413
|
-
* `group`: The capturing group index to return from the regex match.
|
|
1414
|
-
* **code_interpreter**: Executes Python code snippets.
|
|
1415
|
-
* `code`: The Python code snippet to execute.
|
|
1416
|
-
* `timeout`: Maximum execution time in milliseconds.
|
|
1417
|
-
* `args`: Command-line arguments to pass to the script.
|
|
1418
|
-
* `requireConfirmation`: If true, the user will be prompted for confirmation before executing the code.
|
|
1419
|
-
* **transform_node**: Transforms input data using a provided JavaScript function.
|
|
1420
|
-
* `input`: The data to be transformed.
|
|
1421
|
-
* `transformFunction`: A JavaScript function string that takes 'data' as an argument and returns the transformed result.
|
|
1422
|
-
* **pdf_processor**: Extracts text or images from PDF documents.
|
|
1423
|
-
* `filePath`: The absolute path to the PDF file.
|
|
1424
|
-
* `action`: The action to perform: 'extract_text' or 'extract_images'.
|
|
1425
|
-
* `outputDir`: Optional. Directory to save extracted files. If not provided, a temporary directory will be used.
|
|
1426
|
-
* `pageRange`: Optional. Page range to process (e.g., {start: 1, end: 5}).
|
|
1427
|
-
* `password`: Optional. Password for encrypted PDFs.
|
|
1428
|
-
* **spreadsheet**: Reads from and writes to spreadsheet files (.xlsx, .xls, .csv) with advanced manipulation.
|
|
1429
|
-
* `action`: The action to perform.
|
|
1430
|
-
* `filePath`: The absolute path to the spreadsheet file.
|
|
1431
|
-
* `sheetName`: Required for .xlsx/.xls files and sheet-specific actions. The name of the sheet.
|
|
1432
|
-
* `data`: Required for 'write', 'write_range', 'append_rows'. The data to write (array of arrays or array of objects).
|
|
1433
|
-
* `headerRow`: Optional. True if the first row is a header. Defaults to true.
|
|
1434
|
-
* `range`: Required for 'read_range', 'write_range', 'format_cells'. A1 notation (e.g., 'Sheet1!A1:C10').
|
|
1435
|
-
* `startRow`: Required for 'delete_rows', 'insert_rows'. The 1-indexed starting row.
|
|
1436
|
-
* `numRows`: Required for 'delete_rows', 'insert_rows'. The number of rows to delete/insert.
|
|
1437
|
-
* `newSheetName`: Required for 'add_sheet', 'rename_sheet'. The name of the new sheet.
|
|
1438
|
-
* `formats`: Required for 'format_cells'. Formatting options (conceptual, basic XLSX.js has limited styling).
|
|
1439
|
-
* **data_validation**: Validates structured data against a JSON Schema.
|
|
1440
|
-
* `data`: The data to be validated.
|
|
1441
|
-
* `schema`: The JSON Schema object directly.
|
|
1442
|
-
* `schemaPath`: Optional. Path to a JSON Schema file. If provided, 'schema' parameter is ignored.
|
|
1443
|
-
* `action`: The action to perform. Currently only 'validate' is supported.
|
|
1444
|
-
|
|
1445
|
-
### Memory & Embeddings
|
|
1446
|
-
|
|
1447
|
-
* **memory_node**: Stores and retrieves text memories (keyword-based).
|
|
1448
|
-
* `action`: The action to perform: 'store' or 'retrieve'.
|
|
1449
|
-
* `content`: Required for 'store' action. The text content of the memory to store.
|
|
1450
|
-
* `query`: Required for 'retrieve' action. Keywords to search for within stored memories.
|
|
1451
|
-
* `id`: Optional for 'store' action. A unique identifier for the memory. If not provided, one will be generated.
|
|
1452
|
-
* `memoryPath`: Optional. The directory path where memories are stored. Defaults to './agent_memories'.
|
|
1453
|
-
* **semantic_memory_node**: Stores and retrieves text memories via semantic search (requires Ollama).
|
|
1454
|
-
* `action`: The action to perform: 'store' or 'retrieve'.
|
|
1455
|
-
* `content`: Required for 'store' action. The text content of the memory to store.
|
|
1456
|
-
* `query`: Required for 'retrieve' action. The text query for semantic search.
|
|
1457
|
-
* `id`: Optional for 'store' action. A unique identifier for the memory. If not provided, one will be generated.
|
|
1458
|
-
* `metadata`: Optional for 'store' action. Key-value pairs to store alongside the memory.
|
|
1459
|
-
* `memoryPath`: Optional. The directory path where memories and the index are stored. Defaults to './semantic_memories'.
|
|
1460
|
-
* `embeddingModel`: Optional. The Ollama embedding model name to use (e.g., 'nomic-embed-text'). Defaults to 'nomic-embed-text'.
|
|
1461
|
-
* `embeddingBaseUrl`: Optional. The base URL of the Ollama API for embeddings. Defaults to 'http://localhost:11434'.
|
|
1462
|
-
* `topK`: Optional for 'retrieve' action. The number of top similar results to retrieve. Defaults to 5.
|
|
1463
|
-
* **generate_embedding**: Generates vector embeddings for text (requires Ollama).
|
|
1464
|
-
* `text`: The text string to generate an embedding for.
|
|
1465
|
-
* `model`: Optional. The Ollama embedding model name to use (e.g., 'nomic-embed-text'). Defaults to 'nomic-embed-text'.
|
|
1466
|
-
* `baseUrl`: Optional. The base URL of the Ollama API (e.g., 'http://localhost:11434'). Defaults to 'http://localhost:11434'.
|
|
1467
|
-
|
|
1468
|
-
### Flow Control
|
|
1469
|
-
|
|
1470
|
-
* **sub_flow**: Executes a sub-flow.
|
|
1471
|
-
* `flow`: The name of the flow to execute, as registered in the flow registry.
|
|
1472
|
-
* `shared`: The shared object to pass to the sub-flow.
|
|
1473
|
-
* **iterator**: Iterates items, executes sub-flow for each.
|
|
1474
|
-
* `items`: The list of items to iterate over.
|
|
1475
|
-
* `flow`: The name of the flow to execute for each item, as registered in the flow registry.
|
|
1476
|
-
* **scheduler**: Schedules qflow flows for future or recurring execution using cron syntax or a delay.
|
|
1477
|
-
* `action`: The action to perform: 'start' a new schedule or 'stop' an existing one.
|
|
1478
|
-
* `schedule`: Required for 'start'. A cron string (e.g., '0 3 * * *') or a number in milliseconds for a one-time delay.
|
|
1479
|
-
* `flow`: Required for 'start'. The name of the qflow AsyncFlow instance to trigger.
|
|
1480
|
-
* `flowParams`: Optional. Parameters (shared object) to pass to the triggered flow's runAsync.
|
|
1481
|
-
* `id`: Optional. A unique ID for the scheduled task (required for 'stop' action). If not provided for 'start', a random one will be generated.
|
|
1482
|
-
|
|
1483
|
-
### LLM Reasoning
|
|
1484
|
-
|
|
1485
|
-
* **huggingface_llm_reasoning**: Generates human-like text, reasons, and plans. Not for external actions.
|
|
1486
|
-
* `prompt`: The prompt or question to send to the language model.
|
|
1487
|
-
* `model`: The Hugging Face model ID (e.g., 'HuggingFaceH4/zephyr-7b-beta', 'openai/gpt-oss-20b:novita').
|
|
1488
|
-
* `hfToken`: Your Hugging Face API token.
|
|
1489
|
-
* `temperature`: Optional. Controls randomness. Defaults to 0.7.
|
|
1490
|
-
* `max_new_tokens`: Optional. Maximum number of tokens to generate. Defaults to 500.
|
|
1491
|
-
* `baseUrl`: Optional. The base URL of the Hugging Face router API. Defaults to 'https://router.huggingface.co/v1'.
|
|
1492
|
-
* **llm_reasoning**: Generates human-like text, reasons, and plans. Not for external actions.
|
|
1493
|
-
* `prompt`: The prompt or question to send to the language model.
|
|
1494
|
-
* **openrouter_llm_reasoning**: Generates human-like text, reasons, and plans via OpenRouter. Not for external actions.
|
|
1495
|
-
* `prompt`: The prompt or question to send to the language model.
|
|
1496
|
-
* `model`: The OpenRouter model ID (e.g., 'openai/gpt-4o', 'mistralai/mistral-7b-instruct').
|
|
1497
|
-
* `apiKey`: Your OpenRouter API key.
|
|
1498
|
-
* `siteUrl`: Optional. Site URL for rankings on openrouter.ai.
|
|
1499
|
-
* `siteTitle`: Optional. Site title for rankings on openrouter.ai.
|
|
1500
|
-
* **ollama_llm_reasoning**: Generates human-like text, reasons, and plans locally via Ollama. Not for external actions.
|
|
1501
|
-
* `prompt`: The prompt or question to send to the local Ollama language model.
|
|
1502
|
-
* `model`: The Ollama model name to use (e.g., 'llama2', 'gemma:2b'). Defaults to 'llama2'.
|
|
1503
|
-
* `baseUrl`: The base URL of the Ollama API (e.g., 'http://localhost:11434'). Defaults to 'http://localhost:11434'.
|
|
1504
|
-
|
|
1505
|
-
### System & Hardware
|
|
1506
175
|
|
|
1507
|
-
* **shell_command**: Executes shell commands.
|
|
1508
|
-
* `command`: The full shell command to execute (e.g., 'ls -l', 'npm install cheerio').
|
|
1509
|
-
* **system_notification**: Displays a system-level notification across OSs.
|
|
1510
|
-
* `message`: The main message content of the notification.
|
|
1511
|
-
* `title`: Optional. The title of the notification. Defaults to 'QFlow Notification'.
|
|
1512
|
-
* `icon`: Optional. Path to an icon file or a system icon name (Linux specific). Ignored on macOS/Windows.
|
|
1513
|
-
* **display_image**: Displays an image file using the system's default image viewer.
|
|
1514
|
-
* `imagePath`: The absolute path to the image file to display.
|
|
1515
|
-
* **hardware_interaction**: Communicates with local hardware via serial port (UART).
|
|
1516
|
-
* `action`: The action to perform: 'write', 'read_line', 'list_ports'.
|
|
1517
|
-
* `portPath`: Required for 'write'/'read_line'. The path to the serial port (e.g., '/dev/ttyUSB0', 'COM1').
|
|
1518
|
-
* `baudRate`: Optional. The baud rate for serial communication. Defaults to 9600.
|
|
1519
|
-
* `dataToWrite`: Required for 'write'. The data string to send to the serial port.
|
|
1520
|
-
* `timeout`: Optional. Timeout in milliseconds for 'read_line' action. Defaults to 5000.
|
|
1521
|
-
* **image_gallery**: Generates an HTML gallery from multiple image files and opens it in a web browser.
|
|
1522
|
-
* `imagePaths`: An array of absolute paths to the image files to display in the gallery.
|
|
1523
|
-
* `title`: Optional. The title of the HTML gallery page. Defaults to 'Image Gallery'.
|
|
1524
|
-
* `description`: Optional. A short description to display on the gallery page. Defaults to 'Generated by QFlow Agent'.
|
|
1525
|
-
* `outputDir`: Optional. Directory to save the generated HTML file and copied images. Defaults to a temporary directory.
|
|
1526
|
-
* **speech_synthesis**: Converts text to spoken audio using OS capabilities or cloud APIs.
|
|
1527
|
-
* `text`: The text to convert to speech.
|
|
1528
|
-
* `provider`: Optional. The speech synthesis provider to use. Defaults to OS-specific. 'google' requires GOOGLE_TTS_API_KEY.
|
|
1529
|
-
* `voice`: Optional. The specific voice to use (e.g., 'Alex' for macOS, 'en-us' for espeak, 'en-US-Wavenet-D' for Google).
|
|
1530
|
-
* `outputFilePath`: Optional. If provided, saves the audio to this file path instead of playing it directly.
|
|
1531
|
-
* **multimedia_processing**: Performs various multimedia operations on audio and video files using ffmpeg.
|
|
1532
|
-
* `action`: The multimedia operation to perform.
|
|
1533
|
-
* `inputPath`: Path to the input multimedia file.
|
|
1534
|
-
* `outputPath`: Path for the output file.
|
|
1535
|
-
* `format`: Required for 'convert' and 'extract_audio'. The output format (e.g., 'mp4', 'mp3', 'gif', 'wav').
|
|
1536
|
-
* `startTime`: Required for 'trim'. Start time in HH:MM:SS or seconds (e.g., '00:00:10', '10').
|
|
1537
|
-
* `duration`: Required for 'trim'. Duration in HH:MM:SS or seconds (e.g., '00:00:05', '5').
|
|
1538
|
-
* `resolution`: Optional for video 'convert'. Resolution (e.g., '1280x720').
|
|
1539
|
-
* `frameTime`: Required for 'extract_frame'. Time to extract frame from in HH:MM:SS or seconds (e.g., '00:00:05').
|
|
1540
|
-
* `ffmpegArgs`: Required for 'custom'. Raw ffmpeg arguments to execute directly.
|
|
1541
|
-
* **remote_execution**: Executes commands on remote machines via SSH.
|
|
1542
|
-
* `host`: The hostname or IP address of the remote machine.
|
|
1543
|
-
* `port`: Optional. The SSH port. Defaults to 22.
|
|
1544
|
-
* `username`: The username for SSH authentication.
|
|
1545
|
-
* `password`: Optional. The password for SSH authentication (use with caution, prefer privateKey).
|
|
1546
|
-
* `privateKey`: Optional. The content of the private SSH key or its absolute path.
|
|
1547
|
-
* `passphrase`: Optional. The passphrase for an encrypted private key.
|
|
1548
|
-
* `action`: The action to perform. Currently only 'execute_command' is supported.
|
|
1549
|
-
* `command`: The command string to execute on the remote machine.
|
|
1550
|
-
* `timeout`: Optional. Timeout in milliseconds for the command execution. Defaults to 30000 (30 seconds).
|
|
1551
|
-
* **webhook**: Exposes an HTTP endpoint to receive webhooks, triggering a specified qflow flow.
|
|
1552
|
-
* `port`: Optional. The port number to listen on. Defaults to 3000.
|
|
1553
|
-
* `path`: Optional. The URL path for the webhook endpoint. Defaults to '/webhook'.
|
|
1554
|
-
* `flow`: The name of the qflow AsyncFlow instance to trigger when a webhook is received.
|
|
1555
|
-
* `sharedSecret`: Optional. A shared secret for HMAC verification of incoming webhooks.
|
|
1556
|
-
* `responseStatus`: Optional. The HTTP status code to send back to the webhook sender. Defaults to 200.
|
|
1557
|
-
* `responseBody`: Optional. The JSON body to send back to the webhook sender. Defaults to { status: 'received' }.
|
|
1558
|
-
* **git**: Performs Git operations like clone, add, commit, and push.
|
|
1559
|
-
* `action`: The Git action to perform.
|
|
1560
|
-
* `repoPath`: The local path to the repository.
|
|
1561
|
-
* `remoteUrl`: The URL of the remote repository (for 'clone' action).
|
|
1562
|
-
* `files`: An array of file paths to add to the staging area (for 'add' action).
|
|
1563
|
-
* `message`: The commit message (for 'commit' action).
|
|
1564
|
-
* `branch`: The branch to push to or pull from.
|
|
1565
|
-
* `remote`: The name of the remote (e.g., 'origin').
|
|
1566
176
|
|