@fractal-solutions/qflow 1.0.16 → 1.0.18

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 +347 -23
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -120,8 +120,35 @@ A helper class used in conjunction with `Node.transition()` to define conditiona
120
120
  and synthesize information into comprehensive answers or documents, acting as automated
121
121
  research assistants.
122
122
 
123
+ ## How to use the Docs and Examples
123
124
 
124
125
 
126
+ The examples in [Basic Usage & Examples](#basic-usage--examples) below will cover the core functionalities of `qflow`. For more advanced and specific use cases involving the built-in integrations, please explore the [`examples/` folder](https://github.com/fractal-solutions/qflow/tree/main/examples) in the project's GitHub repository. There you will find detailed scripts demonstrating how to use nodes for:
127
+
128
+ * [**LLMs (DeepSeek, OpenAI, Gemini, Ollama):**](#7-inter-node-communication-with-shared-state-advanced-example) The core of agentic behavior.
129
+ * For agents, use specialized LLM nodes like `AgentDeepSeekLLMNode`, `AgentOpenAILLMNode`, `AgentOllamaLLMNode`.
130
+ * [**Agent:**](#12-interactive-agent-example) Orchestrating tools and LLM reasoning to achieve complex goals.
131
+ * [**Embedding:**](#18-embedding-node) For generating vector embeddings from text using Ollama.
132
+ * [**Semantic Memory:**](#19-semantic-memory-node) For storing and retrieving memories based on semantic similarity (RAG) using Ollama.
133
+ * [**Memory:**](#15-memory-node-lightweight-rag) For lightweight, keyword-based long-term memory and 'RAG' (lightweight, dependency free option).
134
+ * [**Transform:**](#16-transform-node) For dynamic data manipulation and reformatting.
135
+ * [**CodeInterpreter:**](#14-code-interpreter-example) For executing dynamic code (in Python) within the workflow.
136
+ * [**Interactive Agent:**](#12-interactive-agent-example) An agent that takes a goal from user input and uses its tools to achieve it.
137
+ * [**Shell:**](#8-shell-command-example) For system-level interaction and execution.
138
+ * [**HTTP:**](#10-generic-http-request-example) For universal API access.
139
+ * [**FileSystem:**](#9-file-system-example) For reading and writing local data.
140
+ * **User Input:** For human-in-the-loop control.
141
+ * [**Web Search:**](#11-web-search-example) Discovering information on the web using either:
142
+ * `DuckDuckGoSearchNode`: API-key-free, using DuckDuckGo's HTML interface.
143
+ * `GoogleSearchNode`: Requires a Google API Key and Custom Search Engine ID for more robust results.
144
+ * **WebScraper:** For targeted web scraping.
145
+ * [**DataExtractor:**](#13-data-extraction-example) For targeted data extraction.
146
+ * **GitHub:** Creating and managing issues.
147
+ * **HackerNews:** Fetching top stories and item details.
148
+ * **Stripe:** Creating charges and retrieving account balances.
149
+
150
+ These examples are a great resource for understanding how to leverage `qflow` to its full potential.
151
+
125
152
  ## Basic Usage & Examples
126
153
 
127
154
  ### 1. Simple Node
@@ -589,7 +616,8 @@ import {
589
616
  UserInputNode,
590
617
  AgentNode,
591
618
  CodeInterpreterNode,
592
- MemoryNode
619
+ MemoryNode,
620
+ TransformNode
593
621
  } from '@fractal-solutions/qflow/nodes';
594
622
 
595
623
  // Ensure your DeepSeek API Key is set as an environment variable
@@ -621,6 +649,7 @@ const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
621
649
  const userInput = new UserInputNode(); // Agent can also ask for user input
622
650
  const codeInterpreter = new CodeInterpreterNode(); // Agent can execute code
623
651
  const memoryNode = new MemoryNode(); // Agent can store and retrieve memories
652
+ const transformNode = new TransformNode(); // Agent can transform data
624
653
 
625
654
  // Map tool names to their instances
626
655
  const availableTools = {
@@ -633,6 +662,7 @@ const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
633
662
  user_input: userInput,
634
663
  code_interpreter: codeInterpreter,
635
664
  memory_node: memoryNode,
665
+ transform_node: transformNode,
636
666
  // Add other tools as needed
637
667
  };
638
668
 
@@ -869,33 +899,327 @@ const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
869
899
 
870
900
  console.log('\n--- MemoryNode RAG Example Finished ---');
871
901
  })();
872
- `````
902
+ ```
873
903
 
874
- ## Exploring More Examples
904
+ ### 16. Transform Node
875
905
 
906
+ Dynamically transforming data using custom JavaScript functions.
876
907
 
877
- The examples above cover the core functionalities of `qflow`. For more advanced and specific use cases involving the built-in integrations, please explore the [`examples/` folder](https://github.com/fractal-solutions/qflow/tree/main/examples) in the project's GitHub repository. There you will find detailed scripts demonstrating how to use nodes for:
908
+ ```javascript
909
+ import { AsyncFlow } from '@fractal-solutions/qflow';
910
+ import { TransformNode } from '@fractal-solutions/qflow/nodes';
911
+
912
+ (async () => {
913
+ console.log('--- Running TransformNode Example ---');
914
+
915
+ // Example 1: Map an array of numbers
916
+ const numbers = [1, 2, 3];
917
+ const doubleNumbers = new TransformNode();
918
+ doubleNumbers.setParams({
919
+ input: numbers,
920
+ transformFunction: '(data) => data.map(x => x * 2)'
921
+ });
922
+
923
+ const flow1 = new AsyncFlow(doubleNumbers);
924
+ try {
925
+ const result = await flow1.runAsync({});
926
+ console.log('Doubled Numbers:', result); // Expected: [2, 4, 6]
927
+ } catch (error) {
928
+ console.error('Transform Flow 1 Failed:', error);
929
+ }
930
+
931
+ // Example 2: Filter an array of objects
932
+ const users = [
933
+ { name: 'Alice', active: true },
934
+ { name: 'Bob', active: false },
935
+ { name: 'Charlie', active: true }
936
+ ];
937
+ const activeUsers = new TransformNode();
938
+ activeUsers.setParams({
939
+ input: users,
940
+ transformFunction: '(data) => data.filter(user => user.active)'
941
+ });
942
+
943
+ const flow2 = new AsyncFlow(activeUsers);
944
+ try {
945
+ const result = await flow2.runAsync({});
946
+ console.log('Active Users:', result); // Expected: [{ name: 'Alice', active: true }, { name: 'Charlie', active: true }]
947
+ } catch (error) {
948
+ console.error('Transform Flow 2 Failed:', error);
949
+ }
950
+
951
+ // Example 3: Extract a specific property from an object
952
+ const product = { id: 1, name: 'Laptop', price: 1200 };
953
+ const productName = new TransformNode();
954
+ productName.setParams({
955
+ input: product,
956
+ transformFunction: '(data) => data.name'
957
+ });
958
+
959
+ const flow3 = new AsyncFlow(productName);
960
+ try {
961
+ const result = await flow3.runAsync({});
962
+ console.log('Product Name:', result); // Expected: 'Laptop'
963
+ } catch (error) {
964
+ console.error('Transform Flow 3 Failed:', error);
965
+ }
966
+
967
+ console.log('\n--- TransformNode Example Finished ---');
968
+ })();
969
+ ```
970
+
971
+ ### 17. Plotting Data with Python Code Interpreter
972
+
973
+ Demonstrates using the `CodeInterpreterNode` to execute Python code for data visualization, saving the output to a file.
974
+
975
+ **Prerequisites:** To run this example, you need Python and `matplotlib` installed. It is highly recommended to use a Python [virtual environment](https://docs.python.org/3/library/venv.html) to manage your Python dependencies.
976
+
977
+ Follow these steps in *your project folder* where you are using `qflow`:
978
+
979
+ 1. **Create a Python Virtual Environment:**
980
+ ```bash
981
+ python3 -m venv .venv
982
+ ```
983
+
984
+ 2. **Activate the Virtual Environment:**
985
+ * On Linux/macOS:
986
+ ```bash
987
+ source .venv/bin/activate
988
+ ```
989
+ * On Windows (Command Prompt):
990
+ ```bash
991
+ .venv\Scripts\activate.bat
992
+ ```
993
+ * On Windows (PowerShell):
994
+ ```powershell
995
+ .venv\Scripts\Activate.ps1
996
+ ```
997
+
998
+ 3. **Install `matplotlib` (and any other Python libraries) within the activated environment:**
999
+ ```bash
1000
+ pip install matplotlib
1001
+ ```
1002
+
1003
+ 4. **Configure the Python Interpreter Path:**
1004
+ Create or update a `.env` file in your project's root directory (where your `qflow` application runs) and add the following line, pointing to the Python executable within your virtual environment:
1005
+ ```bash
1006
+ QFLOW_PYTHON_INTERPRETER=/path/to/your/project/.venv/bin/python
1007
+ # Example for Windows:
1008
+ # QFLOW_PYTHON_INTERPRETER=C:\path\to\your\project\.venv\Scripts\python.exe
1009
+ ```
1010
+ *Note: If you are not using Bun (which loads `.env` files by default), you might need a library like `dotenv` (e.g., `require('dotenv').config();`) in your application to load environment variables from the `.env` file.*
1011
+
1012
+ If you use a Python virtual environment, you can specify its Python executable via an environment variable.
1013
+
1014
+ ```bash
1015
+ # Example for installing matplotlib (preferably in a virtual environment)
1016
+ pip install matplotlib
1017
+
1018
+ # Example for setting the environment variable (if using a virtual environment)
1019
+ export QFLOW_PYTHON_INTERPRETER=/path/to/your/venv/bin/python
1020
+ # Or for Windows PowerShell
1021
+ # $env:QFLOW_PYTHON_INTERPRETER="C:\path\to\your\venv\Scripts\python.exe"
1022
+ ```
1023
+
1024
+ ```javascript
1025
+ import { AsyncFlow } from '@fractal-solutions/qflow';
1026
+ import { CodeInterpreterNode, WriteFileNode } from '@fractal-solutions/qflow/nodes';
1027
+ import path from 'path';
1028
+ import os from 'os';
1029
+
1030
+ (async () => {
1031
+ console.log('--- Running Plot Data with Python CodeInterpreter Example ---');
1032
+
1033
+ // 1. Define sample data
1034
+ const dataToPlot = {
1035
+ x: [1, 2, 3, 4, 5],
1036
+ y: [2, 4, 5, 4, 6]
1037
+ };
1038
+
1039
+ // Define temporary file paths
1040
+ const tempDir = os.tmpdir();
1041
+ const dataFileName = `plot_data_${Date.now()}.json`;
1042
+ const plotFileName = `sample_plot_${Date.now()}.png`;
1043
+ const dataFilePath = path.join(tempDir, dataFileName);
1044
+ const plotFilePath = path.join(tempDir, plotFileName);
1045
+
1046
+ // 2. Python script for plotting
1047
+ const pythonPlotScript = `
1048
+ import matplotlib.pyplot as plt
1049
+ import json
1050
+ import sys
1051
+
1052
+ # Get data file path and output plot path from command line arguments
1053
+ data_file_path = sys.argv[1]
1054
+ output_plot_path = sys.argv[2]
1055
+
1056
+ # Read data from the specified JSON file
1057
+ with open(data_file_path, 'r') as f:
1058
+ data = json.load(f)
1059
+
1060
+ x_data = data['x']
1061
+ y_data = data['y']
1062
+
1063
+ # Create the plot
1064
+ plt.figure(figsize=(8, 6))
1065
+ plt.plot(x_data, y_data, marker='o', linestyle='-', color='b')
1066
+ plt.title('Sample Data Plot')
1067
+ plt.xlabel('X-axis')
1068
+ plt.ylabel('Y-axis')
1069
+ plt.grid(True)
1070
+
1071
+ # Save the plot
1072
+ plt.savefig(output_plot_path)
1073
+ print(f"Plot saved to {output_plot_path}")
1074
+ `;
1075
+
1076
+ // 3. Write data to a temporary JSON file
1077
+ const writeDataNode = new WriteFileNode();
1078
+ writeDataNode.setParams({
1079
+ filePath: dataFilePath,
1080
+ content: JSON.stringify(dataToPlot)
1081
+ });
1082
+
1083
+ // 4. Run the Python script using CodeInterpreterNode
1084
+ const plotNode = new CodeInterpreterNode();
1085
+ plotNode.setParams({
1086
+ code: pythonPlotScript,
1087
+ args: [dataFilePath, plotFilePath], // Pass data file and output plot paths as arguments
1088
+ timeout: 15000, // Increased timeout for plotting
1089
+ requireConfirmation: false, // No confirmation needed for this automated task
1090
+ interpreterPath: process.env.QFLOW_PYTHON_INTERPRETER || 'python' // Allow user to specify Python interpreter path, defaults to 'python'
1091
+ });
1092
+
1093
+ // 5. Chain the nodes
1094
+ writeDataNode.next(plotNode);
1095
+
1096
+ // 6. Run the flow
1097
+ const flow = new AsyncFlow(writeDataNode);
1098
+ try {
1099
+ await flow.runAsync({});
1100
+ console.log(`\nPlotting workflow finished. Check for plot at: ${plotFilePath}`);
1101
+ } catch (error) {
1102
+ console.error('Plotting Workflow Failed:', error);
1103
+ }
1104
+ })();
1105
+ ```
1106
+
1107
+ ### 18. Embedding Node
1108
+
1109
+ Generates vector embeddings for text using a local Ollama server. Essential for semantic search and RAG.
1110
+
1111
+ **Prerequisites:** Ensure you have [Ollama](https://ollama.ai/) installed and an embedding model pulled (e.g., `ollama pull nomic-embed-text`).
1112
+
1113
+ ```javascript
1114
+ import { AsyncFlow } from '@fractal-solutions/qflow';
1115
+ import { EmbeddingNode } from '@fractal-solutions/qflow/nodes';
1116
+
1117
+ (async () => {
1118
+ console.log('--- Running EmbeddingNode Example ---');
1119
+
1120
+ const textToEmbed = "Hello, world! This is a test sentence.";
1121
+ const embedNode = new EmbeddingNode();
1122
+ embedNode.setParams({
1123
+ text: textToEmbed,
1124
+ model: 'nomic-embed-text', // Ensure this model is pulled in Ollama
1125
+ baseUrl: 'http://localhost:11434' // Default Ollama URL
1126
+ });
1127
+
1128
+ embedNode.postAsync = async (shared, prepRes, execRes) => {
1129
+ console.log('Embedding Result (first 5 dimensions):', execRes.embedding.slice(0, 5));
1130
+ console.log('Embedding Length:', execRes.embedding.length);
1131
+ return 'default';
1132
+ };
1133
+
1134
+ const flow = new AsyncFlow(embedNode);
1135
+ try {
1136
+ await flow.runAsync({});
1137
+ } catch (error) {
1138
+ console.error('Embedding Flow Failed:', error);
1139
+ }
1140
+
1141
+ console.log('\n--- EmbeddingNode Example Finished ---');
1142
+ })();
1143
+ ```
1144
+
1145
+ ### 19. Semantic Memory Node
1146
+
1147
+ Stores and retrieves text-based memories using vector embeddings for semantic search. This enables agents to have a more advanced, meaning-based long-term memory.
1148
+
1149
+ **Prerequisites:** Requires [Ollama](https://ollama.ai/) and an embedding model (e.g., `ollama pull nomic-embed-text`).
1150
+
1151
+ ```javascript
1152
+ import { AsyncFlow } from '@fractal-solutions/qflow';
1153
+ import { SemanticMemoryNode, DeepSeekLLMNode } from '@fractal-solutions/qflow/nodes';
1154
+
1155
+ const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
1156
+
1157
+ (async () => {
1158
+ if (!DEEPSEEK_API_KEY) {
1159
+ console.warn("WARNING: DEEPSEEK_API_KEY is not set. Please set it to run the SemanticMemoryNode RAG example.");
1160
+ return;
1161
+ }
1162
+
1163
+ console.log('--- Running SemanticMemoryNode RAG Example ---');
1164
+
1165
+ // 1. Store a semantic memory
1166
+ const storeSemanticMemory = new SemanticMemoryNode();
1167
+ storeSemanticMemory.setParams({
1168
+ action: 'store',
1169
+ content: 'The capital of France is Paris. It is known for the Eiffel Tower and its romantic atmosphere.',
1170
+ id: 'france_capital_sem',
1171
+ metadata: { source: 'wikipedia', topic: 'geography' }
1172
+ });
1173
+ await new AsyncFlow(storeSemanticMemory).runAsync({});
1174
+ console.log('Semantic memory stored.');
1175
+
1176
+ // 2. Store another memory for RAG
1177
+ const storeRagSemanticMemory = new SemanticMemoryNode();
1178
+ storeRagSemanticMemory.setParams({
1179
+ action: 'store',
1180
+ content: 'Quantum computing uses quantum-mechanical phenomena like superposition and entanglement to perform computations.',
1181
+ id: 'quantum_comp_intro',
1182
+ metadata: { topic: 'physics' }
1183
+ });
1184
+ await new AsyncFlow(storeRagSemanticMemory).runAsync({});
1185
+ console.log('Another semantic memory stored.');
1186
+
1187
+ // 3. Retrieve relevant semantic memories based on a query
1188
+ const ragRetrieveSemantic = new SemanticMemoryNode();
1189
+ ragRetrieveSemantic.setParams({
1190
+ action: 'retrieve',
1191
+ query: 'city of love',
1192
+ topK: 1
1193
+ });
1194
+
1195
+ // 4. Use an LLM to answer a question based on retrieved memories
1196
+ const ragLLM = new DeepSeekLLMNode();
1197
+ ragLLM.setParams({ apiKey: DEEPSEEK_API_KEY });
1198
+
1199
+ ragRetrieveSemantic.next(ragLLM);
1200
+
1201
+ ragLLM.preparePrompt = (shared) => {
1202
+ const retrievedContent = shared.semanticMemoryResult.map(mem => mem.content).join('\n\n');
1203
+ ragLLM.setParams({
1204
+ prompt: `Based on the following context, answer the question:\n\nContext:\n${retrievedContent}\n\nQuestion: Explain quantum computing in simple terms.`,
1205
+ keyword: 'semantic_rag_llm'
1206
+ });
1207
+ };
1208
+
1209
+ const ragFlow = new AsyncFlow(ragRetrieveSemantic);
1210
+ try {
1211
+ const ragResult = await ragFlow.runAsync({});
1212
+ console.log('\n--- Semantic RAG Example LLM Response ---');
1213
+ console.log(ragResult);
1214
+ } catch (error) {
1215
+ console.error('RAG Flow Failed:', error);
1216
+ }
1217
+
1218
+ console.log('\n--- SemanticMemoryNode RAG Example Finished ---');
1219
+ })();
1220
+ ```
878
1221
 
879
- * **LLMs (DeepSeek, OpenAI, Gemini, Ollama):** The core of agentic behavior.
880
- * For agents, use specialized LLM nodes like `AgentDeepSeekLLMNode`, `AgentOpenAILLMNode`, `AgentOllamaLLMNode`.
881
- * **Agent:** Orchestrating tools and LLM reasoning to achieve complex goals.
882
- * **Memory:** For lightweight, keyword-based long-term memory and RAG.
883
- * **CodeInterpreter:** For executing dynamic code (e.g., Python) within the workflow.
884
- * **Interactive Agent:** An agent that takes a goal from user input and uses its tools to achieve it.
885
- * **Shell:** For system-level interaction and execution.
886
- * **HTTP:** For universal API access.
887
- * **FileSystem:** For reading and writing local data.
888
- * **User Input:** For human-in-the-loop control.
889
- * **Web Search:** Discovering information on the web using either:
890
- * `DuckDuckGoSearchNode`: API-key-free, using DuckDuckGo's HTML interface.
891
- * `GoogleSearchNode`: Requires a Google API Key and Custom Search Engine ID for more robust results.
892
- * **WebScraper:** For targeted web scraping.
893
- * **DataExtractor:** For targeted data extraction.
894
- * **GitHub:** Creating and managing issues.
895
- * **HackerNews:** Fetching top stories and item details.
896
- * **Stripe:** Creating charges and retrieving account balances.
897
1222
 
898
- These examples are a great resource for understanding how to leverage `qflow` to its full potential.
899
1223
 
900
1224
 
901
1225
  ## Error Handling
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.16",
3
+ "version": "1.0.18",
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",