@fractal-solutions/qflow 1.0.0 → 1.0.2
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 +254 -386
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,498 +1,366 @@
|
|
|
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
|
|
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).
|
|
27
15
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
* **`prep(shared)`**: This method is called before `exec`. It's ideal for preparing any data or resources needed for the node's main logic. The `shared` object, which is a mutable object passed throughout the entire flow, can be used here to access or store global state. The return value of `prep` is passed as `prepRes` to the `exec` method.
|
|
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';
|
|
102
|
+
|
|
103
|
+
let count = 0;
|
|
115
104
|
|
|
116
|
-
// A node that prints a message
|
|
117
105
|
class MessageNode extends Node {
|
|
118
106
|
exec() {
|
|
119
|
-
|
|
120
|
-
|
|
107
|
+
count++;
|
|
108
|
+
console.log(`New Message ${count}`);
|
|
109
|
+
return `default`;
|
|
121
110
|
}
|
|
122
111
|
}
|
|
123
112
|
|
|
124
|
-
// A node that prints the current time
|
|
125
113
|
class TimeNode extends Node {
|
|
126
114
|
exec() {
|
|
127
|
-
console.log(`
|
|
128
|
-
return
|
|
115
|
+
console.log(`Time ${Date.now()}`);
|
|
116
|
+
return `default`;
|
|
129
117
|
}
|
|
130
118
|
}
|
|
131
119
|
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
const
|
|
120
|
+
const m1 = new MessageNode();
|
|
121
|
+
const t1 = new TimeNode();
|
|
122
|
+
const m2 = new MessageNode();
|
|
135
123
|
|
|
136
|
-
|
|
137
|
-
|
|
124
|
+
m1.next(t1);
|
|
125
|
+
t1.next(m2);
|
|
138
126
|
|
|
139
|
-
|
|
140
|
-
const flow = new Flow(messageNode);
|
|
127
|
+
const flow = new Flow(m1);
|
|
141
128
|
flow.run({});
|
|
129
|
+
// Expected output (approximate):
|
|
130
|
+
// New Message 1
|
|
131
|
+
// Time <timestamp>
|
|
132
|
+
// New Message 2
|
|
142
133
|
```
|
|
143
134
|
|
|
144
|
-
###
|
|
135
|
+
### 3. Conditional Flow
|
|
136
|
+
|
|
137
|
+
Using `transition()` for dynamic branching based on an action.
|
|
145
138
|
|
|
146
139
|
```javascript
|
|
147
|
-
import { Node,
|
|
140
|
+
import { Node, Flow } from '@fractal-solutions/qflow';
|
|
141
|
+
|
|
142
|
+
class ConditionalNode extends Node {
|
|
143
|
+
constructor(shouldGoLeft) {
|
|
144
|
+
super();
|
|
145
|
+
this.shouldGoLeft = shouldGoLeft;
|
|
146
|
+
}
|
|
148
147
|
|
|
149
|
-
class MyBatchNode extends Node {
|
|
150
148
|
exec() {
|
|
151
|
-
|
|
152
|
-
|
|
149
|
+
if (this.shouldGoLeft) {
|
|
150
|
+
console.log('ConditionalNode: Going left');
|
|
151
|
+
return 'left';
|
|
152
|
+
} else {
|
|
153
|
+
console.log('ConditionalNode: Going right');
|
|
154
|
+
return 'right';
|
|
155
|
+
}
|
|
153
156
|
}
|
|
154
157
|
}
|
|
155
158
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
159
|
+
// Helper node for conditional transition test
|
|
160
|
+
function MessageNode(message) {
|
|
161
|
+
return new (class extends Node {
|
|
162
|
+
exec() {
|
|
163
|
+
console.log(message);
|
|
164
|
+
return 'default';
|
|
165
|
+
}
|
|
166
|
+
})();
|
|
167
|
+
}
|
|
161
168
|
|
|
162
|
-
|
|
169
|
+
const conditionalNode = new ConditionalNode(true);
|
|
170
|
+
const leftNode = MessageNode('Went Left');
|
|
171
|
+
const rightNode = MessageNode('Went Right');
|
|
172
|
+
|
|
173
|
+
conditionalNode.next(leftNode, 'left');
|
|
174
|
+
conditionalNode.next(rightNode, 'right');
|
|
175
|
+
|
|
176
|
+
const conditionalFlow = new Flow(conditionalNode);
|
|
177
|
+
conditionalFlow.run({});
|
|
178
|
+
// Expected output:
|
|
179
|
+
// ConditionalNode: Going left
|
|
180
|
+
// Went Left
|
|
181
|
+
|
|
182
|
+
const conditionalNode2 = new ConditionalNode(false);
|
|
183
|
+
conditionalNode2.next(leftNode, 'left');
|
|
184
|
+
conditionalNode2.next(rightNode, 'right');
|
|
185
|
+
const conditionalFlow2 = new Flow(conditionalNode2);
|
|
186
|
+
conditionalFlow2.run({});
|
|
187
|
+
// Expected output:
|
|
188
|
+
// ConditionalNode: Going right
|
|
189
|
+
// Went Right
|
|
163
190
|
```
|
|
164
191
|
|
|
165
|
-
###
|
|
192
|
+
### 4. Asynchronous Flow
|
|
193
|
+
|
|
194
|
+
Handling asynchronous operations within a flow.
|
|
166
195
|
|
|
167
196
|
```javascript
|
|
168
|
-
import { AsyncNode,
|
|
197
|
+
import { AsyncNode, AsyncFlow } from '@fractal-solutions/qflow';
|
|
169
198
|
|
|
170
|
-
class
|
|
199
|
+
class MyAsyncNode extends AsyncNode {
|
|
171
200
|
async execAsync() {
|
|
172
|
-
console.log(
|
|
173
|
-
await new Promise(resolve => setTimeout(resolve,
|
|
174
|
-
console.log(
|
|
201
|
+
console.log('AsyncNode: Starting...');
|
|
202
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
203
|
+
console.log('AsyncNode: Finished!');
|
|
175
204
|
return 'default';
|
|
176
205
|
}
|
|
177
206
|
}
|
|
178
207
|
|
|
179
|
-
const
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
208
|
+
const asyncNode1 = new MyAsyncNode();
|
|
209
|
+
const asyncNode2 = new MyAsyncNode();
|
|
210
|
+
asyncNode1.next(asyncNode2);
|
|
211
|
+
|
|
212
|
+
const asyncFlow = new AsyncFlow(asyncNode1);
|
|
213
|
+
await asyncFlow.runAsync({});
|
|
214
|
+
// Expected output:
|
|
215
|
+
// AsyncNode: Starting...
|
|
216
|
+
// AsyncNode: Finished!
|
|
217
|
+
// AsyncNode: Starting...
|
|
218
|
+
// AsyncNode: Finished!
|
|
186
219
|
```
|
|
187
220
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
qflow's flexible node structure makes it straightforward to integrate with external APIs, including Large Language Models (LLMs). By creating custom `AsyncNode` implementations, you can easily add capabilities like text generation, summarization, and more to your workflows.
|
|
221
|
+
### 5. Batch Processing
|
|
191
222
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
### OpenAI GPT-3.5 Turbo Node
|
|
195
|
-
|
|
196
|
-
This example demonstrates an `AsyncNode` that interacts with the OpenAI Chat Completions API.
|
|
223
|
+
Processing multiple items through a flow.
|
|
197
224
|
|
|
198
225
|
```javascript
|
|
199
|
-
import { AsyncNode } from '
|
|
226
|
+
import { Node, BatchFlow, AsyncParallelBatchFlow, AsyncNode } from '@fractal-solutions/qflow';
|
|
200
227
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const { prompt, apiKey } = this.params; // prompt and apiKey passed via node params
|
|
228
|
+
// Synchronous Batch Flow
|
|
229
|
+
console.log('\n--- Running Synchronous Batch Flow ---');
|
|
204
230
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
throw new Error('OpenAI API Key is required.');
|
|
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
|
-
}
|
|
232
|
-
|
|
233
|
-
const data = await response.json();
|
|
234
|
-
const llmResponse = data.choices[0].message.content.trim();
|
|
235
|
-
console.log(`OpenAILLMNode: Received response: "${llmResponse.substring(0, 50)}..."`);
|
|
236
|
-
return llmResponse; // Return the LLM's response
|
|
237
|
-
} catch (error) {
|
|
238
|
-
console.error('OpenAILLMNode: Error during API call:', error);
|
|
239
|
-
throw error; // Re-throw to trigger qflow's retry/fallback
|
|
240
|
-
}
|
|
231
|
+
class MyBatchNode extends Node {
|
|
232
|
+
exec() {
|
|
233
|
+
console.log(`BatchNode: Processing item ${this.params.item}`);
|
|
234
|
+
return 'default';
|
|
241
235
|
}
|
|
242
236
|
}
|
|
243
237
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
//
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
});
|
|
253
|
-
|
|
254
|
-
const llmFlow = new AsyncFlow(openAILLMNode);
|
|
255
|
-
const llmResult = await llmFlow.runAsync({});
|
|
256
|
-
console.log('LLM Flow Result:', llmResult);
|
|
257
|
-
|
|
258
|
-
```
|
|
259
|
-
|
|
260
|
-
### Google Gemini Node
|
|
261
|
-
|
|
262
|
-
This example demonstrates an `AsyncNode` that interacts with the Google Gemini API.
|
|
238
|
+
const batchNode = new MyBatchNode();
|
|
239
|
+
const batchFlow = new BatchFlow(batchNode);
|
|
240
|
+
batchFlow.prep = () => [ { item: 1 }, { item: 2 }, { item: 3 } ];
|
|
241
|
+
batchFlow.run({});
|
|
242
|
+
// Expected output:
|
|
243
|
+
// BatchNode: Processing item 1
|
|
244
|
+
// BatchNode: Processing item 2
|
|
245
|
+
// BatchNode: Processing item 3
|
|
263
246
|
|
|
264
|
-
|
|
265
|
-
|
|
247
|
+
// Asynchronous Parallel Batch Flow
|
|
248
|
+
console.log('\n--- Running Asynchronous Parallel Batch Flow ---');
|
|
266
249
|
|
|
267
|
-
class
|
|
250
|
+
class MyAsyncParallelBatchNode extends AsyncNode {
|
|
268
251
|
async execAsync() {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
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
|
-
}
|
|
295
|
-
|
|
296
|
-
const data = await response.json();
|
|
297
|
-
const llmResponse = data.candidates[0].content.parts[0].text.trim();
|
|
298
|
-
console.log(`GeminiLLMNode: Received response: "${llmResponse.substring(0, 50)}..."`);
|
|
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
|
-
}
|
|
252
|
+
console.log(`AsyncParallelBatchNode: Starting item ${this.params.item}`);
|
|
253
|
+
await new Promise(resolve => setTimeout(resolve, Math.random() * 100));
|
|
254
|
+
console.log(`AsyncParallelBatchNode: Finished item ${this.params.item}`);
|
|
255
|
+
return 'default';
|
|
304
256
|
}
|
|
305
257
|
}
|
|
306
258
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
//
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
const llmResult = await llmFlow.runAsync({});
|
|
319
|
-
console.log('LLM Flow Result:', llmResult);
|
|
320
|
-
|
|
259
|
+
const asyncParallelBatchNode = new MyAsyncParallelBatchNode();
|
|
260
|
+
const asyncParallelBatchFlow = new AsyncParallelBatchFlow(asyncParallelBatchNode);
|
|
261
|
+
asyncParallelBatchFlow.prepAsync = async () => [ { item: 1 }, { item: 2 }, { item: 3 }, { item: 4 }, { item: 5 } ];
|
|
262
|
+
await asyncParallelBatchFlow.runAsync({});
|
|
263
|
+
// Expected output (order may vary due to parallel execution):
|
|
264
|
+
// AsyncParallelBatchNode: Starting item 1
|
|
265
|
+
// AsyncParallelBatchNode: Starting item 2
|
|
266
|
+
// ...
|
|
267
|
+
// AsyncParallelBatchNode: Finished item 1
|
|
268
|
+
// AsyncParallelBatchNode: Finished item 2
|
|
269
|
+
// ...
|
|
321
270
|
```
|
|
322
271
|
|
|
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.
|
|
272
|
+
### 6. Retry Mechanism
|
|
326
273
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
This example demonstrates a flow where a GitHub issue is created, and then the created issue is retrieved:
|
|
274
|
+
Configuring a node to retry on failure.
|
|
330
275
|
|
|
331
276
|
```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
|
-
```
|
|
277
|
+
import { Node, Flow } from '@fractal-solutions/qflow';
|
|
358
278
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
```javascript
|
|
364
|
-
import { AsyncFlow, AsyncNode, AsyncParallelBatchFlow } from 'qflow';
|
|
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;
|
|
279
|
+
let retryCount = 0;
|
|
280
|
+
class RetryNode extends Node {
|
|
281
|
+
constructor() {
|
|
282
|
+
super(3, 0.1); // 3 retries, 0.1s wait
|
|
374
283
|
}
|
|
375
284
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
if (
|
|
379
|
-
console.log(`
|
|
380
|
-
|
|
285
|
+
exec() {
|
|
286
|
+
retryCount++;
|
|
287
|
+
if (retryCount < 3) {
|
|
288
|
+
console.log(`RetryNode: Failing, attempt ${retryCount}`);
|
|
289
|
+
throw new Error('Failed!');
|
|
290
|
+
} else {
|
|
291
|
+
console.log('RetryNode: Succeeded!');
|
|
292
|
+
return 'default';
|
|
381
293
|
}
|
|
294
|
+
}
|
|
382
295
|
|
|
383
|
-
|
|
384
|
-
console.log(
|
|
385
|
-
console.log(`\n--- End Content for: ${url} ---\n`);
|
|
386
|
-
return html.length; // Return character count as the result
|
|
296
|
+
execFallback(prepRes, error) {
|
|
297
|
+
console.log('RetryNode: Fallback executed');
|
|
387
298
|
}
|
|
388
299
|
}
|
|
389
300
|
|
|
390
|
-
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
return 'default'; // Return a static action for the flow to transition
|
|
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);
|
|
301
|
+
const retryNode = new RetryNode();
|
|
302
|
+
const retryFlow = new Flow(retryNode);
|
|
303
|
+
retryFlow.run({});
|
|
304
|
+
// Expected output:
|
|
305
|
+
// RetryNode: Failing, attempt 1
|
|
306
|
+
// RetryNode: Failing, attempt 2
|
|
307
|
+
// RetryNode: Succeeded!
|
|
418
308
|
```
|
|
419
309
|
|
|
420
|
-
##
|
|
310
|
+
## Built-in Nodes
|
|
421
311
|
|
|
422
|
-
|
|
312
|
+
`qflow` comes with a set of pre-built nodes to accelerate common development tasks. These are available via `@fractal-solutions/qflow/nodes`.
|
|
423
313
|
|
|
424
|
-
*
|
|
425
|
-
*
|
|
426
|
-
*
|
|
427
|
-
*
|
|
428
|
-
*
|
|
429
|
-
* `examples/stripe_test.js` - Demonstrates the Stripe integration.
|
|
314
|
+
* **`LLMNode`**: Interact with Large Language Models (e.g., for text generation, summarization).
|
|
315
|
+
* **`HackerNewsNode`**: Fetch data from the Hacker News API.
|
|
316
|
+
* **`GitHubNode`**: Interact with the GitHub API (e.g., fetch repository details, user info).
|
|
317
|
+
* **`StripeNode`**: Integrate with the Stripe API for payment processing.
|
|
318
|
+
* **`WebScraperNode`**: Perform web scraping tasks to extract data from web pages.
|
|
430
319
|
|
|
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:
|
|
320
|
+
**Example: Using a Built-in Node (WebScraperNode)**
|
|
465
321
|
|
|
466
322
|
```javascript
|
|
467
|
-
import {
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
323
|
+
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
324
|
+
import { ScrapeURLNode } from '@fractal-solutions/qflow/nodes'; // Correct import for WebScraperNode
|
|
325
|
+
|
|
326
|
+
// Define a flow to scrape a URL and display its title
|
|
327
|
+
class ScrapeTitleFlow extends AsyncFlow {
|
|
328
|
+
constructor() {
|
|
329
|
+
super();
|
|
330
|
+
const scraper = new ScrapeURLNode(); // Use ScrapeURLNode as per examples
|
|
331
|
+
scraper.setParams({
|
|
332
|
+
url: 'https://example.com',
|
|
333
|
+
selectors: {
|
|
334
|
+
title: 'h1' // Select the h1 tag
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
this.start(scraper); // Set the starting node for the flow
|
|
338
|
+
}
|
|
339
|
+
}
|
|
471
340
|
|
|
472
|
-
|
|
341
|
+
async function runScrapeFlow() {
|
|
342
|
+
const flow = new ScrapeTitleFlow();
|
|
343
|
+
// Run the flow. The result will be the output of the last node in the flow.
|
|
344
|
+
const result = await flow.runAsync({});
|
|
345
|
+
console.log('Scraped Title:', result.title);
|
|
346
|
+
}
|
|
473
347
|
|
|
474
|
-
|
|
475
|
-
|
|
348
|
+
runScrapeFlow();
|
|
349
|
+
// Expected output (will vary based on example.com content):
|
|
350
|
+
// Scraped Title: Example Domain
|
|
476
351
|
```
|
|
477
352
|
|
|
478
|
-
|
|
353
|
+
## Integration
|
|
479
354
|
|
|
480
|
-
`qflow` is designed to be
|
|
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.
|
|
485
|
-
|
|
486
|
-
**Deno**
|
|
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
|
-
```
|
|
355
|
+
`qflow` is designed to be highly flexible and can be integrated into various application architectures:
|
|
494
356
|
|
|
357
|
+
* **CLI Tools:** Build powerful command-line tools that automate complex tasks.
|
|
358
|
+
* **Web Servers (e.g., Express.js, Koa):** Implement API endpoints that trigger workflows for data processing, background jobs, or agent-driven responses.
|
|
359
|
+
* **Background Services:** Run long-running processes or scheduled tasks.
|
|
360
|
+
* **Browser Applications:** Create interactive, client-side workflows (ensure appropriate polyfills for `SharedArrayBuffer` if using synchronous `wait` in `Node`).
|
|
495
361
|
|
|
496
362
|
## Contributing
|
|
497
363
|
|
|
498
|
-
|
|
364
|
+
We welcome contributions! Please see our GitHub repository for more details on how to contribute.
|
|
365
|
+
|
|
366
|
+
---
|
package/package.json
CHANGED