@fractal-solutions/qflow 1.0.3 → 1.0.5

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 +225 -58
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,17 +1,18 @@
1
1
  # qflow: A Lightweight and Flexible JavaScript Workflow and Agent Library
2
2
 
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.
3
+ `qflow` is a lightweight and flexible JavaScript library designed for creating and managing complex workflows and autonomous agents. It provides a minimalist yet expressive API to define sequences of operations, manage data flow, and orchestrate execution, supporting both synchronous and asynchronous patterns.
4
4
 
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.
5
+ With zero external dependencies for its core functionality, `qflow` is built for performance and seamless integration into any JavaScript environment, from Node.js backends to browser-based applications.
6
6
 
7
7
  ## Features
8
8
 
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.
9
+ * **Modular & Extensible:** Easily define custom nodes and compose them into complex, reusable flows.
10
+ * **Synchronous & Asynchronous Flows:** Supports both blocking and non-blocking execution models.
11
+ * **Shared State Management:** Pass and manipulate data across nodes using a central, mutable `shared` object.
12
+ * **Batch Processing:** Efficiently process collections of data through dedicated batch nodes and flows, including parallel execution.
12
13
  * **Retry Mechanisms:** Built-in support for retrying failed operations with configurable delays.
13
14
  * **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).
15
+ * **Built-in Integrations:** Comes with pre-built nodes for common tasks like LLM interactions, web scraping, and popular API integrations (GitHub, HackerNews, Stripe).
15
16
 
16
17
  ## Installation
17
18
 
@@ -23,39 +24,65 @@ npm install @fractal-solutions/qflow
23
24
  bun add @fractal-solutions/qflow
24
25
  ```
25
26
 
27
+ ## Module Imports
28
+
29
+ `qflow` provides different entry points for its core functionalities and built-in nodes to keep your imports clean and specific.
30
+
31
+ * **Core Classes (`Node`, `Flow`, `AsyncNode`, `AsyncFlow`, etc.):**
32
+ These are imported directly from the main package:
33
+ ```javascript
34
+ import { Node, Flow, AsyncNode, AsyncFlow } from '@fractal-solutions/qflow';
35
+ ```
36
+
37
+ * **Built-in Integration Nodes (`LLMNode`, `DeepSeekLLMNode`, `GitHubNode`, `WebScraperNode`, etc.):**
38
+ These are imported from the `/nodes` subpath:
39
+ ```javascript
40
+ import { DeepSeekLLMNode, GitHubNode, WebScraperNode } from '@fractal-solutions/qflow/nodes';
41
+ ```
42
+
26
43
  ## Core Abstractions
27
44
 
28
- `qflow` is built around a few core abstractions that allow you to define powerful and flexible workflows.
45
+ `qflow` is built around a few core abstractions that enable powerful and flexible workflow definitions.
46
+
47
+ ### Shared State (`shared` object)
48
+
49
+ A central, mutable JavaScript object that is passed through the entire flow. Nodes can read from and write to this `shared` object, making it the primary mechanism for passing data and context between different nodes in a workflow. This is particularly useful for accumulating results or maintaining state across multiple steps.
29
50
 
30
51
  ### Node
31
52
 
32
- The fundamental building block of any `qflow` workflow. A `Node` represents a single operation or step in your flow.
53
+ The fundamental building block of any `qflow` workflow. A `Node` represents a single, atomic operation or step in your flow.
33
54
 
34
- * `prep(shared)`: Prepares data for execution.
55
+ * `prep(shared)`: Prepares data for execution. Receives the `shared` object.
35
56
  * `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.
57
+ * `post(shared, prepRes, execRes)`: Processes the result of `exec`. Receives the `shared` object.
58
+ * `setParams(params)`: Configures the node with specific parameters. Parameters are accessible via `this.params`.
38
59
  * `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.
60
+ * `transition(action)`: Initiates a conditional transition to another node, allowing for dynamic branching.
40
61
 
41
62
  **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.
63
+ For operations that involve I/O or are inherently asynchronous, `qflow` provides `AsyncNode` and its variants. These nodes leverage `async`/`await` for non-blocking execution. When working within `AsyncFlow`s, it's crucial to implement the `async` versions of the lifecycle methods:
64
+ * `prepAsync(shared)`
65
+ * `execAsync(prepRes, shared)`
66
+ * `postAsync(shared, prepRes, execRes)`
67
+ * `preparePrompt(shared)` (specifically for LLM nodes, allowing prompt construction based on `shared` state)
68
+
69
+ These `async` methods ensure proper awaiting and data propagation within asynchronous workflows.
43
70
 
44
71
  ### Flow
45
72
 
46
73
  A `Flow` orchestrates the execution of a sequence of `Node`s. It defines the overall path and manages the transitions between nodes.
47
74
 
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.
75
+ * `start(startNode)`: Sets the initial node for the flow. (Note: In practice, you often pass the start node directly to the `Flow` constructor for conciseness).
76
+ * `_orch(shared, params)` / `_orchAsync(shared, params)`: Internal methods used to run the flow, especially when passing initial parameters to the starting node. For most use cases, `flow.run(sharedState)` or `await flow.runAsync(sharedState)` is sufficient.
50
77
 
51
78
  **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.
79
+ These specialized flows are designed to process collections of items. They run a sub-flow for each item in the batch. `AsyncParallelBatchFlow` is particularly useful for concurrently processing batch items, significantly speeding up operations.
53
80
 
54
81
  ### ConditionalTransition
55
82
 
56
- A helper class used with `Node.transition()` to define conditional branching in your flows.
83
+ A helper class used in conjunction with `Node.transition()` to define conditional branching within your workflows.
57
84
 
58
- * `to(targetNode)`: Specifies the target node for the transition.
85
+ * `to(targetNode)`: Specifies the target node for the transition based on the action returned by the preceding node.
59
86
 
60
87
  ## Basic Usage & Examples
61
88
 
@@ -134,19 +161,15 @@ flow.run({});
134
161
 
135
162
  ### 3. Conditional Flow
136
163
 
137
- Using `transition()` for dynamic branching based on an action.
164
+ Using `transition()` for dynamic branching based on an action. This example demonstrates configuring a node using `setParams` for a cleaner API.
138
165
 
139
166
  ```javascript
140
167
  import { Node, Flow } from '@fractal-solutions/qflow';
141
168
 
142
169
  class ConditionalNode extends Node {
143
- constructor(shouldGoLeft) {
144
- super();
145
- this.shouldGoLeft = shouldGoLeft;
146
- }
147
-
148
170
  exec() {
149
- if (this.shouldGoLeft) {
171
+ // Access shouldGoLeft from this.params, which is set via setParams
172
+ if (this.params.shouldGoLeft) {
150
173
  console.log('ConditionalNode: Going left');
151
174
  return 'left';
152
175
  } else {
@@ -166,7 +189,9 @@ function MessageNode(message) {
166
189
  })();
167
190
  }
168
191
 
169
- const conditionalNode = new ConditionalNode(true);
192
+ const conditionalNode = new ConditionalNode();
193
+ conditionalNode.setParams({ shouldGoLeft: true }); // Configure via setParams
194
+
170
195
  const leftNode = MessageNode('Went Left');
171
196
  const rightNode = MessageNode('Went Right');
172
197
 
@@ -179,7 +204,9 @@ conditionalFlow.run({});
179
204
  // ConditionalNode: Going left
180
205
  // Went Left
181
206
 
182
- const conditionalNode2 = new ConditionalNode(false);
207
+ const conditionalNode2 = new ConditionalNode();
208
+ conditionalNode2.setParams({ shouldGoLeft: false }); // Configure via setParams
209
+
183
210
  conditionalNode2.next(leftNode, 'left');
184
211
  conditionalNode2.next(rightNode, 'right');
185
212
  const conditionalFlow2 = new Flow(conditionalNode2);
@@ -307,47 +334,187 @@ retryFlow.run({});
307
334
  // RetryNode: Succeeded!
308
335
  ```
309
336
 
310
- ## Built-in Nodes
337
+ ### 7. Inter-Node Communication with Shared State (Advanced Example)
338
+
339
+ Demonstrates how to pass data between nodes using the `shared` object, particularly important in asynchronous workflows. This example showcases two LLM nodes interacting, where the output of the first influences the input of the second.
340
+
341
+ ```javascript
342
+ import { AsyncFlow } from '@fractal-solutions/qflow';
343
+ import { DeepSeekLLMNode } from '@fractal-solutions/qflow/nodes';
344
+
345
+ // Node representing the "Apologist" personality
346
+ class ApologistNode extends DeepSeekLLMNode {
347
+ // preparePrompt now receives the shared object
348
+ preparePrompt(shared) {
349
+ const { topic } = this.params;
350
+ this.params.prompt = `You are an eloquent apologist. Your task is to defend the following topic with a concise, positive, and persuasive argument, no more than 3 sentences: "${topic}"`;
351
+ }
352
+
353
+ // postAsync is used to ensure shared state is updated after async execution
354
+ async postAsync(shared, prepRes, execRes) {
355
+ shared.apologistArgument = execRes; // Store the argument in shared state
356
+ return 'default'; // Signal default transition
357
+ }
358
+ }
359
+
360
+ // Node representing the "Heretic" personality
361
+ class HereticNode extends DeepSeekLLMNode {
362
+ // preparePrompt now receives the shared object
363
+ preparePrompt(shared) {
364
+ const { apologistArgument } = shared; // Access the argument from shared state
365
+
366
+ if (!apologistArgument) {
367
+ throw new Error("Apologist's argument is missing from shared state. Cannot critique.");
368
+ }
369
+
370
+ this.params.prompt = `You are a skeptical heretic. Your task is to critically analyze and briefly refute or find a flaw in the following argument, no more than 3 sentences: "${apologistArgument}"`;
371
+ }
372
+
373
+ // postAsync is used to ensure shared state is updated after async execution
374
+ async postAsync(shared, prepRes, execRes) {
375
+ shared.hereticCritique = execRes; // Store the critique in shared state
376
+ return execRes; // Return the critique as the node's result
377
+ }
378
+ }
379
+
380
+ (async () => {
381
+ const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY; // Ensure this is set in .env or env vars
382
+
383
+ if (!DEEPSEEK_API_KEY) {
384
+ console.warn("WARNING: DeepSeek API key is not set. Please configure it to run this example.");
385
+ return;
386
+ }
387
+
388
+ console.log('--- Starting Apologist vs. Heretic LLM Workflow ---');
389
+
390
+ const topicInput = prompt("Enter a topic for the Apologist to defend (e.g., 'The benefits of remote work'):\nYour topic: ");
391
+
392
+ if (!topicInput) {
393
+ console.log("No topic provided. Exiting.");
394
+ return;
395
+ }
396
+
397
+ const apologist = new ApologistNode();
398
+ apologist.setParams({ apiKey: DEEPSEEK_API_KEY, topic: topicInput });
311
399
 
312
- `qflow` comes with a set of pre-built nodes to accelerate common development tasks. These are available via `@fractal-solutions/qflow/nodes`.
400
+ const heretic = new HereticNode();
401
+ heretic.setParams({ apiKey: DEEPSEEK_API_KEY });
313
402
 
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.
403
+ apologist.next(heretic);
319
404
 
320
- **Example: Using a Built-in Node (WebScraperNode)**
405
+ const debateFlow = new AsyncFlow(apologist);
406
+
407
+ try {
408
+ const sharedState = {}; // Initialize an empty shared state object
409
+ await debateFlow.runAsync(sharedState); // Run the flow, passing the shared state
410
+
411
+ console.log('\n--- The Debate Unfolds ---');
412
+ console.log('Topic:', topicInput);
413
+ console.log('\nApologist\'s Argument:');
414
+ console.log(sharedState.apologistArgument);
415
+ console.log('\nHeretic\'s Critique:');
416
+ console.log(sharedState.hereticCritique);
417
+ console.log('\n--- Workflow Finished ---');
418
+
419
+ } catch (error) {
420
+ console.error('--- Workflow Failed ---', error);
421
+ }
422
+ })();
423
+
424
+ ```
425
+
426
+ ## Error Handling
427
+
428
+ `qflow` provides mechanisms to handle errors gracefully within your workflows.
429
+
430
+ * **Node-level Error Handling:**
431
+ * Synchronous `Node`s: If an error occurs in `prep` or `exec`, it will be caught by the flow and propagate up. You can implement `execFallback(prepRes, error)` in your `Node` subclass to provide a fallback mechanism when `exec` fails after all retries.
432
+ * Asynchronous `AsyncNode`s: Similarly, `prepAsync` or `execAsync` can throw errors. Implement `execFallbackAsync(prepRes, error)` for asynchronous fallbacks.
433
+ * **Flow-level Error Handling:**
434
+ * When you run a flow using `flow.run(sharedState)` or `await flow.runAsync(sharedState)`, any unhandled errors from within the nodes will propagate up and can be caught using standard JavaScript `try...catch` blocks around the `run` or `runAsync` call. This allows you to manage errors at the workflow level.
321
435
 
322
436
  ```javascript
323
- import { AsyncFlow } from '@fractal-solutions/qflow';
324
- import { ScrapeURLNode } from '@fractal-solutions/qflow/nodes'; // Correct import for WebScraperNode
437
+ import { Node, Flow } from '@fractal-solutions/qflow';
325
438
 
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
439
+ class FailingNode extends Node {
440
+ exec() {
441
+ throw new Error("Something went wrong in FailingNode!");
442
+ }
443
+ execFallback(prepRes, error) {
444
+ console.error("FailingNode fallback triggered:", error.message);
445
+ return "Fallback successful!";
338
446
  }
339
447
  }
340
448
 
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);
449
+ const failingNode = new FailingNode();
450
+ const errorFlow = new Flow(failingNode);
451
+
452
+ try {
453
+ const result = errorFlow.run({});
454
+ console.log("Flow completed with result:", result);
455
+ } catch (error) {
456
+ console.error("Flow failed with unhandled error:", error.message);
346
457
  }
458
+ // Expected output:
459
+ // FailingNode fallback triggered: Something went wrong in FailingNode!
460
+ // Flow completed with result: Fallback successful!
461
+ ```
347
462
 
348
- runScrapeFlow();
349
- // Expected output (will vary based on example.com content):
350
- // Scraped Title: Example Domain
463
+ ## Debugging
464
+
465
+ Debugging `qflow` workflows can be done using standard JavaScript debugging tools and techniques.
466
+
467
+ * **`console.log`:** The simplest way to inspect data and execution flow. Strategically place `console.log` statements within `prep`, `exec`, `post`, and their `Async` counterparts to trace the `shared` object, `prepRes`, and `execRes` values.
468
+ * **Debugger:** Use your IDE's built-in debugger (e.g., VS Code's debugger) or Node.js/Bun's inspector (`node --inspect` or `bun --inspect`). Set breakpoints within your node's lifecycle methods to step through the execution and examine the state.
469
+ * **Error Messages:** Pay close attention to the error messages and stack traces. `qflow` aims to provide clear error messages that point to the source of the problem within your nodes.
470
+
471
+ ## Testing
472
+
473
+ Testing `qflow` workflows involves unit testing individual nodes and integration testing entire flows.
474
+
475
+ * **Unit Testing Nodes:**
476
+ * Test each `Node` or `AsyncNode` subclass in isolation.
477
+ * Mock external dependencies (e.g., API calls for `LLMNode`, `GitHubNode`) to ensure tests are fast and reliable.
478
+ * Verify the behavior of `prep`, `exec`, `post`, and their `Async` counterparts, as well as `setParams` and `execFallback`.
479
+ * **Integration Testing Flows:**
480
+ * Test entire `Flow`s or `AsyncFlow`s to ensure nodes are chained correctly and data flows as expected.
481
+ * Provide controlled `shared` state inputs and assert on the final `shared` state or the flow's return value.
482
+ * Use your preferred testing framework (e.g., Jest, Mocha, Bun's built-in test runner).
483
+
484
+ ```javascript
485
+ // Example (using Bun's test runner syntax)
486
+ import { test, expect } from "bun:test";
487
+ import { Node, Flow } from '@fractal-solutions/qflow';
488
+
489
+ class TestNodeA extends Node {
490
+ exec(input) { return input + 1; }
491
+ }
492
+
493
+ class TestNodeB extends Node {
494
+ exec(input) { return input * 2; }
495
+ }
496
+
497
+ test("Simple Flow should process data correctly", () => {
498
+ const nodeA = new TestNodeA();
499
+ const nodeB = new TestNodeB();
500
+ nodeA.next(nodeB);
501
+
502
+ const flow = new Flow(nodeA);
503
+ const sharedState = { initialValue: 5 };
504
+ const result = flow.run(sharedState); // Assuming run returns the final execRes of the last node
505
+
506
+ expect(result).toBe(12); // (5 + 1) * 2 = 12
507
+ });
508
+
509
+ test("Node should handle parameters via setParams", () => {
510
+ class ParamNode extends Node {
511
+ exec() { return this.params.value; }
512
+ }
513
+ const node = new ParamNode();
514
+ node.setParams({ value: "hello" });
515
+ const result = node.run({});
516
+ expect(result).toBe("hello");
517
+ });
351
518
  ```
352
519
 
353
520
  ## Integration
@@ -363,4 +530,4 @@ runScrapeFlow();
363
530
 
364
531
  We welcome contributions! Please see our GitHub repository for more details on how to contribute.
365
532
 
366
- ---
533
+ ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
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",