@fractal-solutions/qflow 1.0.0 → 1.0.1
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 +226 -391
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,498 +1,333 @@
|
|
|
1
|
-
# qflow
|
|
1
|
+
# qflow: A Lightweight and Flexible JavaScript Workflow and Agent Library
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`qflow` is a lightweight and flexible JavaScript library designed for creating and managing complex workflows and autonomous agents. Inspired by the simplicity and power of flow-based programming, `qflow` provides a minimalist yet expressive API to define sequences of operations, handle data flow, and manage execution, both synchronously and asynchronously.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
qflow allows you to define complex workflows as a series of connected nodes. Each node represents a step in the process, and you can control the flow of execution based on the outcome of each step.
|
|
8
|
-
|
|
9
|
-
* **`Node`**: The fundamental building block of a qflow. A `Node` is a single step in your workflow. It has three main lifecycle methods:
|
|
10
|
-
* `prep(shared)`: Prepare data for the `exec` method. The `shared` object is passed through the entire flow.
|
|
11
|
-
* `exec(prepRes)`: The main logic of the node. It receives the result from the `prep` method.
|
|
12
|
-
* `post(shared, prepRes, execRes)`: Clean up or process the results after the `exec` method. **The return value of this method determines the next action in the flow.**
|
|
13
|
-
|
|
14
|
-
* **`Flow`**: A `Flow` manages the execution of a series of connected `Node`s. You define the starting node and the transitions between nodes.
|
|
5
|
+
With zero external dependencies for its core functionality, `qflow` is built for performance and ease of integration into any JavaScript environment, from Node.js backends to browser-based applications.
|
|
15
6
|
|
|
16
7
|
## Features
|
|
17
8
|
|
|
18
|
-
* **
|
|
19
|
-
* **
|
|
20
|
-
* **
|
|
21
|
-
* **
|
|
22
|
-
* **Conditional Transitions
|
|
23
|
-
|
|
24
|
-
## Understanding Nodes, Flows, and Data Management
|
|
25
|
-
|
|
26
|
-
### Nodes: The Building Blocks
|
|
27
|
-
|
|
28
|
-
Each `Node` in qflow represents a distinct step in your workflow. Nodes are designed with a clear lifecycle to manage their execution:
|
|
9
|
+
* **Modular & Extensible:** Easily define custom nodes and compose them into complex flows.
|
|
10
|
+
* **Synchronous & Asynchronous Flows:** Supports both blocking and non-blocking execution patterns.
|
|
11
|
+
* **Batch Processing:** Efficiently process collections of data through dedicated batch nodes and flows.
|
|
12
|
+
* **Retry Mechanisms:** Built-in support for retrying failed operations with configurable delays.
|
|
13
|
+
* **Conditional Transitions:** Define dynamic flow paths based on execution outcomes.
|
|
14
|
+
* **Built-in Nodes:** Comes with pre-built nodes for common tasks like LLM interactions, web scraping, and API integrations (GitHub, HackerNews, Stripe).
|
|
29
15
|
|
|
30
|
-
|
|
31
|
-
* **`exec(prepRes)`**: This is the core logic of your node. It receives the result from the `prep` method (`prepRes`). The `exec` method should perform the primary task of the node. **The return value of `exec` is crucial for controlling the flow's path.** It can be a string representing an "action" (e.g., "success", "failure", "long", "short") that the `Flow` uses to determine the next node.
|
|
32
|
-
* **`post(shared, prepRes, execRes)`**: This method is called after `exec` completes. It's suitable for cleanup, logging, or further processing of the `exec` result. It receives the `shared` object, the `prepRes`, and the `execRes`. **The return value of `post` also dictates the flow's path, similar to `exec`.** If both `exec` and `post` return a value, the `post` method's return value takes precedence for determining the next transition.
|
|
33
|
-
|
|
34
|
-
### Flows: Orchestrating Execution
|
|
35
|
-
|
|
36
|
-
A `Flow` acts as the orchestrator for your nodes. It defines the sequence of execution and manages transitions between nodes.
|
|
16
|
+
## Installation
|
|
37
17
|
|
|
38
|
-
|
|
39
|
-
* **Transitions**: Nodes are connected using the `node.next(nextNode, action)` method. When a node's `exec` or `post` method returns an `action` string, the `Flow` looks for a successor node registered with that specific action. If no action is specified (or the method returns `undefined`), the "default" action is used. This allows for powerful conditional branching in your workflows.
|
|
18
|
+
You can install `qflow` via npm or Bun:
|
|
40
19
|
|
|
41
|
-
|
|
20
|
+
```bash
|
|
21
|
+
npm install @fractal-solutions/qflow
|
|
22
|
+
# or
|
|
23
|
+
bun add @fractal-solutions/qflow
|
|
24
|
+
```
|
|
42
25
|
|
|
43
|
-
|
|
26
|
+
## Core Abstractions
|
|
44
27
|
|
|
45
|
-
|
|
46
|
-
```javascript
|
|
47
|
-
// Example of setting params for a node
|
|
48
|
-
class MyNode extends Node {
|
|
49
|
-
exec() {
|
|
50
|
-
console.log(this.params.myValue);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
const myNode = new MyNode();
|
|
54
|
-
// When running a flow, the flow will call myNode.setParams({ myValue: 'hello' });
|
|
55
|
-
```
|
|
28
|
+
`qflow` is built around a few core abstractions that allow you to define powerful and flexible workflows.
|
|
56
29
|
|
|
57
|
-
|
|
30
|
+
### Node
|
|
58
31
|
|
|
59
|
-
|
|
32
|
+
The fundamental building block of any `qflow` workflow. A `Node` represents a single operation or step in your flow.
|
|
60
33
|
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
34
|
+
* `prep(shared)`: Prepares data for execution.
|
|
35
|
+
* `exec(prepRes)`: Executes the node's primary logic.
|
|
36
|
+
* `post(shared, prepRes, execRes)`: Processes the result of `exec`.
|
|
37
|
+
* `setParams(params)`: Sets parameters for the node.
|
|
38
|
+
* `next(node, action = "default")`: Chains this node to another, defining the next step in the flow.
|
|
39
|
+
* `transition(action)`: Initiates a conditional transition to another node.
|
|
64
40
|
|
|
65
|
-
|
|
41
|
+
**Asynchronous Nodes (`AsyncNode`, `AsyncBatchNode`, `AsyncParallelBatchNode`)**
|
|
42
|
+
For operations that involve I/O or are inherently asynchronous, `qflow` provides `AsyncNode` and its variants. These nodes use `async`/`await` for non-blocking execution.
|
|
66
43
|
|
|
67
|
-
###
|
|
44
|
+
### Flow
|
|
68
45
|
|
|
69
|
-
|
|
46
|
+
A `Flow` orchestrates the execution of a sequence of `Node`s. It defines the overall path and manages the transitions between nodes.
|
|
70
47
|
|
|
71
|
-
* `
|
|
72
|
-
* `
|
|
73
|
-
* `next(node, action = "default")`: Defines the next node in the flow.
|
|
74
|
-
* `prep(shared)`: Pre-execution logic.
|
|
75
|
-
* `exec(prepRes)`: Execution logic.
|
|
76
|
-
* `post(shared, prepRes, execRes)`: Post-execution logic. The return value of this method is used to determine the next node in the flow.
|
|
77
|
-
* `run(shared)`: Runs the node.
|
|
48
|
+
* `start(startNode)`: Sets the initial node for the flow. (Note: In practice, you often pass the start node directly to the `Flow` constructor).
|
|
49
|
+
* `_orch(shared, params)` / `_orchAsync(shared, params)`: Internal methods used to run the flow, especially when passing initial parameters to the starting node.
|
|
78
50
|
|
|
79
|
-
|
|
51
|
+
**Batch Flows (`BatchFlow`, `AsyncBatchFlow`, `AsyncParallelBatchFlow`)**
|
|
52
|
+
These flows are designed to process collections of items, running a sub-flow for each item in the batch. `AsyncParallelBatchFlow` executes batch items concurrently.
|
|
80
53
|
|
|
81
|
-
|
|
54
|
+
### ConditionalTransition
|
|
82
55
|
|
|
83
|
-
|
|
84
|
-
* `execFallback(prepRes, error)`: Logic to execute if all retries fail.
|
|
56
|
+
A helper class used with `Node.transition()` to define conditional branching in your flows.
|
|
85
57
|
|
|
86
|
-
|
|
58
|
+
* `to(targetNode)`: Specifies the target node for the transition.
|
|
87
59
|
|
|
88
|
-
|
|
60
|
+
## Basic Usage & Examples
|
|
89
61
|
|
|
90
|
-
|
|
91
|
-
* `start(startNode)`: Sets the starting node.
|
|
92
|
-
* `run(shared)`: Runs the entire flow.
|
|
62
|
+
### 1. Simple Node
|
|
93
63
|
|
|
94
|
-
|
|
64
|
+
A basic example of defining and running a single node.
|
|
95
65
|
|
|
96
|
-
|
|
66
|
+
```javascript
|
|
67
|
+
import { Node } from '@fractal-solutions/qflow';
|
|
97
68
|
|
|
98
|
-
|
|
69
|
+
class MySimpleNode extends Node {
|
|
70
|
+
prep(shared) {
|
|
71
|
+
console.log('Preparing data...');
|
|
72
|
+
return shared.inputData * 2;
|
|
73
|
+
}
|
|
99
74
|
|
|
100
|
-
|
|
75
|
+
exec(prepRes) {
|
|
76
|
+
console.log('Executing with prepared data:', prepRes);
|
|
77
|
+
return prepRes + 10;
|
|
78
|
+
}
|
|
101
79
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
80
|
+
post(shared, prepRes, execRes) {
|
|
81
|
+
console.log('Post-processing result:', execRes);
|
|
82
|
+
return { finalResult: execRes, originalInput: shared.inputData };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
106
85
|
|
|
107
|
-
|
|
86
|
+
const node = new MySimpleNode();
|
|
87
|
+
const result = node.run({ inputData: 5 });
|
|
88
|
+
console.log('Node run result:', result);
|
|
89
|
+
// Expected output:
|
|
90
|
+
// Preparing data...
|
|
91
|
+
// Executing with prepared data: 10
|
|
92
|
+
// Post-processing result: 20
|
|
93
|
+
// Node run result: { finalResult: 20, originalInput: 5 }
|
|
94
|
+
```
|
|
108
95
|
|
|
109
|
-
|
|
96
|
+
### 2. Simple Flow
|
|
110
97
|
|
|
111
|
-
|
|
98
|
+
Chaining multiple nodes together to form a basic workflow.
|
|
112
99
|
|
|
113
100
|
```javascript
|
|
114
|
-
import { Node, Flow } from '
|
|
101
|
+
import { Node, Flow } from '@fractal-solutions/qflow';
|
|
115
102
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
exec() {
|
|
119
|
-
console.log("Hello from MessageNode!");
|
|
120
|
-
return 'default'; // Transition to the default successor
|
|
121
|
-
}
|
|
103
|
+
class AddNode extends Node {
|
|
104
|
+
exec(input) { return input + 5; }
|
|
122
105
|
}
|
|
123
106
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
exec() {
|
|
127
|
-
console.log(`Current time: ${Date.now()}`);
|
|
128
|
-
return 'default';
|
|
129
|
-
}
|
|
107
|
+
class MultiplyNode extends Node {
|
|
108
|
+
exec(input) { return input * 2; }
|
|
130
109
|
}
|
|
131
110
|
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
const timeNode = new TimeNode();
|
|
111
|
+
const add = new AddNode();
|
|
112
|
+
const multiply = new MultiplyNode();
|
|
135
113
|
|
|
136
|
-
//
|
|
137
|
-
|
|
114
|
+
// Chain the nodes
|
|
115
|
+
add.next(multiply);
|
|
138
116
|
|
|
139
|
-
// Create
|
|
140
|
-
const flow = new Flow(
|
|
141
|
-
|
|
117
|
+
// Create the flow, starting with the 'add' node
|
|
118
|
+
const flow = new Flow(add);
|
|
119
|
+
|
|
120
|
+
// Run the flow. Initial parameters can be passed via the second argument to _orch.
|
|
121
|
+
const result = flow._orch(null, { params: 10 });
|
|
122
|
+
console.log('Flow result:', result); // Expected: 30 ((10 + 5) * 2)
|
|
142
123
|
```
|
|
143
124
|
|
|
144
|
-
###
|
|
125
|
+
### 3. Conditional Flow
|
|
145
126
|
|
|
146
|
-
|
|
147
|
-
import { Node, BatchFlow } from './qflow.js';
|
|
127
|
+
Using `transition()` for dynamic branching based on an action.
|
|
148
128
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
129
|
+
```javascript
|
|
130
|
+
import { Node, Flow } from '@fractal-solutions/qflow';
|
|
131
|
+
|
|
132
|
+
class CheckValueNode extends Node {
|
|
133
|
+
exec(value) {
|
|
134
|
+
if (value > 10) {
|
|
135
|
+
return 'greater';
|
|
136
|
+
} else {
|
|
137
|
+
return 'lessOrEqual';
|
|
138
|
+
}
|
|
153
139
|
}
|
|
154
140
|
}
|
|
155
141
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
// The prep method returns an array of parameter objects for the batch.
|
|
160
|
-
batchFlow.prep = () => [ { item: 1 }, { item: 2 }, { item: 3 } ];
|
|
161
|
-
|
|
162
|
-
batchFlow.run({});
|
|
163
|
-
```
|
|
164
|
-
|
|
165
|
-
### Async Parallel Batch Flow
|
|
166
|
-
|
|
167
|
-
```javascript
|
|
168
|
-
import { AsyncNode, AsyncParallelBatchFlow } from './qflow.js';
|
|
169
|
-
|
|
170
|
-
class MyAsyncParallelBatchNode extends AsyncNode {
|
|
171
|
-
async execAsync() {
|
|
172
|
-
console.log(`AsyncParallelBatchNode: Starting item ${this.params.item}`);
|
|
173
|
-
await new Promise(resolve => setTimeout(resolve, Math.random() * 100));
|
|
174
|
-
console.log(`AsyncParallelBatchNode: Finished item ${this.params.item}`);
|
|
175
|
-
return 'default';
|
|
176
|
-
}
|
|
142
|
+
class GreaterNode extends Node {
|
|
143
|
+
exec() { return 'Value is greater than 10'; }
|
|
177
144
|
}
|
|
178
145
|
|
|
179
|
-
|
|
180
|
-
|
|
146
|
+
class LessOrEqualNode extends Node {
|
|
147
|
+
exec() { return 'Value is less than or equal to 10'; }
|
|
148
|
+
}
|
|
181
149
|
|
|
182
|
-
|
|
183
|
-
|
|
150
|
+
const check = new CheckValueNode();
|
|
151
|
+
const greater = new GreaterNode();
|
|
152
|
+
const lessOrEqual = new LessOrEqualNode();
|
|
184
153
|
|
|
185
|
-
|
|
186
|
-
|
|
154
|
+
// Chain the nodes with conditional transitions
|
|
155
|
+
check.transition('greater').to(greater);
|
|
156
|
+
check.transition('lessOrEqual').to(lessOrEqual);
|
|
187
157
|
|
|
188
|
-
|
|
158
|
+
// Create the flow, starting with the 'check' node
|
|
159
|
+
const flow = new Flow(check);
|
|
189
160
|
|
|
190
|
-
|
|
161
|
+
let result1 = flow._orch(null, { params: 15 }); // Pass params directly to _orch
|
|
162
|
+
console.log(result1); // Expected: Value is greater than 10
|
|
191
163
|
|
|
192
|
-
|
|
164
|
+
let result2 = flow._orch(null, { params: 7 });
|
|
165
|
+
console.log(result2); // Expected: Value is less than or equal to 10
|
|
166
|
+
```
|
|
193
167
|
|
|
194
|
-
###
|
|
168
|
+
### 4. Asynchronous Flow
|
|
195
169
|
|
|
196
|
-
|
|
170
|
+
Handling asynchronous operations within a flow.
|
|
197
171
|
|
|
198
172
|
```javascript
|
|
199
|
-
import { AsyncNode } from '
|
|
200
|
-
|
|
201
|
-
class OpenAILLMNode extends AsyncNode {
|
|
202
|
-
async execAsync() {
|
|
203
|
-
const { prompt, apiKey } = this.params; // prompt and apiKey passed via node params
|
|
173
|
+
import { AsyncNode, AsyncFlow } from '@fractal-solutions/qflow';
|
|
204
174
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
console.log(`OpenAILLMNode: Sending prompt to OpenAI: "${prompt.substring(0, 50)}..."`);
|
|
213
|
-
|
|
214
|
-
try {
|
|
215
|
-
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
|
216
|
-
method: 'POST',
|
|
217
|
-
headers: {
|
|
218
|
-
'Content-Type': 'application/json',
|
|
219
|
-
'Authorization': `Bearer ${apiKey}`
|
|
220
|
-
},
|
|
221
|
-
body: JSON.stringify({
|
|
222
|
-
model: 'gpt-3.5-turbo',
|
|
223
|
-
messages: [{ role: 'user', content: prompt }],
|
|
224
|
-
max_tokens: 150
|
|
225
|
-
})
|
|
226
|
-
});
|
|
227
|
-
|
|
228
|
-
if (!response.ok) {
|
|
229
|
-
const errorData = await response.json();
|
|
230
|
-
throw new Error(`OpenAI API error: ${response.status} - ${errorData.error.message}`);
|
|
231
|
-
}
|
|
175
|
+
class FetchDataNode extends AsyncNode {
|
|
176
|
+
async execAsync(url) {
|
|
177
|
+
console.log(`Fetching data from: ${url}`);
|
|
178
|
+
// Simulate an API call
|
|
179
|
+
return new Promise(resolve => setTimeout(() => resolve(`Data from ${url}`), 100));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
232
182
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
} catch (error) {
|
|
238
|
-
console.error('OpenAILLMNode: Error during API call:', error);
|
|
239
|
-
throw error; // Re-throw to trigger qflow's retry/fallback
|
|
240
|
-
}
|
|
183
|
+
class ProcessDataNode extends AsyncNode {
|
|
184
|
+
async execAsync(data) {
|
|
185
|
+
console.log(`Processing: ${data}`);
|
|
186
|
+
return data.toUpperCase();
|
|
241
187
|
}
|
|
242
188
|
}
|
|
243
189
|
|
|
244
|
-
|
|
245
|
-
|
|
190
|
+
const fetchNode = new FetchDataNode();
|
|
191
|
+
const processNode = new ProcessDataNode();
|
|
192
|
+
|
|
193
|
+
// Chain the nodes
|
|
194
|
+
fetchNode.next(processNode);
|
|
246
195
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
openAILLMNode.setParams({
|
|
250
|
-
prompt: 'Write a short, creative slogan for a new coffee shop.',
|
|
251
|
-
apiKey: process.env.OPENAI_API_KEY // Load from environment variable
|
|
252
|
-
});
|
|
196
|
+
// Create the async flow, starting with the 'fetchNode'
|
|
197
|
+
const asyncFlow = new AsyncFlow(fetchNode);
|
|
253
198
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
199
|
+
async function runAsyncFlow() {
|
|
200
|
+
// Run the flow, passing the URL as an initial parameter to the first node
|
|
201
|
+
const result = await asyncFlow._orchAsync(null, { params: 'https://api.example.com/data' });
|
|
202
|
+
console.log('Async Flow Result:', result);
|
|
203
|
+
}
|
|
257
204
|
|
|
205
|
+
runAsyncFlow();
|
|
206
|
+
// Expected output:
|
|
207
|
+
// Fetching data from: https://api.example.com/data
|
|
208
|
+
// Processing: Data from https://api.example.com/data
|
|
209
|
+
// Async Flow Result: DATA FROM HTTPS://API.EXAMPLE.COM/DATA
|
|
258
210
|
```
|
|
259
211
|
|
|
260
|
-
###
|
|
212
|
+
### 5. Batch Processing
|
|
261
213
|
|
|
262
|
-
|
|
214
|
+
Processing multiple items through a flow.
|
|
263
215
|
|
|
264
216
|
```javascript
|
|
265
|
-
import {
|
|
266
|
-
|
|
267
|
-
class GeminiLLMNode extends AsyncNode {
|
|
268
|
-
async execAsync() {
|
|
269
|
-
const { prompt, apiKey } = this.params; // prompt and apiKey passed via node params
|
|
270
|
-
|
|
271
|
-
if (!prompt) {
|
|
272
|
-
throw new Error('Prompt is required for GeminiLLMNode.');
|
|
273
|
-
}
|
|
274
|
-
if (!apiKey) {
|
|
275
|
-
throw new Error('Google Gemini API Key is required.');
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
console.log(`GeminiLLMNode: Sending prompt to Gemini: "${prompt.substring(0, 50)}..."`);
|
|
279
|
-
|
|
280
|
-
try {
|
|
281
|
-
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${apiKey}`, {
|
|
282
|
-
method: 'POST',
|
|
283
|
-
headers: {
|
|
284
|
-
'Content-Type': 'application/json'
|
|
285
|
-
},
|
|
286
|
-
body: JSON.stringify({
|
|
287
|
-
contents: [{ parts: [{ text: prompt }] }]
|
|
288
|
-
})
|
|
289
|
-
});
|
|
290
|
-
|
|
291
|
-
if (!response.ok) {
|
|
292
|
-
const errorData = await response.json();
|
|
293
|
-
throw new Error(`Gemini API error: ${response.status} - ${errorData.error.message}`);
|
|
294
|
-
}
|
|
217
|
+
import { Node, BatchFlow } from '@fractal-solutions/qflow';
|
|
295
218
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
return llmResponse; // Return the LLM's response
|
|
300
|
-
} catch (error) {
|
|
301
|
-
console.error('GeminiLLMNode: Error during API call:', error);
|
|
302
|
-
throw error; // Re-throw to trigger qflow's retry/fallback
|
|
303
|
-
}
|
|
219
|
+
class ProcessItemNode extends Node {
|
|
220
|
+
exec(item) {
|
|
221
|
+
return `Processed: ${item}`;
|
|
304
222
|
}
|
|
305
223
|
}
|
|
306
224
|
|
|
307
|
-
|
|
308
|
-
import { AsyncFlow } from './qflow.js';
|
|
225
|
+
const processItem = new ProcessItemNode();
|
|
309
226
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
geminiLLMNode.setParams({
|
|
313
|
-
prompt: 'Generate a short, catchy headline for a tech blog post about AI in healthcare.',
|
|
314
|
-
apiKey: process.env.GEMINI_API_KEY // Load from environment variable
|
|
315
|
-
});
|
|
227
|
+
// Create the batch flow, starting with the 'processItem' node
|
|
228
|
+
const batchFlow = new BatchFlow(processItem);
|
|
316
229
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
console.log('LLM Flow Result:', llmResult);
|
|
230
|
+
// Define the items to process. For BatchFlow, the prep method should return an array.
|
|
231
|
+
batchFlow.prep = () => ['itemA', 'itemB', 'itemC'];
|
|
320
232
|
|
|
233
|
+
const results = batchFlow.run({}); // Run the batch flow
|
|
234
|
+
console.log('Batch Flow Results:', results);
|
|
235
|
+
// Expected output:
|
|
236
|
+
// Batch Flow Results: [ 'Processed: itemA', 'Processed: itemB', 'Processed: itemC' ]
|
|
321
237
|
```
|
|
322
238
|
|
|
323
|
-
###
|
|
324
|
-
|
|
325
|
-
One of the powerful features of qflow is the ability to chain nodes, allowing the output of one node to become the input for the next. This is particularly useful for multi-step workflows where the output of one operation is required for the next.
|
|
239
|
+
### 6. Retry Mechanism
|
|
326
240
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
This example demonstrates a flow where a GitHub issue is created, and then the created issue is retrieved:
|
|
241
|
+
Configuring a node to retry on failure.
|
|
330
242
|
|
|
331
243
|
```javascript
|
|
332
|
-
import {
|
|
333
|
-
import { CreateIssueNode, GetIssueNode } from 'qflow/nodes';
|
|
334
|
-
|
|
335
|
-
// 1. Create instances of the nodes
|
|
336
|
-
const createIssue = new CreateIssueNode();
|
|
337
|
-
createIssue.setParams({
|
|
338
|
-
token: process.env.GITHUB_TOKEN,
|
|
339
|
-
owner: 'your-username',
|
|
340
|
-
repo: 'your-repo',
|
|
341
|
-
title: '[qflow] Test Issue'
|
|
342
|
-
});
|
|
343
|
-
|
|
344
|
-
const getIssue = new GetIssueNode();
|
|
345
|
-
getIssue.setParams({
|
|
346
|
-
token: process.env.GITHUB_TOKEN,
|
|
347
|
-
owner: 'your-username',
|
|
348
|
-
repo: 'your-repo'
|
|
349
|
-
});
|
|
350
|
-
|
|
351
|
-
// 2. Define the workflow
|
|
352
|
-
createIssue.next(getIssue);
|
|
353
|
-
|
|
354
|
-
// 3. Create and run the flow
|
|
355
|
-
const githubFlow = new AsyncFlow(createIssue);
|
|
356
|
-
const result = await githubFlow.runAsync({});
|
|
357
|
-
```
|
|
358
|
-
|
|
359
|
-
### Web Scraping Example
|
|
244
|
+
import { Node } from '@fractal-solutions/qflow';
|
|
360
245
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
import { ScrapeURLNode } from 'qflow/nodes';
|
|
366
|
-
|
|
367
|
-
/**
|
|
368
|
-
* A node to display the scraped content.
|
|
369
|
-
*/
|
|
370
|
-
class DisplayScrapedContentNode extends AsyncNode {
|
|
371
|
-
async prepAsync(shared) {
|
|
372
|
-
this.params.html = shared.scrapedHTML;
|
|
373
|
-
this.params.url = shared.scrapedURL;
|
|
246
|
+
let attempt = 0;
|
|
247
|
+
class FlakyNode extends Node {
|
|
248
|
+
constructor() {
|
|
249
|
+
super(3, 0.1); // maxRetries = 3, wait = 0.1 seconds
|
|
374
250
|
}
|
|
375
251
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
252
|
+
exec(input) {
|
|
253
|
+
attempt++;
|
|
254
|
+
console.log(`FlakyNode attempt ${attempt} for input: ${input}`);
|
|
255
|
+
if (attempt < 3) {
|
|
256
|
+
throw new Error('Simulated failure');
|
|
381
257
|
}
|
|
258
|
+
return `Success on attempt ${attempt}`;
|
|
259
|
+
}
|
|
382
260
|
|
|
383
|
-
|
|
384
|
-
console.
|
|
385
|
-
|
|
386
|
-
return html.length; // Return character count as the result
|
|
261
|
+
execFallback(prepRes, error) {
|
|
262
|
+
console.error('FlakyNode failed after retries:', error.message);
|
|
263
|
+
return 'Fallback result due to persistent failure';
|
|
387
264
|
}
|
|
388
265
|
}
|
|
389
266
|
|
|
390
|
-
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
};
|
|
399
|
-
|
|
400
|
-
const displayNode = new DisplayScrapedContentNode();
|
|
401
|
-
|
|
402
|
-
// 2. Define the workflow
|
|
403
|
-
scrapeNode.next(displayNode);
|
|
404
|
-
|
|
405
|
-
// 3. Create the batch flow
|
|
406
|
-
const scraperBatchFlow = new AsyncParallelBatchFlow(scrapeNode);
|
|
407
|
-
|
|
408
|
-
// Define the URLs to scrape in the prepAsync of the flow
|
|
409
|
-
scraperBatchFlow.prepAsync = async () => [
|
|
410
|
-
{ url: 'https://example.com' },
|
|
411
|
-
{ url: 'https://www.iana.org/domains/example' },
|
|
412
|
-
{ url: 'https://www.w3.org/' }
|
|
413
|
-
];
|
|
414
|
-
|
|
415
|
-
// 4. Run the flow
|
|
416
|
-
const results = await scraperBatchFlow.runAsync({});
|
|
417
|
-
console.log('Final Results (character counts):', results);
|
|
267
|
+
const flakyNode = new FlakyNode();
|
|
268
|
+
const result = flakyNode.run('test');
|
|
269
|
+
console.log('Flaky Node Result:', result);
|
|
270
|
+
// Expected output (may vary slightly due to timing):
|
|
271
|
+
// FlakyNode attempt 1 for input: test
|
|
272
|
+
// FlakyNode attempt 2 for input: test
|
|
273
|
+
// FlakyNode attempt 3 for input: test
|
|
274
|
+
// Flaky Node Result: Success on attempt 3
|
|
418
275
|
```
|
|
419
276
|
|
|
420
|
-
##
|
|
277
|
+
## Built-in Nodes
|
|
421
278
|
|
|
422
|
-
|
|
279
|
+
`qflow` comes with a set of pre-built nodes to accelerate common development tasks. These are available via `@fractal-solutions/qflow/nodes`.
|
|
423
280
|
|
|
424
|
-
*
|
|
425
|
-
*
|
|
426
|
-
*
|
|
427
|
-
*
|
|
428
|
-
*
|
|
429
|
-
* `examples/stripe_test.js` - Demonstrates the Stripe integration.
|
|
281
|
+
* **`LLMNode`**: Interact with Large Language Models (e.g., for text generation, summarization).
|
|
282
|
+
* **`HackerNewsNode`**: Fetch data from the Hacker News API.
|
|
283
|
+
* **`GitHubNode`**: Interact with the GitHub API (e.g., fetch repository details, user info).
|
|
284
|
+
* **`StripeNode`**: Integrate with the Stripe API for payment processing.
|
|
285
|
+
* **`WebScraperNode`**: Perform web scraping tasks to extract data from web pages.
|
|
430
286
|
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
To run the examples, you can use `bun run`:
|
|
434
|
-
|
|
435
|
-
```bash
|
|
436
|
-
bun run examples/test.js
|
|
437
|
-
```
|
|
438
|
-
|
|
439
|
-
**Note:** Some examples require API keys or other credentials. These can be set as environment variables or by replacing the placeholder values in the example files.
|
|
440
|
-
|
|
441
|
-
## Installation
|
|
442
|
-
|
|
443
|
-
Install `qflow` using your favorite package manager:
|
|
444
|
-
|
|
445
|
-
**NPM**
|
|
446
|
-
```bash
|
|
447
|
-
npm install qflow
|
|
448
|
-
```
|
|
449
|
-
|
|
450
|
-
**Yarn**
|
|
451
|
-
```bash
|
|
452
|
-
yarn add qflow
|
|
453
|
-
```
|
|
454
|
-
|
|
455
|
-
**Bun**
|
|
456
|
-
```bash
|
|
457
|
-
bun add qflow
|
|
458
|
-
```
|
|
459
|
-
|
|
460
|
-
## Usage
|
|
461
|
-
|
|
462
|
-
### Core Concepts
|
|
463
|
-
|
|
464
|
-
Import the core `qflow` classes from the main entry point:
|
|
287
|
+
**Example: Using a Built-in Node (WebScraperNode)**
|
|
465
288
|
|
|
466
289
|
```javascript
|
|
467
|
-
import {
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
290
|
+
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
291
|
+
import { ScrapeURLNode } from '@fractal-solutions/qflow/nodes'; // Correct import for WebScraperNode
|
|
292
|
+
|
|
293
|
+
// Define a flow to scrape a URL and display its title
|
|
294
|
+
class ScrapeTitleFlow extends AsyncFlow {
|
|
295
|
+
constructor() {
|
|
296
|
+
super();
|
|
297
|
+
const scraper = new ScrapeURLNode(); // Use ScrapeURLNode as per examples
|
|
298
|
+
scraper.setParams({
|
|
299
|
+
url: 'https://example.com',
|
|
300
|
+
selectors: {
|
|
301
|
+
title: 'h1' // Select the h1 tag
|
|
302
|
+
}
|
|
303
|
+
});
|
|
304
|
+
this.start(scraper); // Set the starting node for the flow
|
|
305
|
+
}
|
|
306
|
+
}
|
|
471
307
|
|
|
472
|
-
|
|
308
|
+
async function runScrapeFlow() {
|
|
309
|
+
const flow = new ScrapeTitleFlow();
|
|
310
|
+
// Run the flow. The result will be the output of the last node in the flow.
|
|
311
|
+
const result = await flow.runAsync({});
|
|
312
|
+
console.log('Scraped Title:', result.title);
|
|
313
|
+
}
|
|
473
314
|
|
|
474
|
-
|
|
475
|
-
|
|
315
|
+
runScrapeFlow();
|
|
316
|
+
// Expected output (will vary based on example.com content):
|
|
317
|
+
// Scraped Title: Example Domain
|
|
476
318
|
```
|
|
477
319
|
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
`qflow` is designed to be compatible with modern JavaScript runtimes.
|
|
481
|
-
|
|
482
|
-
**Node.js**
|
|
483
|
-
|
|
484
|
-
When using `qflow` in a Node.js environment, you may need to use the `--experimental-modules` flag if you are using ES modules.
|
|
320
|
+
## Integration
|
|
485
321
|
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
`qflow` can be used in Deno by importing it from a CDN that serves NPM packages, such as esm.sh:
|
|
489
|
-
|
|
490
|
-
```javascript
|
|
491
|
-
import { Node, Flow } from 'https://esm.sh/qflow';
|
|
492
|
-
import { OpenAILLMNode } from 'https://esm.sh/qflow/nodes';
|
|
493
|
-
```
|
|
322
|
+
`qflow` is designed to be highly flexible and can be integrated into various application architectures:
|
|
494
323
|
|
|
324
|
+
* **CLI Tools:** Build powerful command-line tools that automate complex tasks.
|
|
325
|
+
* **Web Servers (e.g., Express.js, Koa):** Implement API endpoints that trigger workflows for data processing, background jobs, or agent-driven responses.
|
|
326
|
+
* **Background Services:** Run long-running processes or scheduled tasks.
|
|
327
|
+
* **Browser Applications:** Create interactive, client-side workflows (ensure appropriate polyfills for `SharedArrayBuffer` if using synchronous `wait` in `Node`).
|
|
495
328
|
|
|
496
329
|
## Contributing
|
|
497
330
|
|
|
498
|
-
|
|
331
|
+
We welcome contributions! Please see our GitHub repository for more details on how to contribute.
|
|
332
|
+
|
|
333
|
+
---
|
package/package.json
CHANGED