@fractal-solutions/qflow 1.0.19 → 1.0.20

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.
@@ -0,0 +1,115 @@
1
+ import { AsyncNode, AsyncFlow } from '../qflow.js';
2
+ import { UserInputNode } from './user.js';
3
+ import { promises as fs } from 'fs';
4
+ import path from 'path';
5
+ import os from 'os';
6
+ let nodeChildProcess = null;
7
+ if (!process.versions.bun) {
8
+ nodeChildProcess = require('child_process');
9
+ }
10
+ export class CodeInterpreterNode extends AsyncNode {
11
+ async execAsync() {
12
+ const { code, timeout = 30000, args = [], requireConfirmation = true, interpreterPath } = this.params;
13
+ if (!code) {
14
+ throw new Error('CodeInterpreterNode requires a `code` parameter.');
15
+ }
16
+ const tempDir = os.tmpdir();
17
+ const tempFileName = `qflow_python_code_${Date.now()}_${Math.random().toString(36).substring(2, 8)}.py`;
18
+ const tempFilePath = path.join(tempDir, tempFileName);
19
+ const interpreterCommand = interpreterPath || 'python';
20
+ console.log(`[CodeInterpreter] Proposed execution: ${interpreterCommand} ${tempFilePath}`);
21
+ console.log(`[CodeInterpreter] Code to execute:\n${code}`);
22
+ // --- User Confirmation ---
23
+ // --- User Confirmation ---
24
+ if (requireConfirmation) {
25
+ const confirmNode = new UserInputNode();
26
+ confirmNode.setParams({
27
+ prompt: `The agent wants to execute the following Python code:\n${code}\nDo you approve? (yes/no): `
28
+ });
29
+ const confirmFlow = new AsyncFlow(confirmNode);
30
+ const confirmation = await confirmFlow.runAsync({});
31
+ if (confirmation.toLowerCase() !== 'yes') {
32
+ throw new Error('Code execution denied by user.');
33
+ }
34
+ }
35
+ // --- End User Confirmation ---
36
+ // --- End User Confirmation ---
37
+ try {
38
+ await fs.writeFile(tempFilePath, code, 'utf-8');
39
+ let stdout = '';
40
+ let stderr = '';
41
+ let exitCode = 1; // Default to failure
42
+ const abortController = new AbortController();
43
+ const timeoutId = setTimeout(() => abortController.abort(), timeout);
44
+ try {
45
+ if (process.versions.bun) {
46
+ const childProcess = Bun.spawn([interpreterCommand, tempFilePath, ...args], {
47
+ stdin: 'inherit',
48
+ stdout: 'pipe',
49
+ stderr: 'pipe',
50
+ signal: abortController.signal,
51
+ });
52
+ // Await stdout and stderr first
53
+ stdout = await new Response(childProcess.stdout).text();
54
+ stderr = await new Response(childProcess.stderr).text();
55
+ const bunExitResult = await childProcess.exited;
56
+ if (abortController.signal.aborted) {
57
+ stderr += `\nExecution timed out after ${timeout}ms.`;
58
+ exitCode = 1; // Indicate failure due to timeout
59
+ }
60
+ else {
61
+ exitCode = Number(bunExitResult !== null ? bunExitResult : 1); // Ensure exitCode is a number
62
+ }
63
+ }
64
+ else if (nodeChildProcess) {
65
+ const childProcess = nodeChildProcess.spawn(interpreterCommand, [tempFilePath, ...args], {
66
+ stdio: ['inherit', 'pipe', 'pipe'],
67
+ signal: abortController.signal,
68
+ });
69
+ const stdoutChunks = [];
70
+ const stderrChunks = [];
71
+ childProcess.stdout.on('data', (data) => stdoutChunks.push(data));
72
+ childProcess.stderr.on('data', (data) => stderrChunks.push(data));
73
+ const { code: exitCodeFromClose, signal: signalFromClose } = await new Promise((resolve, reject) => {
74
+ childProcess.on('close', (code, signal) => resolve({ code, signal }));
75
+ childProcess.on('error', (err) => reject(err));
76
+ });
77
+ stdout = Buffer.concat(stdoutChunks).toString('utf-8');
78
+ stderr = Buffer.concat(stderrChunks).toString('utf-8');
79
+ exitCode = exitCodeFromClose !== null ? exitCodeFromClose : (signalFromClose ? 1 : 1); // If signal, treat as failure
80
+ }
81
+ else {
82
+ throw new Error('Unsupported runtime environment.');
83
+ }
84
+ }
85
+ catch (error) {
86
+ if (error.name === "AbortError" || error.code === "ABORT_ERR") { // Handle AbortError for both Bun and Node
87
+ stderr += `
88
+ Execution timed out after ${timeout}ms.`;
89
+ exitCode = 1; // Indicate failure due to timeout
90
+ }
91
+ else if (error.code === 'ENOENT') {
92
+ stderr += `\nError: Command '${interpreterCommand}' not found. Please ensure it is installed and in your system's PATH.`;
93
+ exitCode = 1;
94
+ }
95
+ else {
96
+ stderr += `
97
+ Error during execution: ${error.message}`;
98
+ exitCode = 1;
99
+ }
100
+ }
101
+ finally {
102
+ clearTimeout(timeoutId);
103
+ }
104
+ return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode };
105
+ }
106
+ finally {
107
+ // Clean up temporary file
108
+ await fs.unlink(tempFilePath).catch(e => console.error(`Failed to delete temp file ${tempFilePath}:`, e));
109
+ }
110
+ }
111
+ async postAsync(shared, prepRes, execRes) {
112
+ shared.codeInterpreterResult = execRes;
113
+ return 'default';
114
+ }
115
+ }
@@ -0,0 +1,5 @@
1
+ export class DataExtractorNode extends AsyncNode {
2
+ execAsync(): Promise<any>;
3
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
4
+ }
5
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,80 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ import * as cheerio from 'cheerio';
3
+ export class DataExtractorNode extends AsyncNode {
4
+ async execAsync() {
5
+ const { input, type, selector, jsonPath, regex, group } = this.params;
6
+ if (!input) {
7
+ throw new Error('DataExtractorNode requires an `input` string.');
8
+ }
9
+ if (!type || !['html', 'json', 'text'].includes(type)) {
10
+ throw new Error('DataExtractorNode requires a valid `type` (html, json, text).');
11
+ }
12
+ let result;
13
+ switch (type) {
14
+ case 'html':
15
+ if (!selector) {
16
+ throw new Error('HTML extraction requires a `selector`.');
17
+ }
18
+ console.log(`[DataExtractor] Extracting HTML with selector: ${selector}`);
19
+ const $ = cheerio.load(input);
20
+ result = $(selector).map((i, el) => $(el).text()).get();
21
+ break;
22
+ case 'json':
23
+ if (!jsonPath) {
24
+ throw new Error('JSON extraction requires a `jsonPath`.');
25
+ }
26
+ console.log(`[DataExtractor] Extracting JSON with path: ${jsonPath}`);
27
+ try {
28
+ const data = JSON.parse(input);
29
+ // Simple JSON path implementation (dot notation and array indexing)
30
+ result = jsonPath.split('.').reduce((acc, part) => {
31
+ if (acc === undefined || acc === null)
32
+ return undefined;
33
+ const arrayMatch = part.match(/(.*)\[(\d+)\]$/);
34
+ if (arrayMatch) {
35
+ const prop = arrayMatch[1];
36
+ const index = parseInt(arrayMatch[2], 10);
37
+ return acc[prop] ? acc[prop][index] : undefined;
38
+ }
39
+ else {
40
+ return acc[part];
41
+ }
42
+ }, data);
43
+ }
44
+ catch (e) {
45
+ throw new Error(`Invalid JSON input or jsonPath: ${e.message}`);
46
+ }
47
+ break;
48
+ case 'text':
49
+ if (!regex) {
50
+ throw new Error('Text extraction requires a `regex`.');
51
+ }
52
+ console.log(`[DataExtractor] Extracting text with regex: ${regex}`);
53
+ const re = new RegExp(regex, 'g');
54
+ const matches = [];
55
+ let match;
56
+ while ((match = re.exec(input)) !== null) {
57
+ if (group !== undefined && match.length > group) {
58
+ matches.push(match[group]);
59
+ }
60
+ else if (group === undefined) {
61
+ matches.push(match[0]);
62
+ }
63
+ else {
64
+ // Group not found, push undefined or skip
65
+ matches.push(undefined);
66
+ }
67
+ }
68
+ result = matches;
69
+ break;
70
+ default:
71
+ throw new Error('Unsupported extraction type.');
72
+ }
73
+ console.log(`[DataExtractor] Extraction complete. Result: ${JSON.stringify(result).substring(0, 100)}...`);
74
+ return result;
75
+ }
76
+ async postAsync(shared, prepRes, execRes) {
77
+ shared.extractedData = execRes;
78
+ return 'default';
79
+ }
80
+ }
@@ -0,0 +1,7 @@
1
+ export class EmbeddingNode extends AsyncNode {
2
+ execAsync(): Promise<{
3
+ embedding: any;
4
+ }>;
5
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
6
+ }
7
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,44 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ export class EmbeddingNode extends AsyncNode {
3
+ constructor(maxRetries = 3, wait = 2) {
4
+ super(maxRetries, wait);
5
+ }
6
+ async execAsync() {
7
+ const { text, model = 'nomic-embed-text', baseUrl = 'http://localhost:11434' } = this.params;
8
+ if (!text) {
9
+ throw new Error('EmbeddingNode requires a `text` parameter to embed.');
10
+ }
11
+ const url = `${baseUrl}/api/embeddings`;
12
+ const payload = {
13
+ model: model,
14
+ prompt: text,
15
+ };
16
+ console.log(`[EmbeddingNode] Generating embedding for text (model: ${model}) at ${baseUrl}...`);
17
+ try {
18
+ const response = await fetch(url, {
19
+ method: 'POST',
20
+ headers: {
21
+ 'Content-Type': 'application/json',
22
+ },
23
+ body: JSON.stringify(payload),
24
+ });
25
+ if (!response.ok) {
26
+ const errorText = await response.text();
27
+ throw new Error(`Ollama embedding API error: ${response.status} ${response.statusText} - ${errorText}`);
28
+ }
29
+ const data = await response.json();
30
+ if (!data.embedding) {
31
+ throw new Error('Ollama embedding API response missing embedding.');
32
+ }
33
+ console.log(`[EmbeddingNode] Embedding generated successfully.`);
34
+ return { embedding: data.embedding };
35
+ }
36
+ catch (error) {
37
+ throw new Error(`Failed to generate embedding: ${error.message}`);
38
+ }
39
+ }
40
+ async postAsync(shared, prepRes, execRes) {
41
+ shared.embeddingResult = execRes.embedding; // Store the embedding array directly
42
+ return 'default';
43
+ }
44
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Reads a file from the file system.
3
+ * @param {object} params - The parameters for the node.
4
+ * @param {string} params.filePath - The path to the file to read.
5
+ * @returns {Promise<string>} A promise that resolves to the content of the file.
6
+ */
7
+ export class ReadFileNode extends AsyncNode {
8
+ execAsync(): Promise<string>;
9
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
10
+ }
11
+ /**
12
+ * Writes a file to the file system.
13
+ * @param {object} params - The parameters for the node.
14
+ * @param {string} params.filePath - The path to the file to write.
15
+ * @param {string} params.content - The content to write to the file.
16
+ * @returns {Promise<void>} A promise that resolves when the file has been written.
17
+ */
18
+ export class WriteFileNode extends AsyncNode {
19
+ execAsync(): Promise<string>;
20
+ }
21
+ /**
22
+ * Appends content to a file.
23
+ * @param {object} params - The parameters for the node.
24
+ * @param {string} params.filePath - The path to the file to append to.
25
+ * @param {string} params.content - The content to append to the file.
26
+ * @returns {Promise<void>} A promise that resolves when the content has been appended.
27
+ */
28
+ export class AppendFileNode extends AsyncNode {
29
+ execAsync(): Promise<string>;
30
+ }
31
+ /**
32
+ * Lists the files in a directory.
33
+ * @param {object} params - The parameters for the node.
34
+ * @param {string} params.directoryPath - The path to the directory to list.
35
+ * @returns {Promise<string[]>} A promise that resolves to an array of file names.
36
+ */
37
+ export class ListDirectoryNode extends AsyncNode {
38
+ execAsync(): Promise<string[]>;
39
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
40
+ }
41
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,87 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ import { promises as fs } from 'fs';
3
+ import path from 'path';
4
+ /**
5
+ * Reads a file from the file system.
6
+ * @param {object} params - The parameters for the node.
7
+ * @param {string} params.filePath - The path to the file to read.
8
+ * @returns {Promise<string>} A promise that resolves to the content of the file.
9
+ */
10
+ export class ReadFileNode extends AsyncNode {
11
+ async execAsync() {
12
+ const { filePath } = this.params;
13
+ if (!filePath) {
14
+ throw new Error('Missing required parameter: filePath');
15
+ }
16
+ console.log(`[FileSystem] Reading file: ${filePath}`);
17
+ const content = await fs.readFile(filePath, 'utf-8');
18
+ console.log(`[FileSystem] Successfully read file: ${filePath}`);
19
+ return content;
20
+ }
21
+ async postAsync(shared, prepRes, execRes) {
22
+ shared.fileContent = execRes;
23
+ return 'default';
24
+ }
25
+ }
26
+ /**
27
+ * Writes a file to the file system.
28
+ * @param {object} params - The parameters for the node.
29
+ * @param {string} params.filePath - The path to the file to write.
30
+ * @param {string} params.content - The content to write to the file.
31
+ * @returns {Promise<void>} A promise that resolves when the file has been written.
32
+ */
33
+ export class WriteFileNode extends AsyncNode {
34
+ async execAsync() {
35
+ const { filePath, content } = this.params;
36
+ if (!filePath || content === undefined) {
37
+ throw new Error('Missing required parameters: filePath, content');
38
+ }
39
+ console.log(`[FileSystem] Writing to file: ${filePath}`);
40
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
41
+ await fs.writeFile(filePath, content, 'utf-8');
42
+ console.log(`[FileSystem] Successfully wrote to file: ${filePath}`);
43
+ return 'default';
44
+ }
45
+ }
46
+ /**
47
+ * Appends content to a file.
48
+ * @param {object} params - The parameters for the node.
49
+ * @param {string} params.filePath - The path to the file to append to.
50
+ * @param {string} params.content - The content to append to the file.
51
+ * @returns {Promise<void>} A promise that resolves when the content has been appended.
52
+ */
53
+ export class AppendFileNode extends AsyncNode {
54
+ async execAsync() {
55
+ const { filePath, content } = this.params;
56
+ if (!filePath || content === undefined) {
57
+ throw new Error('Missing required parameters: filePath, content');
58
+ }
59
+ console.log(`[FileSystem] Appending to file: ${filePath}`);
60
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
61
+ await fs.appendFile(filePath, content, 'utf-8');
62
+ console.log(`[FileSystem] Successfully appended to file: ${filePath}`);
63
+ return 'default';
64
+ }
65
+ }
66
+ /**
67
+ * Lists the files in a directory.
68
+ * @param {object} params - The parameters for the node.
69
+ * @param {string} params.directoryPath - The path to the directory to list.
70
+ * @returns {Promise<string[]>} A promise that resolves to an array of file names.
71
+ */
72
+ export class ListDirectoryNode extends AsyncNode {
73
+ async execAsync() {
74
+ const { directoryPath } = this.params;
75
+ if (!directoryPath) {
76
+ throw new Error('Missing required parameter: directoryPath');
77
+ }
78
+ console.log(`[FileSystem] Listing directory: ${directoryPath}`);
79
+ const files = await fs.readdir(directoryPath);
80
+ console.log(`[FileSystem] Successfully listed directory: ${directoryPath}`);
81
+ return files;
82
+ }
83
+ async postAsync(shared, prepRes, execRes) {
84
+ shared.directoryFiles = execRes;
85
+ return 'default';
86
+ }
87
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * A flexible node for making generic HTTP requests to any REST API.
3
+ * @param {object} params - The parameters for the node.
4
+ * @param {string} params.url - The full URL of the API endpoint.
5
+ * @param {string} [params.method='GET'] - The HTTP method (e.g., 'POST', 'PUT', 'DELETE').
6
+ * @param {object} [params.headers] - Custom headers for the request.
7
+ * @param {*} [params.body] - The request payload. If it's an object, it will be stringified as JSON.
8
+ * @param {object} [params.auth] - Authentication configuration.
9
+ * @param {'bearer'|'basic'} [params.auth.type] - The type of authentication.
10
+ * @param {string} [params.auth.token] - The bearer token.
11
+ * @param {string} [params.auth.username] - The username for basic auth.
12
+ * @param {string} [params.auth.password] - The password for basic auth.
13
+ * @returns {Promise<object>} A promise that resolves to a structured object containing the status, headers, and body of the response.
14
+ */
15
+ export class HttpRequestNode extends AsyncNode {
16
+ execAsync(): Promise<{
17
+ status: number;
18
+ headers: {
19
+ [k: string]: string;
20
+ };
21
+ body: any;
22
+ }>;
23
+ parseResponseBody(response: any): Promise<any>;
24
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
25
+ }
26
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,66 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ /**
3
+ * A flexible node for making generic HTTP requests to any REST API.
4
+ * @param {object} params - The parameters for the node.
5
+ * @param {string} params.url - The full URL of the API endpoint.
6
+ * @param {string} [params.method='GET'] - The HTTP method (e.g., 'POST', 'PUT', 'DELETE').
7
+ * @param {object} [params.headers] - Custom headers for the request.
8
+ * @param {*} [params.body] - The request payload. If it's an object, it will be stringified as JSON.
9
+ * @param {object} [params.auth] - Authentication configuration.
10
+ * @param {'bearer'|'basic'} [params.auth.type] - The type of authentication.
11
+ * @param {string} [params.auth.token] - The bearer token.
12
+ * @param {string} [params.auth.username] - The username for basic auth.
13
+ * @param {string} [params.auth.password] - The password for basic auth.
14
+ * @returns {Promise<object>} A promise that resolves to a structured object containing the status, headers, and body of the response.
15
+ */
16
+ export class HttpRequestNode extends AsyncNode {
17
+ async execAsync() {
18
+ const { url, method = 'GET', headers = {}, body, auth } = this.params;
19
+ if (!url) {
20
+ throw new Error('HttpRequestNode requires a `url` parameter.');
21
+ }
22
+ const fetchOptions = {
23
+ method,
24
+ headers: { ...headers }, // Create a mutable copy
25
+ };
26
+ // Handle Authentication
27
+ if (auth) {
28
+ if (auth.type === 'bearer' && auth.token) {
29
+ fetchOptions.headers['Authorization'] = `Bearer ${auth.token}`;
30
+ }
31
+ else if (auth.type === 'basic' && auth.username && auth.password) {
32
+ const credentials = btoa(`${auth.username}:${auth.password}`);
33
+ fetchOptions.headers['Authorization'] = `Basic ${credentials}`;
34
+ }
35
+ }
36
+ // Handle Body
37
+ if (body) {
38
+ if (typeof body === 'object' && !fetchOptions.headers['Content-Type']) {
39
+ fetchOptions.headers['Content-Type'] = 'application/json';
40
+ fetchOptions.body = JSON.stringify(body);
41
+ }
42
+ else {
43
+ fetchOptions.body = body;
44
+ }
45
+ }
46
+ console.log(`[HTTP] ${method} ${url}`);
47
+ const response = await fetch(url, fetchOptions);
48
+ const responseBody = await this.parseResponseBody(response);
49
+ return {
50
+ status: response.status,
51
+ headers: Object.fromEntries(response.headers.entries()),
52
+ body: responseBody,
53
+ };
54
+ }
55
+ async parseResponseBody(response) {
56
+ const contentType = response.headers.get('content-type') || '';
57
+ if (contentType.includes('application/json')) {
58
+ return await response.json();
59
+ }
60
+ return await response.text();
61
+ }
62
+ async postAsync(shared, prepRes, execRes) {
63
+ shared.httpResult = execRes;
64
+ return 'default';
65
+ }
66
+ }
@@ -1,5 +1,20 @@
1
1
  export * from "./llm.js";
2
+ export * from "./agent_llm.js";
3
+ export * from "./data_extractor.js";
4
+ export * from "./code_interpreter.js";
2
5
  export * from "./hackernews.js";
3
6
  export * from "./github.js";
4
7
  export * from "./stripe.js";
5
8
  export * from "./webscraper.js";
9
+ export * from "./shell.js";
10
+ export * from "./filesystem.js";
11
+ export * from "./user.js";
12
+ export * from "./http.js";
13
+ export * from "./search.js";
14
+ export * from "./summarize.js";
15
+ export * from "./memory.js";
16
+ export * from "./transform.js";
17
+ export * from "./embedding.js";
18
+ export * from "./semantic_memory.js";
19
+ export * from "./semantic_memory.js";
20
+ export * from "../agent/agent.js";
@@ -1,5 +1,20 @@
1
1
  export * from './llm.js';
2
+ export * from './agent_llm.js';
3
+ export * from './data_extractor.js';
4
+ export * from './code_interpreter.js';
2
5
  export * from './hackernews.js';
3
6
  export * from './github.js';
4
7
  export * from './stripe.js';
5
8
  export * from './webscraper.js';
9
+ export * from './shell.js';
10
+ export * from './filesystem.js';
11
+ export * from './user.js';
12
+ export * from './http.js';
13
+ export * from './search.js';
14
+ export * from './summarize.js';
15
+ export * from './memory.js';
16
+ export * from './transform.js';
17
+ export * from './embedding.js';
18
+ export * from './semantic_memory.js';
19
+ export * from './semantic_memory.js';
20
+ export * from '../agent/agent.js';
@@ -1,6 +1,6 @@
1
1
  export class DeepSeekLLMNode extends AsyncNode {
2
- preparePrompt(): void;
3
- execAsync(): Promise<any>;
2
+ preparePrompt(shared: any): void;
3
+ execAsync(prepRes: any, shared: any): Promise<any>;
4
4
  }
5
5
  export class OpenAILLMNode extends AsyncNode {
6
6
  execAsync(): Promise<any>;
@@ -8,4 +8,8 @@ export class OpenAILLMNode extends AsyncNode {
8
8
  export class GeminiLLMNode extends AsyncNode {
9
9
  execAsync(): Promise<any>;
10
10
  }
11
+ export class OllamaLLMNode extends AsyncNode {
12
+ preparePrompt(shared: any): void;
13
+ execAsync(prepRes: any, shared: any): Promise<any>;
14
+ }
11
15
  import { AsyncNode } from '../qflow.js';
package/dist/nodes/llm.js CHANGED
@@ -5,11 +5,11 @@ export class DeepSeekLLMNode extends AsyncNode {
5
5
  super(maxRetries, wait);
6
6
  }
7
7
  // This will be implemented by subclasses
8
- preparePrompt() {
8
+ preparePrompt(shared) {
9
9
  throw new Error("preparePrompt must be implemented by subclasses");
10
10
  }
11
- async execAsync() {
12
- this.preparePrompt(); // Set the prompt
11
+ async execAsync(prepRes, shared) {
12
+ this.preparePrompt(shared); // Set the prompt, passing shared state
13
13
  const { prompt, keyword, apiKey } = this.params;
14
14
  if (!prompt) {
15
15
  throw new Error("Prompt was not generated.");
@@ -91,7 +91,7 @@ export class GeminiLLMNode extends AsyncNode {
91
91
  if (!apiKey) {
92
92
  throw new Error('Google Gemini API Key is required.');
93
93
  }
94
- console.log(`GeminiLLMNode: Sending prompt to Gemini: \"${prompt.substring(0, 50)}\"...`);
94
+ console.log(`GeminiLLMNode: Sending prompt to Gemini: "${prompt.substring(0, 50)}"...`);
95
95
  try {
96
96
  const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${apiKey}`, {
97
97
  method: 'POST',
@@ -108,7 +108,7 @@ export class GeminiLLMNode extends AsyncNode {
108
108
  }
109
109
  const data = await response.json();
110
110
  const llmResponse = data.candidates[0].content.parts[0].text.trim();
111
- console.log(`GeminiLLMNode: Received response: \"${llmResponse.substring(0, 50)}\"...`);
111
+ console.log(`GeminiLLMNode: Received response: "${llmResponse.substring(0, 50)}"...`);
112
112
  return llmResponse; // Return the LLM's response
113
113
  }
114
114
  catch (error) {
@@ -117,3 +117,45 @@ export class GeminiLLMNode extends AsyncNode {
117
117
  }
118
118
  }
119
119
  }
120
+ export class OllamaLLMNode extends AsyncNode {
121
+ constructor(maxRetries = 3, wait = 2) {
122
+ super(maxRetries, wait);
123
+ }
124
+ preparePrompt(shared) {
125
+ // Default implementation, can be overridden by subclasses
126
+ // For direct LLM calls, prompt is usually set directly via setParams
127
+ }
128
+ async execAsync(prepRes, shared) {
129
+ this.preparePrompt(shared); // Allow subclasses to prepare prompt
130
+ const { prompt, model = 'llama2', baseUrl = 'http://localhost:11434' } = this.params;
131
+ if (!prompt) {
132
+ throw new Error('Prompt is required for OllamaLLMNode.');
133
+ }
134
+ console.log(`[Ollama] Sending prompt to ${model} at ${baseUrl}: "${prompt.substring(0, 50)}"...`);
135
+ try {
136
+ const response = await fetch(`${baseUrl}/api/generate`, {
137
+ method: 'POST',
138
+ headers: {
139
+ 'Content-Type': 'application/json',
140
+ },
141
+ body: JSON.stringify({
142
+ model: model,
143
+ prompt: prompt,
144
+ stream: false,
145
+ }),
146
+ });
147
+ if (!response.ok) {
148
+ const errorData = await response.json();
149
+ throw new Error(`Ollama API error: ${response.status} - ${errorData.error}`);
150
+ }
151
+ const data = await response.json();
152
+ const llmResponse = data.response.trim();
153
+ console.log(`[Ollama] Received response from ${model}: "${llmResponse.substring(0, 50)}"...`);
154
+ return llmResponse;
155
+ }
156
+ catch (error) {
157
+ console.error('OllamaLLMNode: Error during API call:', error);
158
+ throw error;
159
+ }
160
+ }
161
+ }
@@ -0,0 +1,12 @@
1
+ export class MemoryNode extends AsyncNode {
2
+ execAsync(): Promise<{
3
+ status: string;
4
+ id: any;
5
+ filePath: string;
6
+ } | {
7
+ id: string;
8
+ content: string;
9
+ }[]>;
10
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
11
+ }
12
+ import { AsyncNode } from '../qflow.js';