@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.
Files changed (2) hide show
  1. package/README.md +226 -391
  2. 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
- A lightweight and flexible JavaScript library for creating and managing workflows. Adopted Pocket Flow design.
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
- ## Core Concepts
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
- * **Synchronous and Asynchronous Execution**: qflow provides both synchronous and asynchronous versions of `Node`s and `Flow`s, allowing you to handle both CPU-bound and I/O-bound tasks efficiently.
19
- * **Batch Processing**: The `BatchFlow` and `AsyncBatchFlow` classes allow you to process arrays of items in a single workflow.
20
- * **Parallel Execution**: The `AsyncParallelBatchNode` and `AsyncParallelBatchFlow` classes enable you to execute asynchronous operations in parallel for maximum efficiency.
21
- * **Retries and Error Handling**: The `Node` class has built-in support for retries with a configurable delay. You can also define a `execFallback` method to handle cases where all retries fail.
22
- * **Conditional Transitions**: You can define multiple successors for a node and choose which one to transition to based on the return value of the `exec` or `post` method.
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
- * **`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
- * **Starting a Flow**: You initialize a `Flow` with a `startNode`. This is the first node that will be executed when the flow runs.
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
- ### Data Transfer and State Management
20
+ ```bash
21
+ npm install @fractal-solutions/qflow
22
+ # or
23
+ bun add @fractal-solutions/qflow
24
+ ```
42
25
 
43
- qflow provides two primary mechanisms for data management within a flow:
26
+ ## Core Abstractions
44
27
 
45
- 1. **Node-Specific Parameters (`this.params`)**: Each node instance has a `this.params` object. This object is populated by the `Flow` when it calls `node.setParams(params)`. This is the recommended way to pass data *into* a specific node for its execution. For `BatchFlow` and `AsyncBatchFlow`, the `prep` (or `prepAsync`) method should return an array of objects, where each object contains the `params` for a single batch item.
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
- 2. **Shared State (`shared` object)**: The `shared` object is a mutable object that is passed to the `prep`, `exec`, and `post` methods of every node in the flow. This object is ideal for maintaining global state or data that needs to be accessible and modifiable across multiple nodes in the workflow. Any changes made to the `shared` object by one node will be visible to subsequent nodes.
30
+ ### Node
58
31
 
59
- ### Nuances
32
+ The fundamental building block of any `qflow` workflow. A `Node` represents a single operation or step in your flow.
60
33
 
61
- * **Return Values for Transitions**: The string returned by a node's `exec` or `post` method is critical for defining the flow's path. If a node returns "success", the flow will look for a successor registered with the "success" action. If no action is returned, the "default" action is assumed.
62
- * **Error Handling**: Nodes can throw errors. The `Node` class provides `maxRetries` and `wait` parameters for automatic retries. If all retries fail, the `execFallback` method is called.
63
- * **Asynchronous Operations**: For asynchronous operations, use `AsyncNode` and `AsyncFlow`. Their lifecycle methods (`prepAsync`, `execAsync`, `postAsync`) are `async` functions, allowing you to use `await` for non-blocking operations.
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
- ## API Reference
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
- ### `BaseNode`
44
+ ### Flow
68
45
 
69
- The base class for all nodes.
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
- * `constructor()`
72
- * `setParams(params)`: Sets the parameters for the node.
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
- ### `Node`
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
- Extends `BaseNode` with retry logic.
54
+ ### ConditionalTransition
82
55
 
83
- * `constructor(maxRetries = 1, wait = 0)`: `maxRetries` is the number of times to retry on failure, and `wait` is the delay in seconds between retries.
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
- ### `Flow`
58
+ * `to(targetNode)`: Specifies the target node for the transition.
87
59
 
88
- Manages a workflow of nodes.
60
+ ## Basic Usage & Examples
89
61
 
90
- * `constructor(start = null)`: `start` is the starting node of the flow.
91
- * `start(startNode)`: Sets the starting node.
92
- * `run(shared)`: Runs the entire flow.
62
+ ### 1. Simple Node
93
63
 
94
- ### `BatchFlow`
64
+ A basic example of defining and running a single node.
95
65
 
96
- Extends `Flow` for batch processing. The `prep` method should return an array of objects, where each object contains the parameters for a single execution of the flow.
66
+ ```javascript
67
+ import { Node } from '@fractal-solutions/qflow';
97
68
 
98
- ### Asynchronous Classes
69
+ class MySimpleNode extends Node {
70
+ prep(shared) {
71
+ console.log('Preparing data...');
72
+ return shared.inputData * 2;
73
+ }
99
74
 
100
- qflow provides asynchronous versions of the core classes:
75
+ exec(prepRes) {
76
+ console.log('Executing with prepared data:', prepRes);
77
+ return prepRes + 10;
78
+ }
101
79
 
102
- * `AsyncNode`
103
- * `AsyncFlow`
104
- * `AsyncBatchFlow`
105
- * `AsyncParallelBatchFlow`
80
+ post(shared, prepRes, execRes) {
81
+ console.log('Post-processing result:', execRes);
82
+ return { finalResult: execRes, originalInput: shared.inputData };
83
+ }
84
+ }
106
85
 
107
- These classes have `...Async` versions of the lifecycle methods (e.g., `prepAsync`, `execAsync`, `postAsync`) and support `async/await`. The `AsyncFlow` class has a `runAsync` method to execute the flow.
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
- ## Usage Examples
96
+ ### 2. Simple Flow
110
97
 
111
- ### Basic Flow
98
+ Chaining multiple nodes together to form a basic workflow.
112
99
 
113
100
  ```javascript
114
- import { Node, Flow } from './qflow.js';
101
+ import { Node, Flow } from '@fractal-solutions/qflow';
115
102
 
116
- // A node that prints a message
117
- class MessageNode extends Node {
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
- // A node that prints the current time
125
- class TimeNode extends Node {
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
- // Create the nodes
133
- const messageNode = new MessageNode();
134
- const timeNode = new TimeNode();
111
+ const add = new AddNode();
112
+ const multiply = new MultiplyNode();
135
113
 
136
- // Define the workflow
137
- messageNode.next(timeNode); // After messageNode, go to timeNode
114
+ // Chain the nodes
115
+ add.next(multiply);
138
116
 
139
- // Create and run the flow
140
- const flow = new Flow(messageNode);
141
- flow.run({});
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
- ### Batch Flow
125
+ ### 3. Conditional Flow
145
126
 
146
- ```javascript
147
- import { Node, BatchFlow } from './qflow.js';
127
+ Using `transition()` for dynamic branching based on an action.
148
128
 
149
- class MyBatchNode extends Node {
150
- exec() {
151
- console.log(`BatchNode: Processing item ${this.params.item}`);
152
- return 'default';
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
- const batchNode = new MyBatchNode();
157
- const batchFlow = new BatchFlow(batchNode);
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
- const asyncParallelBatchNode = new MyAsyncParallelBatchNode();
180
- const asyncParallelBatchFlow = new AsyncParallelBatchFlow(asyncParallelBatchNode);
146
+ class LessOrEqualNode extends Node {
147
+ exec() { return 'Value is less than or equal to 10'; }
148
+ }
181
149
 
182
- // The prepAsync method returns an array of parameter objects for the batch.
183
- asyncParallelBatchFlow.prepAsync = async () => [ { item: 1 }, { item: 2 }, { item: 3 }, { item: 4 }, { item: 5 } ];
150
+ const check = new CheckValueNode();
151
+ const greater = new GreaterNode();
152
+ const lessOrEqual = new LessOrEqualNode();
184
153
 
185
- await asyncParallelBatchFlow.runAsync({});
186
- ```
154
+ // Chain the nodes with conditional transitions
155
+ check.transition('greater').to(greater);
156
+ check.transition('lessOrEqual').to(lessOrEqual);
187
157
 
188
- ## Extending qflow with LLM Nodes
158
+ // Create the flow, starting with the 'check' node
159
+ const flow = new Flow(check);
189
160
 
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.
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
- Below are examples of how you might create nodes for popular LLM providers. Remember to handle API keys securely (e.g., using environment variables) and to include necessary `fetch` polyfills or libraries if running in environments that don't natively support `fetch` (like Node.js without a recent version or a polyfill).
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
- ### OpenAI GPT-3.5 Turbo Node
168
+ ### 4. Asynchronous Flow
195
169
 
196
- This example demonstrates an `AsyncNode` that interacts with the OpenAI Chat Completions API.
170
+ Handling asynchronous operations within a flow.
197
171
 
198
172
  ```javascript
199
- import { AsyncNode } from './qflow.js';
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
- if (!prompt) {
206
- throw new Error('Prompt is required for OpenAILLMNode.');
207
- }
208
- if (!apiKey) {
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
- }
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
- 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
- }
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
- // Example Usage in a Flow:
245
- import { AsyncFlow } from './qflow.js';
190
+ const fetchNode = new FetchDataNode();
191
+ const processNode = new ProcessDataNode();
192
+
193
+ // Chain the nodes
194
+ fetchNode.next(processNode);
246
195
 
247
- const openAILLMNode = new OpenAILLMNode();
248
- // Pass prompt and API key via params
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
- const llmFlow = new AsyncFlow(openAILLMNode);
255
- const llmResult = await llmFlow.runAsync({});
256
- console.log('LLM Flow Result:', llmResult);
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
- ### Google Gemini Node
212
+ ### 5. Batch Processing
261
213
 
262
- This example demonstrates an `AsyncNode` that interacts with the Google Gemini API.
214
+ Processing multiple items through a flow.
263
215
 
264
216
  ```javascript
265
- import { AsyncNode } from './qflow.js';
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
- 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
- }
219
+ class ProcessItemNode extends Node {
220
+ exec(item) {
221
+ return `Processed: ${item}`;
304
222
  }
305
223
  }
306
224
 
307
- // Example Usage in a Flow:
308
- import { AsyncFlow } from './qflow.js';
225
+ const processItem = new ProcessItemNode();
309
226
 
310
- const geminiLLMNode = new GeminiLLMNode();
311
- // Pass prompt and API key via params
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
- const llmFlow = new AsyncFlow(geminiLLMNode);
318
- const llmResult = await llmFlow.runAsync({});
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
- ### Chaining Nodes and Passing Data
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
- The recommended way to pass data between asynchronous nodes is to use the `shared` object. The first node should place its result into the `shared` object in its `postAsync` method, and the second node can then access that data in its `prepAsync` method.
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 { AsyncFlow } from 'qflow';
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
- This example demonstrates how to use the `ScrapeURLNode` to fetch content from multiple URLs in parallel and then process them with another node.
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;
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
- async execAsync() {
377
- const { html, url } = this.params;
378
- if (!html) {
379
- console.log(`[DisplayContent] No HTML content found for ${url || 'unknown URL'}.`);
380
- return 'error';
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
- console.log(`\n--- Scraped Content for: ${url} ---\n`);
384
- console.log(html.substring(0, 500) + '...'); // Log first 500 characters
385
- console.log(`\n--- End Content for: ${url} ---\n`);
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
- // 1. Create instances of the nodes
391
- const scrapeNode = new ScrapeURLNode();
392
- // Override postAsync to pass data to the shared object for the next node
393
- scrapeNode.postAsync = async (shared, prepRes, execRes) => {
394
- shared.scrapedHTML = execRes; // execRes is the returned HTML
395
- // We also need to store the URL that was just scraped for context in the next node
396
- shared.scrapedURL = scrapeNode.params.url;
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);
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
- ## More Examples
277
+ ## Built-in Nodes
421
278
 
422
- For more detailed usage examples and advanced workflows, refer to the `examples/` directory.
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
- * `examples/test.js` - Basic flow and node usage.
425
- * `examples/test2.js` - Demonstrates async flows, conditional transitions, retries, and batch processing.
426
- * `examples/test3.js` - Advanced workflow integrating with a public API.
427
- * `examples/hackernews_test.js` - Demonstrates the Hacker News integration.
428
- * `examples/github_test.js` - Demonstrates the GitHub integration.
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
- ### Running the Examples
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 { Node, Flow, AsyncNode, AsyncFlow } from 'qflow';
468
- ```
469
-
470
- ### Integrated Nodes
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
- `qflow` also includes a variety of pre-built nodes for common integrations, such as LLMs. You can import these nodes from the `qflow/nodes` entry point:
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
- ```javascript
475
- import { OpenAILLMNode, GeminiLLMNode, DeepSeekLLMNode } from 'qflow/nodes';
315
+ runScrapeFlow();
316
+ // Expected output (will vary based on example.com content):
317
+ // Scraped Title: Example Domain
476
318
  ```
477
319
 
478
- ### Runtime Compatibility
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
- **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
- ```
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
- Contributions are welcome! Please feel free to submit a pull request.
331
+ We welcome contributions! Please see our GitHub repository for more details on how to contribute.
332
+
333
+ ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "A lightweight and flexible JavaScript library for creating and managing workflows and agents.",
5
5
  "main": "dist/qflow.js",
6
6
  "types": "dist/qflow.d.ts",