@fractal-solutions/qflow 1.0.3 → 1.0.4

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 +209 -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
 
@@ -25,37 +26,47 @@ bun add @fractal-solutions/qflow
25
26
 
26
27
  ## Core Abstractions
27
28
 
28
- `qflow` is built around a few core abstractions that allow you to define powerful and flexible workflows.
29
+ `qflow` is built around a few core abstractions that enable powerful and flexible workflow definitions.
30
+
31
+ ### Shared State (`shared` object)
32
+
33
+ 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
34
 
30
35
  ### Node
31
36
 
32
- The fundamental building block of any `qflow` workflow. A `Node` represents a single operation or step in your flow.
37
+ The fundamental building block of any `qflow` workflow. A `Node` represents a single, atomic operation or step in your flow.
33
38
 
34
- * `prep(shared)`: Prepares data for execution.
39
+ * `prep(shared)`: Prepares data for execution. Receives the `shared` object.
35
40
  * `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.
41
+ * `post(shared, prepRes, execRes)`: Processes the result of `exec`. Receives the `shared` object.
42
+ * `setParams(params)`: Configures the node with specific parameters. Parameters are accessible via `this.params`.
38
43
  * `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.
44
+ * `transition(action)`: Initiates a conditional transition to another node, allowing for dynamic branching.
40
45
 
41
46
  **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.
47
+ 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:
48
+ * `prepAsync(shared)`
49
+ * `execAsync(prepRes, shared)`
50
+ * `postAsync(shared, prepRes, execRes)`
51
+ * `preparePrompt(shared)` (specifically for LLM nodes, allowing prompt construction based on `shared` state)
52
+
53
+ These `async` methods ensure proper awaiting and data propagation within asynchronous workflows.
43
54
 
44
55
  ### Flow
45
56
 
46
57
  A `Flow` orchestrates the execution of a sequence of `Node`s. It defines the overall path and manages the transitions between nodes.
47
58
 
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.
59
+ * `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).
60
+ * `_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
61
 
51
62
  **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.
63
+ 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
64
 
54
65
  ### ConditionalTransition
55
66
 
56
- A helper class used with `Node.transition()` to define conditional branching in your flows.
67
+ A helper class used in conjunction with `Node.transition()` to define conditional branching within your workflows.
57
68
 
58
- * `to(targetNode)`: Specifies the target node for the transition.
69
+ * `to(targetNode)`: Specifies the target node for the transition based on the action returned by the preceding node.
59
70
 
60
71
  ## Basic Usage & Examples
61
72
 
@@ -134,19 +145,15 @@ flow.run({});
134
145
 
135
146
  ### 3. Conditional Flow
136
147
 
137
- Using `transition()` for dynamic branching based on an action.
148
+ Using `transition()` for dynamic branching based on an action. This example demonstrates configuring a node using `setParams` for a cleaner API.
138
149
 
139
150
  ```javascript
140
151
  import { Node, Flow } from '@fractal-solutions/qflow';
141
152
 
142
153
  class ConditionalNode extends Node {
143
- constructor(shouldGoLeft) {
144
- super();
145
- this.shouldGoLeft = shouldGoLeft;
146
- }
147
-
148
154
  exec() {
149
- if (this.shouldGoLeft) {
155
+ // Access shouldGoLeft from this.params, which is set via setParams
156
+ if (this.params.shouldGoLeft) {
150
157
  console.log('ConditionalNode: Going left');
151
158
  return 'left';
152
159
  } else {
@@ -166,7 +173,9 @@ function MessageNode(message) {
166
173
  })();
167
174
  }
168
175
 
169
- const conditionalNode = new ConditionalNode(true);
176
+ const conditionalNode = new ConditionalNode();
177
+ conditionalNode.setParams({ shouldGoLeft: true }); // Configure via setParams
178
+
170
179
  const leftNode = MessageNode('Went Left');
171
180
  const rightNode = MessageNode('Went Right');
172
181
 
@@ -179,7 +188,9 @@ conditionalFlow.run({});
179
188
  // ConditionalNode: Going left
180
189
  // Went Left
181
190
 
182
- const conditionalNode2 = new ConditionalNode(false);
191
+ const conditionalNode2 = new ConditionalNode();
192
+ conditionalNode2.setParams({ shouldGoLeft: false }); // Configure via setParams
193
+
183
194
  conditionalNode2.next(leftNode, 'left');
184
195
  conditionalNode2.next(rightNode, 'right');
185
196
  const conditionalFlow2 = new Flow(conditionalNode2);
@@ -307,47 +318,187 @@ retryFlow.run({});
307
318
  // RetryNode: Succeeded!
308
319
  ```
309
320
 
310
- ## Built-in Nodes
321
+ ### 7. Inter-Node Communication with Shared State (Advanced Example)
322
+
323
+ 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.
324
+
325
+ ```javascript
326
+ import { AsyncFlow } from '@fractal-solutions/qflow';
327
+ import { DeepSeekLLMNode } from '@fractal-solutions/qflow/nodes';
328
+
329
+ // Node representing the "Apologist" personality
330
+ class ApologistNode extends DeepSeekLLMNode {
331
+ // preparePrompt now receives the shared object
332
+ preparePrompt(shared) {
333
+ const { topic } = this.params;
334
+ 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}"`;
335
+ }
336
+
337
+ // postAsync is used to ensure shared state is updated after async execution
338
+ async postAsync(shared, prepRes, execRes) {
339
+ shared.apologistArgument = execRes; // Store the argument in shared state
340
+ return 'default'; // Signal default transition
341
+ }
342
+ }
343
+
344
+ // Node representing the "Heretic" personality
345
+ class HereticNode extends DeepSeekLLMNode {
346
+ // preparePrompt now receives the shared object
347
+ preparePrompt(shared) {
348
+ const { apologistArgument } = shared; // Access the argument from shared state
349
+
350
+ if (!apologistArgument) {
351
+ throw new Error("Apologist's argument is missing from shared state. Cannot critique.");
352
+ }
353
+
354
+ 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}"`;
355
+ }
356
+
357
+ // postAsync is used to ensure shared state is updated after async execution
358
+ async postAsync(shared, prepRes, execRes) {
359
+ shared.hereticCritique = execRes; // Store the critique in shared state
360
+ return execRes; // Return the critique as the node's result
361
+ }
362
+ }
363
+
364
+ (async () => {
365
+ const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY; // Ensure this is set in .env or env vars
366
+
367
+ if (!DEEPSEEK_API_KEY) {
368
+ console.warn("WARNING: DeepSeek API key is not set. Please configure it to run this example.");
369
+ return;
370
+ }
371
+
372
+ console.log('--- Starting Apologist vs. Heretic LLM Workflow ---');
373
+
374
+ const topicInput = prompt("Enter a topic for the Apologist to defend (e.g., 'The benefits of remote work'):\nYour topic: ");
375
+
376
+ if (!topicInput) {
377
+ console.log("No topic provided. Exiting.");
378
+ return;
379
+ }
380
+
381
+ const apologist = new ApologistNode();
382
+ apologist.setParams({ apiKey: DEEPSEEK_API_KEY, topic: topicInput });
383
+
384
+ const heretic = new HereticNode();
385
+ heretic.setParams({ apiKey: DEEPSEEK_API_KEY });
386
+
387
+ apologist.next(heretic);
311
388
 
312
- `qflow` comes with a set of pre-built nodes to accelerate common development tasks. These are available via `@fractal-solutions/qflow/nodes`.
389
+ const debateFlow = new AsyncFlow(apologist);
313
390
 
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.
391
+ try {
392
+ const sharedState = {}; // Initialize an empty shared state object
393
+ await debateFlow.runAsync(sharedState); // Run the flow, passing the shared state
319
394
 
320
- **Example: Using a Built-in Node (WebScraperNode)**
395
+ console.log('\n--- The Debate Unfolds ---');
396
+ console.log('Topic:', topicInput);
397
+ console.log('\nApologist\'s Argument:');
398
+ console.log(sharedState.apologistArgument);
399
+ console.log('\nHeretic\'s Critique:');
400
+ console.log(sharedState.hereticCritique);
401
+ console.log('\n--- Workflow Finished ---');
402
+
403
+ } catch (error) {
404
+ console.error('--- Workflow Failed ---', error);
405
+ }
406
+ })();
407
+
408
+ ```
409
+
410
+ ## Error Handling
411
+
412
+ `qflow` provides mechanisms to handle errors gracefully within your workflows.
413
+
414
+ * **Node-level Error Handling:**
415
+ * 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.
416
+ * Asynchronous `AsyncNode`s: Similarly, `prepAsync` or `execAsync` can throw errors. Implement `execFallbackAsync(prepRes, error)` for asynchronous fallbacks.
417
+ * **Flow-level Error Handling:**
418
+ * 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
419
 
322
420
  ```javascript
323
- import { AsyncFlow } from '@fractal-solutions/qflow';
324
- import { ScrapeURLNode } from '@fractal-solutions/qflow/nodes'; // Correct import for WebScraperNode
421
+ import { Node, Flow } from '@fractal-solutions/qflow';
325
422
 
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
423
+ class FailingNode extends Node {
424
+ exec() {
425
+ throw new Error("Something went wrong in FailingNode!");
426
+ }
427
+ execFallback(prepRes, error) {
428
+ console.error("FailingNode fallback triggered:", error.message);
429
+ return "Fallback successful!";
338
430
  }
339
431
  }
340
432
 
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);
433
+ const failingNode = new FailingNode();
434
+ const errorFlow = new Flow(failingNode);
435
+
436
+ try {
437
+ const result = errorFlow.run({});
438
+ console.log("Flow completed with result:", result);
439
+ } catch (error) {
440
+ console.error("Flow failed with unhandled error:", error.message);
346
441
  }
442
+ // Expected output:
443
+ // FailingNode fallback triggered: Something went wrong in FailingNode!
444
+ // Flow completed with result: Fallback successful!
445
+ ```
446
+
447
+ ## Debugging
347
448
 
348
- runScrapeFlow();
349
- // Expected output (will vary based on example.com content):
350
- // Scraped Title: Example Domain
449
+ Debugging `qflow` workflows can be done using standard JavaScript debugging tools and techniques.
450
+
451
+ * **`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.
452
+ * **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.
453
+ * **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.
454
+
455
+ ## Testing
456
+
457
+ Testing `qflow` workflows involves unit testing individual nodes and integration testing entire flows.
458
+
459
+ * **Unit Testing Nodes:**
460
+ * Test each `Node` or `AsyncNode` subclass in isolation.
461
+ * Mock external dependencies (e.g., API calls for `LLMNode`, `GitHubNode`) to ensure tests are fast and reliable.
462
+ * Verify the behavior of `prep`, `exec`, `post`, and their `Async` counterparts, as well as `setParams` and `execFallback`.
463
+ * **Integration Testing Flows:**
464
+ * Test entire `Flow`s or `AsyncFlow`s to ensure nodes are chained correctly and data flows as expected.
465
+ * Provide controlled `shared` state inputs and assert on the final `shared` state or the flow's return value.
466
+ * Use your preferred testing framework (e.g., Jest, Mocha, Bun's built-in test runner).
467
+
468
+ ```javascript
469
+ // Example (using Bun's test runner syntax)
470
+ import { test, expect } from "bun:test";
471
+ import { Node, Flow } from '@fractal-solutions/qflow';
472
+
473
+ class TestNodeA extends Node {
474
+ exec(input) { return input + 1; }
475
+ }
476
+
477
+ class TestNodeB extends Node {
478
+ exec(input) { return input * 2; }
479
+ }
480
+
481
+ test("Simple Flow should process data correctly", () => {
482
+ const nodeA = new TestNodeA();
483
+ const nodeB = new TestNodeB();
484
+ nodeA.next(nodeB);
485
+
486
+ const flow = new Flow(nodeA);
487
+ const sharedState = { initialValue: 5 };
488
+ const result = flow.run(sharedState); // Assuming run returns the final execRes of the last node
489
+
490
+ expect(result).toBe(12); // (5 + 1) * 2 = 12
491
+ });
492
+
493
+ test("Node should handle parameters via setParams", () => {
494
+ class ParamNode extends Node {
495
+ exec() { return this.params.value; }
496
+ }
497
+ const node = new ParamNode();
498
+ node.setParams({ value: "hello" });
499
+ const result = node.run({});
500
+ expect(result).toBe("hello");
501
+ });
351
502
  ```
352
503
 
353
504
  ## Integration
@@ -363,4 +514,4 @@ runScrapeFlow();
363
514
 
364
515
  We welcome contributions! Please see our GitHub repository for more details on how to contribute.
365
516
 
366
- ---
517
+ ---
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.4",
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",