@fractal-solutions/qflow 1.0.17 → 1.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +264 -22
- 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. Specific instructions on library use in [matplotlib example](#17-plotting-data-with-python-code-interpreter).
|
|
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
|
|
@@ -941,32 +968,247 @@ import { TransformNode } from '@fractal-solutions/qflow/nodes';
|
|
|
941
968
|
})();
|
|
942
969
|
```
|
|
943
970
|
|
|
944
|
-
|
|
971
|
+
### 17. Plotting Data with Python Code Interpreter
|
|
945
972
|
|
|
973
|
+
Demonstrates using the `CodeInterpreterNode` to execute Python code for data visualization, saving the output to a file.
|
|
946
974
|
|
|
947
|
-
|
|
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
|
+
|
|
1013
|
+
```javascript
|
|
1014
|
+
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
1015
|
+
import { CodeInterpreterNode, WriteFileNode } from '@fractal-solutions/qflow/nodes';
|
|
1016
|
+
import path from 'path';
|
|
1017
|
+
import os from 'os';
|
|
1018
|
+
|
|
1019
|
+
(async () => {
|
|
1020
|
+
console.log('--- Running Plot Data with Python CodeInterpreter Example ---');
|
|
1021
|
+
|
|
1022
|
+
// 1. Define sample data
|
|
1023
|
+
const dataToPlot = {
|
|
1024
|
+
x: [1, 2, 3, 4, 5],
|
|
1025
|
+
y: [2, 4, 5, 4, 6]
|
|
1026
|
+
};
|
|
1027
|
+
|
|
1028
|
+
// Define temporary file paths
|
|
1029
|
+
const tempDir = os.tmpdir();
|
|
1030
|
+
const dataFileName = `plot_data_${Date.now()}.json`;
|
|
1031
|
+
const plotFileName = `sample_plot_${Date.now()}.png`;
|
|
1032
|
+
const dataFilePath = path.join(tempDir, dataFileName);
|
|
1033
|
+
const plotFilePath = path.join(tempDir, plotFileName);
|
|
1034
|
+
|
|
1035
|
+
// 2. Python script for plotting
|
|
1036
|
+
const pythonPlotScript = `
|
|
1037
|
+
import matplotlib.pyplot as plt
|
|
1038
|
+
import json
|
|
1039
|
+
import sys
|
|
1040
|
+
|
|
1041
|
+
# Get data file path and output plot path from command line arguments
|
|
1042
|
+
data_file_path = sys.argv[1]
|
|
1043
|
+
output_plot_path = sys.argv[2]
|
|
1044
|
+
|
|
1045
|
+
# Read data from the specified JSON file
|
|
1046
|
+
with open(data_file_path, 'r') as f:
|
|
1047
|
+
data = json.load(f)
|
|
1048
|
+
|
|
1049
|
+
x_data = data['x']
|
|
1050
|
+
y_data = data['y']
|
|
1051
|
+
|
|
1052
|
+
# Create the plot
|
|
1053
|
+
plt.figure(figsize=(8, 6))
|
|
1054
|
+
plt.plot(x_data, y_data, marker='o', linestyle='-', color='b')
|
|
1055
|
+
plt.title('Sample Data Plot')
|
|
1056
|
+
plt.xlabel('X-axis')
|
|
1057
|
+
plt.ylabel('Y-axis')
|
|
1058
|
+
plt.grid(True)
|
|
1059
|
+
|
|
1060
|
+
# Save the plot
|
|
1061
|
+
plt.savefig(output_plot_path)
|
|
1062
|
+
print(f"Plot saved to {output_plot_path}")
|
|
1063
|
+
`;
|
|
1064
|
+
|
|
1065
|
+
// 3. Write data to a temporary JSON file
|
|
1066
|
+
const writeDataNode = new WriteFileNode();
|
|
1067
|
+
writeDataNode.setParams({
|
|
1068
|
+
filePath: dataFilePath,
|
|
1069
|
+
content: JSON.stringify(dataToPlot)
|
|
1070
|
+
});
|
|
1071
|
+
|
|
1072
|
+
// 4. Run the Python script using CodeInterpreterNode
|
|
1073
|
+
const plotNode = new CodeInterpreterNode();
|
|
1074
|
+
plotNode.setParams({
|
|
1075
|
+
code: pythonPlotScript,
|
|
1076
|
+
args: [dataFilePath, plotFilePath], // Pass data file and output plot paths as arguments
|
|
1077
|
+
timeout: 15000, // Increased timeout for plotting
|
|
1078
|
+
requireConfirmation: false, // No confirmation needed for this automated task
|
|
1079
|
+
interpreterPath: process.env.QFLOW_PYTHON_INTERPRETER || 'python' // Allow user to specify Python interpreter path, defaults to 'python'
|
|
1080
|
+
});
|
|
1081
|
+
|
|
1082
|
+
// 5. Chain the nodes
|
|
1083
|
+
writeDataNode.next(plotNode);
|
|
1084
|
+
|
|
1085
|
+
// 6. Run the flow
|
|
1086
|
+
const flow = new AsyncFlow(writeDataNode);
|
|
1087
|
+
try {
|
|
1088
|
+
await flow.runAsync({});
|
|
1089
|
+
console.log(`\nPlotting workflow finished. Check for plot at: ${plotFilePath}`);
|
|
1090
|
+
} catch (error) {
|
|
1091
|
+
console.error('Plotting Workflow Failed:', error);
|
|
1092
|
+
}
|
|
1093
|
+
})();
|
|
1094
|
+
```
|
|
1095
|
+
|
|
1096
|
+
### 18. Embedding Node
|
|
1097
|
+
|
|
1098
|
+
Generates vector embeddings for text using a local Ollama server. Essential for semantic search and RAG.
|
|
1099
|
+
|
|
1100
|
+
**Prerequisites:** Ensure you have [Ollama](https://ollama.ai/) installed and an embedding model pulled (e.g., `ollama pull nomic-embed-text`).
|
|
1101
|
+
|
|
1102
|
+
```javascript
|
|
1103
|
+
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
1104
|
+
import { EmbeddingNode } from '@fractal-solutions/qflow/nodes';
|
|
1105
|
+
|
|
1106
|
+
(async () => {
|
|
1107
|
+
console.log('--- Running EmbeddingNode Example ---');
|
|
1108
|
+
|
|
1109
|
+
const textToEmbed = "Hello, world! This is a test sentence.";
|
|
1110
|
+
const embedNode = new EmbeddingNode();
|
|
1111
|
+
embedNode.setParams({
|
|
1112
|
+
text: textToEmbed,
|
|
1113
|
+
model: 'nomic-embed-text', // Ensure this model is pulled in Ollama
|
|
1114
|
+
baseUrl: 'http://localhost:11434' // Default Ollama URL
|
|
1115
|
+
});
|
|
1116
|
+
|
|
1117
|
+
embedNode.postAsync = async (shared, prepRes, execRes) => {
|
|
1118
|
+
console.log('Embedding Result (first 5 dimensions):', execRes.embedding.slice(0, 5));
|
|
1119
|
+
console.log('Embedding Length:', execRes.embedding.length);
|
|
1120
|
+
return 'default';
|
|
1121
|
+
};
|
|
1122
|
+
|
|
1123
|
+
const flow = new AsyncFlow(embedNode);
|
|
1124
|
+
try {
|
|
1125
|
+
await flow.runAsync({});
|
|
1126
|
+
} catch (error) {
|
|
1127
|
+
console.error('Embedding Flow Failed:', error);
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
console.log('\n--- EmbeddingNode Example Finished ---');
|
|
1131
|
+
})();
|
|
1132
|
+
```
|
|
1133
|
+
|
|
1134
|
+
### 19. Semantic Memory Node
|
|
1135
|
+
|
|
1136
|
+
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.
|
|
1137
|
+
|
|
1138
|
+
**Prerequisites:** Requires [Ollama](https://ollama.ai/) and an embedding model (e.g., `ollama pull nomic-embed-text`).
|
|
1139
|
+
|
|
1140
|
+
```javascript
|
|
1141
|
+
import { AsyncFlow } from '@fractal-solutions/qflow';
|
|
1142
|
+
import { SemanticMemoryNode, DeepSeekLLMNode } from '@fractal-solutions/qflow/nodes';
|
|
1143
|
+
|
|
1144
|
+
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
|
|
1145
|
+
|
|
1146
|
+
(async () => {
|
|
1147
|
+
if (!DEEPSEEK_API_KEY) {
|
|
1148
|
+
console.warn("WARNING: DEEPSEEK_API_KEY is not set. Please set it to run the SemanticMemoryNode RAG example.");
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
console.log('--- Running SemanticMemoryNode RAG Example ---');
|
|
1153
|
+
|
|
1154
|
+
// 1. Store a semantic memory
|
|
1155
|
+
const storeSemanticMemory = new SemanticMemoryNode();
|
|
1156
|
+
storeSemanticMemory.setParams({
|
|
1157
|
+
action: 'store',
|
|
1158
|
+
content: 'The capital of France is Paris. It is known for the Eiffel Tower and its romantic atmosphere.',
|
|
1159
|
+
id: 'france_capital_sem',
|
|
1160
|
+
metadata: { source: 'wikipedia', topic: 'geography' }
|
|
1161
|
+
});
|
|
1162
|
+
await new AsyncFlow(storeSemanticMemory).runAsync({});
|
|
1163
|
+
console.log('Semantic memory stored.');
|
|
1164
|
+
|
|
1165
|
+
// 2. Store another memory for RAG
|
|
1166
|
+
const storeRagSemanticMemory = new SemanticMemoryNode();
|
|
1167
|
+
storeRagSemanticMemory.setParams({
|
|
1168
|
+
action: 'store',
|
|
1169
|
+
content: 'Quantum computing uses quantum-mechanical phenomena like superposition and entanglement to perform computations.',
|
|
1170
|
+
id: 'quantum_comp_intro',
|
|
1171
|
+
metadata: { topic: 'physics' }
|
|
1172
|
+
});
|
|
1173
|
+
await new AsyncFlow(storeRagSemanticMemory).runAsync({});
|
|
1174
|
+
console.log('Another semantic memory stored.');
|
|
1175
|
+
|
|
1176
|
+
// 3. Retrieve relevant semantic memories based on a query
|
|
1177
|
+
const ragRetrieveSemantic = new SemanticMemoryNode();
|
|
1178
|
+
ragRetrieveSemantic.setParams({
|
|
1179
|
+
action: 'retrieve',
|
|
1180
|
+
query: 'city of love',
|
|
1181
|
+
topK: 1
|
|
1182
|
+
});
|
|
1183
|
+
|
|
1184
|
+
// 4. Use an LLM to answer a question based on retrieved memories
|
|
1185
|
+
const ragLLM = new DeepSeekLLMNode();
|
|
1186
|
+
ragLLM.setParams({ apiKey: DEEPSEEK_API_KEY });
|
|
1187
|
+
|
|
1188
|
+
ragRetrieveSemantic.next(ragLLM);
|
|
1189
|
+
|
|
1190
|
+
ragLLM.preparePrompt = (shared) => {
|
|
1191
|
+
const retrievedContent = shared.semanticMemoryResult.map(mem => mem.content).join('\n\n');
|
|
1192
|
+
ragLLM.setParams({
|
|
1193
|
+
prompt: `Based on the following context, answer the question:\n\nContext:\n${retrievedContent}\n\nQuestion: Explain quantum computing in simple terms.`,
|
|
1194
|
+
keyword: 'semantic_rag_llm'
|
|
1195
|
+
});
|
|
1196
|
+
};
|
|
1197
|
+
|
|
1198
|
+
const ragFlow = new AsyncFlow(ragRetrieveSemantic);
|
|
1199
|
+
try {
|
|
1200
|
+
const ragResult = await ragFlow.runAsync({});
|
|
1201
|
+
console.log('\n--- Semantic RAG Example LLM Response ---');
|
|
1202
|
+
console.log(ragResult);
|
|
1203
|
+
} catch (error) {
|
|
1204
|
+
console.error('RAG Flow Failed:', error);
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
console.log('\n--- SemanticMemoryNode RAG Example Finished ---');
|
|
1208
|
+
})();
|
|
1209
|
+
```
|
|
948
1210
|
|
|
949
|
-
* **LLMs (DeepSeek, OpenAI, Gemini, Ollama):** The core of agentic behavior.
|
|
950
|
-
* For agents, use specialized LLM nodes like `AgentDeepSeekLLMNode`, `AgentOpenAILLMNode`, `AgentOllamaLLMNode`.
|
|
951
|
-
* **Agent:** Orchestrating tools and LLM reasoning to achieve complex goals.
|
|
952
|
-
* **Transform:** For dynamic data manipulation and reformatting.
|
|
953
|
-
* **Memory:** For lightweight, keyword-based long-term memory and RAG.
|
|
954
|
-
* **CodeInterpreter:** For executing dynamic code (e.g., Python) within the workflow.
|
|
955
|
-
* **Interactive Agent:** An agent that takes a goal from user input and uses its tools to achieve it.
|
|
956
|
-
* **Shell:** For system-level interaction and execution.
|
|
957
|
-
* **HTTP:** For universal API access.
|
|
958
|
-
* **FileSystem:** For reading and writing local data.
|
|
959
|
-
* **User Input:** For human-in-the-loop control.
|
|
960
|
-
* **Web Search:** Discovering information on the web using either:
|
|
961
|
-
* `DuckDuckGoSearchNode`: API-key-free, using DuckDuckGo's HTML interface.
|
|
962
|
-
* `GoogleSearchNode`: Requires a Google API Key and Custom Search Engine ID for more robust results.
|
|
963
|
-
* **WebScraper:** For targeted web scraping.
|
|
964
|
-
* **DataExtractor:** For targeted data extraction.
|
|
965
|
-
* **GitHub:** Creating and managing issues.
|
|
966
|
-
* **HackerNews:** Fetching top stories and item details.
|
|
967
|
-
* **Stripe:** Creating charges and retrieving account balances.
|
|
968
1211
|
|
|
969
|
-
These examples are a great resource for understanding how to leverage `qflow` to its full potential.
|
|
970
1212
|
|
|
971
1213
|
|
|
972
1214
|
## Error Handling
|
package/package.json
CHANGED