@fractal-solutions/qflow 1.0.25 → 1.0.27

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 CHANGED
@@ -125,9 +125,10 @@ A helper class used in conjunction with `Node.transition()` to define conditiona
125
125
 
126
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
127
 
128
- * [**LLMs (DeepSeek, OpenAI, Gemini, Ollama, Hugging Face):**](#7-inter-node-communication-with-shared-state-advanced-example) The core of agentic behavior.
128
+ * [**LLMs (DeepSeek, OpenAI, Gemini, Ollama, Hugging Face, OpenRouter):**](#7-inter-node-communication-with-shared-state-advanced-example) The core of agentic behavior.
129
129
  * For agents, use specialized LLM nodes like `AgentDeepSeekLLMNode`, `AgentOpenAILLMNode`, `AgentOllamaLLMNode`.
130
130
  * [**Hugging Face Models:**](https://github.com/fractal-solutions/qflow/blob/main/examples/huggingface_chat_llm.js) Leverage Hugging Face's free Inference API (OpenAI-compatible endpoint) by using `HuggingFaceLLMNode` and [`AgentHuggingFaceLLMNode`](https://github.com/fractal-solutions/qflow/blob/main/examples/agent_huggingface_llm_test.js) with `baseUrl: 'https://router.huggingface.co/v1'` and your Hugging Face API token. Ensure you specify the correct `model` ID (e.g., `openai/gpt-oss-20b:novita`).
131
+ * [**OpenRouter Models:**](https://github.com/fractal-solutions/qflow/blob/main/examples/agent_openrouter_llm_test.js) Utilize OpenRouter's unified API by using `OpenRouterLLMNode` and [`AgentOpenRouterLLMNode`](https://github.com/fractal-solutions/qflow/blob/main/examples/agent_openrouter_llm_test.js) with your OpenRouter API key and desired model (e.g., `openai/gpt-4o`).
131
132
  * [**Agent:**](#12-interactive-agent-example) Orchestrating tools and LLM reasoning to achieve complex goals.
132
133
  * [**Embedding:**](#18-embedding-node) For generating vector embeddings from text using Ollama.
133
134
  * [**Semantic Memory:**](#19-semantic-memory-node) For storing and retrieving memories based on semantic similarity (RAG) using Ollama. A slightly more advanced RAG is implemented as [RAG with user query input](https://github.com/fractal-solutions/qflow/blob/main/examples/rag_user_input.js).
@@ -1406,6 +1407,15 @@ The `AgentNode` can be equipped with a variety of tools to perform a wide range
1406
1407
  * `model`: The Ollama embedding model name to use.
1407
1408
  * `baseUrl`: The base URL of the Ollama API.
1408
1409
 
1410
+ ### Flow Control
1411
+
1412
+ * **sub_flow**: Executes a sub-flow.
1413
+ * `flow`: The flow to execute.
1414
+ * `shared`: The shared object to pass to the sub-flow.
1415
+ * **iterator**: Iterates over a list of items and executes a sub-flow for each item.
1416
+ * `items`: The list of items to iterate over.
1417
+ * `flow`: The flow to execute for each item.
1418
+
1409
1419
  ### LLM Reasoning
1410
1420
 
1411
1421
  * **huggingface_llm_reasoning**: A powerful language model for general reasoning, problem-solving, and generating text, using Hugging Face's OpenAI-compatible router.
@@ -1,10 +1,12 @@
1
1
  export class AgentNode extends AsyncNode {
2
- constructor(llmNode: any, availableTools: any, summarizeLLM: any);
2
+ constructor(llmNode: any, availableTools: any, summarizeLLM: any, flowRegistry?: {}, requireFinishConfirmation?: boolean);
3
3
  llmNode: any;
4
4
  availableTools: any;
5
5
  summarizeLLM: any;
6
+ flowRegistry: {};
6
7
  conversationHistory: any[];
7
8
  maxSteps: number;
9
+ requireFinishConfirmation: boolean;
8
10
  execAsync(): Promise<any>;
9
11
  getSystemPrompt(): string;
10
12
  getLLMAction(): Promise<any>;
@@ -1,9 +1,10 @@
1
1
  import { AsyncNode, AsyncFlow, Flow } from '../qflow.js';
2
+ import { UserInputNode } from '../nodes';
2
3
  import { getToolDefinitions } from './tools.js';
3
4
  import { SummarizeNode } from '../nodes/summarize.js';
4
5
  import { logger } from './logger.js';
5
6
  export class AgentNode extends AsyncNode {
6
- constructor(llmNode, availableTools, summarizeLLM) {
7
+ constructor(llmNode, availableTools, summarizeLLM, flowRegistry = {}, requireFinishConfirmation = true) {
7
8
  super();
8
9
  if (!llmNode) {
9
10
  throw new Error("AgentNode requires an LLMNode instance for reasoning.");
@@ -11,8 +12,10 @@ export class AgentNode extends AsyncNode {
11
12
  this.llmNode = llmNode;
12
13
  this.availableTools = availableTools;
13
14
  this.summarizeLLM = summarizeLLM;
15
+ this.flowRegistry = flowRegistry;
14
16
  this.conversationHistory = [];
15
17
  this.maxSteps = 20;
18
+ this.requireFinishConfirmation = requireFinishConfirmation;
16
19
  }
17
20
  async execAsync() {
18
21
  const { goal } = this.params;
@@ -52,6 +55,19 @@ export class AgentNode extends AsyncNode {
52
55
  this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought, tool: toolCall }) });
53
56
  if (toolCall.tool === "finish") {
54
57
  finalOutput = toolCall.parameters.output;
58
+ if (this.requireFinishConfirmation) {
59
+ const confirmNode = new UserInputNode();
60
+ confirmNode.setParams({
61
+ prompt: `Agent proposes to finish with output: "${finalOutput}". Do you approve? (yes/no): `
62
+ });
63
+ const confirmFlow = new AsyncFlow(confirmNode);
64
+ const confirmation = await confirmFlow.runAsync({});
65
+ if (confirmation.toLowerCase() !== 'yes') {
66
+ logger.info("Agent finish denied by user. Continuing...");
67
+ this.conversationHistory.push({ role: "user", content: "User denied finish. Continue working." });
68
+ continue; // Continue the loop
69
+ }
70
+ }
55
71
  logger.final(finalOutput);
56
72
  break;
57
73
  }
@@ -65,6 +81,14 @@ export class AgentNode extends AsyncNode {
65
81
  let toolOutput;
66
82
  try {
67
83
  logger.toolCall(toolCall.tool, toolCall.parameters);
84
+ // If the tool is a sub-flow or iterator, look up the flow in the registry
85
+ if (toolCall.tool === 'sub_flow' || toolCall.tool === 'iterator') {
86
+ const flowName = toolCall.parameters.flow;
87
+ if (!this.flowRegistry[flowName]) {
88
+ throw new Error(`Flow '${flowName}' not found in registry.`);
89
+ }
90
+ toolCall.parameters.flow = this.flowRegistry[flowName];
91
+ }
68
92
  toolInstance.setParams(toolCall.parameters);
69
93
  const ToolFlowClass = toolInstance instanceof AsyncNode ? AsyncFlow : Flow;
70
94
  const toolFlow = new ToolFlowClass(toolInstance);
@@ -103,7 +127,8 @@ export class AgentNode extends AsyncNode {
103
127
  const params = JSON.stringify(tool.parameters);
104
128
  return `### Tool: ${tool.name}\nDescription: ${tool.description}\nParameters: ${params}`;
105
129
  }).join('\n\n');
106
- return `You are an autonomous agent designed to achieve a goal by selecting and using tools. Your responses must be in a specific JSON format.\n\nAvailable Tools:\n${toolDescriptions}\n\nYour response must be a single JSON object with two keys: 'thought' and 'tool'.\n'thought': A string explaining your reasoning process and plan.\n'tool': An object with two keys: 'tool' (the name of the tool to call) and 'parameters' (an object containing the parameters for that tool).\n\nExample response:\n{\n "thought": "I need to find information about X, so I will use the duckduckgo_search tool.",\n "tool": {\n "tool": "duckduckgo_search",\n "parameters": {\n "query": "X information"\n }\n }\n}\n\nWhen you have achieved the goal or cannot proceed, use the 'finish' tool.\nExample finish response:\n{\n "thought": "I have successfully achieved the goal.",\n "tool": {\n "tool": "finish",\n "parameters": {\n "output": "The final result of the goal."\n }\n}\n\nBegin!`;
130
+ const flowRegistryDescription = Object.keys(this.flowRegistry).length > 0 ? `\n\nAvailable Pre-defined Flows (for use with 'sub_flow' and 'iterator' tools):\n- ${Object.keys(this.flowRegistry).join('\n- ')}` : "";
131
+ return `You are an autonomous agent designed to achieve a goal by selecting and using tools. Your responses must be in a specific JSON format.\n\nAvailable Tools:\n${toolDescriptions}${flowRegistryDescription}\n\nYour response must be a single JSON object with two keys: 'thought' and 'tool'.\n'thought': A string explaining your reasoning process and plan.\n'tool': An object with two keys: 'tool' (the name of the tool to call) and 'parameters' (an object containing the parameters for that tool).\n\nWhen using 'sub_flow' or 'iterator', the 'flow' parameter must be a string matching one of the pre-defined flow names.\n\nExample response:\n{\n "thought": "I need to find information about X, so I will use the duckduckgo_search tool.",\n "tool": {\n "tool": "duckduckgo_search",\n "parameters": {\n "query": "X information"\n }\n }\n}\n\nWhen you have achieved the goal or cannot proceed, use the 'finish' tool.\nExample finish response:\n{\n "thought": "I have successfully achieved the goal.",\n "tool": {\n "tool": "finish",\n "parameters": {\n "output": "The final result of the goal."\n }\n}\n\nBegin!`;
107
132
  }
108
133
  async getLLMAction() {
109
134
  this.llmNode.setParams({ prompt: JSON.stringify(this.conversationHistory) });
@@ -117,12 +142,19 @@ export class AgentNode extends AsyncNode {
117
142
  let rawData = llmResponse;
118
143
  if (typeof llmResponse === 'string') {
119
144
  try {
120
- rawData = JSON.parse(llmResponse);
145
+ parsed = JSON.parse(llmResponse);
146
+ if (parsed.thought && parsed.tool && parsed.tool.tool && parsed.tool.parameters !== undefined) {
147
+ return parsed;
148
+ }
149
+ throw new Error("Missing required keys in LLM response (thought, tool.tool, tool.parameters).");
121
150
  }
122
151
  catch (e) {
152
+ // If it's not JSON, assume it's a direct text response from LLM
153
+ // This path should ideally not be taken if LLM is tool-calling capable
123
154
  return { thought: "Direct LLM response", tool: { tool: "finish", parameters: { output: llmResponse } } };
124
155
  }
125
156
  }
157
+ // Prioritize tool_calls if present (OpenAI function calling format)
126
158
  if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0].message) {
127
159
  const message = rawData.choices[0].message;
128
160
  if (message.tool_calls && message.tool_calls.length > 0) {
@@ -135,6 +167,7 @@ export class AgentNode extends AsyncNode {
135
167
  return { thought, tool: toolCall };
136
168
  }
137
169
  else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
170
+ // If no tool_calls, but content is JSON (for thought/tool/finish)
138
171
  try {
139
172
  parsed = JSON.parse(message.content);
140
173
  if (parsed.thought && parsed.tool && parsed.tool.tool && parsed.tool.parameters !== undefined) {
@@ -40,6 +40,9 @@ export function getToolDefinitions(): ({
40
40
  text?: undefined;
41
41
  input?: undefined;
42
42
  transformFunction?: undefined;
43
+ apiKey?: undefined;
44
+ siteUrl?: undefined;
45
+ siteTitle?: undefined;
43
46
  type?: undefined;
44
47
  selector?: undefined;
45
48
  jsonPath?: undefined;
@@ -49,7 +52,6 @@ export function getToolDefinitions(): ({
49
52
  timeout?: undefined;
50
53
  args?: undefined;
51
54
  requireConfirmation?: undefined;
52
- apiKey?: undefined;
53
55
  cseId?: undefined;
54
56
  command?: undefined;
55
57
  filePath?: undefined;
@@ -59,6 +61,9 @@ export function getToolDefinitions(): ({
59
61
  headers?: undefined;
60
62
  body?: undefined;
61
63
  auth?: undefined;
64
+ flow?: undefined;
65
+ shared?: undefined;
66
+ items?: undefined;
62
67
  output?: undefined;
63
68
  };
64
69
  required: string[];
@@ -115,6 +120,9 @@ export function getToolDefinitions(): ({
115
120
  text?: undefined;
116
121
  input?: undefined;
117
122
  transformFunction?: undefined;
123
+ apiKey?: undefined;
124
+ siteUrl?: undefined;
125
+ siteTitle?: undefined;
118
126
  type?: undefined;
119
127
  selector?: undefined;
120
128
  jsonPath?: undefined;
@@ -124,7 +132,6 @@ export function getToolDefinitions(): ({
124
132
  timeout?: undefined;
125
133
  args?: undefined;
126
134
  requireConfirmation?: undefined;
127
- apiKey?: undefined;
128
135
  cseId?: undefined;
129
136
  command?: undefined;
130
137
  filePath?: undefined;
@@ -134,6 +141,9 @@ export function getToolDefinitions(): ({
134
141
  headers?: undefined;
135
142
  body?: undefined;
136
143
  auth?: undefined;
144
+ flow?: undefined;
145
+ shared?: undefined;
146
+ items?: undefined;
137
147
  output?: undefined;
138
148
  };
139
149
  required: string[];
@@ -171,6 +181,9 @@ export function getToolDefinitions(): ({
171
181
  topK?: undefined;
172
182
  input?: undefined;
173
183
  transformFunction?: undefined;
184
+ apiKey?: undefined;
185
+ siteUrl?: undefined;
186
+ siteTitle?: undefined;
174
187
  type?: undefined;
175
188
  selector?: undefined;
176
189
  jsonPath?: undefined;
@@ -180,7 +193,6 @@ export function getToolDefinitions(): ({
180
193
  timeout?: undefined;
181
194
  args?: undefined;
182
195
  requireConfirmation?: undefined;
183
- apiKey?: undefined;
184
196
  cseId?: undefined;
185
197
  command?: undefined;
186
198
  filePath?: undefined;
@@ -190,6 +202,9 @@ export function getToolDefinitions(): ({
190
202
  headers?: undefined;
191
203
  body?: undefined;
192
204
  auth?: undefined;
205
+ flow?: undefined;
206
+ shared?: undefined;
207
+ items?: undefined;
193
208
  output?: undefined;
194
209
  };
195
210
  required: string[];
@@ -224,6 +239,9 @@ export function getToolDefinitions(): ({
224
239
  embeddingBaseUrl?: undefined;
225
240
  topK?: undefined;
226
241
  text?: undefined;
242
+ apiKey?: undefined;
243
+ siteUrl?: undefined;
244
+ siteTitle?: undefined;
227
245
  type?: undefined;
228
246
  selector?: undefined;
229
247
  jsonPath?: undefined;
@@ -233,7 +251,6 @@ export function getToolDefinitions(): ({
233
251
  timeout?: undefined;
234
252
  args?: undefined;
235
253
  requireConfirmation?: undefined;
236
- apiKey?: undefined;
237
254
  cseId?: undefined;
238
255
  command?: undefined;
239
256
  filePath?: undefined;
@@ -243,6 +260,9 @@ export function getToolDefinitions(): ({
243
260
  headers?: undefined;
244
261
  body?: undefined;
245
262
  auth?: undefined;
263
+ flow?: undefined;
264
+ shared?: undefined;
265
+ items?: undefined;
246
266
  output?: undefined;
247
267
  };
248
268
  required: string[];
@@ -287,6 +307,9 @@ export function getToolDefinitions(): ({
287
307
  text?: undefined;
288
308
  input?: undefined;
289
309
  transformFunction?: undefined;
310
+ apiKey?: undefined;
311
+ siteUrl?: undefined;
312
+ siteTitle?: undefined;
290
313
  type?: undefined;
291
314
  selector?: undefined;
292
315
  jsonPath?: undefined;
@@ -296,7 +319,6 @@ export function getToolDefinitions(): ({
296
319
  timeout?: undefined;
297
320
  args?: undefined;
298
321
  requireConfirmation?: undefined;
299
- apiKey?: undefined;
300
322
  cseId?: undefined;
301
323
  command?: undefined;
302
324
  filePath?: undefined;
@@ -306,6 +328,9 @@ export function getToolDefinitions(): ({
306
328
  headers?: undefined;
307
329
  body?: undefined;
308
330
  auth?: undefined;
331
+ flow?: undefined;
332
+ shared?: undefined;
333
+ items?: undefined;
309
334
  output?: undefined;
310
335
  };
311
336
  required: string[];
@@ -337,6 +362,9 @@ export function getToolDefinitions(): ({
337
362
  text?: undefined;
338
363
  input?: undefined;
339
364
  transformFunction?: undefined;
365
+ apiKey?: undefined;
366
+ siteUrl?: undefined;
367
+ siteTitle?: undefined;
340
368
  type?: undefined;
341
369
  selector?: undefined;
342
370
  jsonPath?: undefined;
@@ -346,7 +374,6 @@ export function getToolDefinitions(): ({
346
374
  timeout?: undefined;
347
375
  args?: undefined;
348
376
  requireConfirmation?: undefined;
349
- apiKey?: undefined;
350
377
  cseId?: undefined;
351
378
  command?: undefined;
352
379
  filePath?: undefined;
@@ -356,6 +383,9 @@ export function getToolDefinitions(): ({
356
383
  headers?: undefined;
357
384
  body?: undefined;
358
385
  auth?: undefined;
386
+ flow?: undefined;
387
+ shared?: undefined;
388
+ items?: undefined;
359
389
  output?: undefined;
360
390
  };
361
391
  required: string[];
@@ -374,13 +404,22 @@ export function getToolDefinitions(): ({
374
404
  type: string;
375
405
  description: string;
376
406
  };
377
- baseUrl: {
407
+ apiKey: {
408
+ type: string;
409
+ description: string;
410
+ };
411
+ siteUrl: {
412
+ type: string;
413
+ description: string;
414
+ };
415
+ siteTitle: {
378
416
  type: string;
379
417
  description: string;
380
418
  };
381
419
  hfToken?: undefined;
382
420
  temperature?: undefined;
383
421
  max_new_tokens?: undefined;
422
+ baseUrl?: undefined;
384
423
  action?: undefined;
385
424
  content?: undefined;
386
425
  query?: undefined;
@@ -402,7 +441,67 @@ export function getToolDefinitions(): ({
402
441
  timeout?: undefined;
403
442
  args?: undefined;
404
443
  requireConfirmation?: undefined;
444
+ cseId?: undefined;
445
+ command?: undefined;
446
+ filePath?: undefined;
447
+ directoryPath?: undefined;
448
+ url?: undefined;
449
+ method?: undefined;
450
+ headers?: undefined;
451
+ body?: undefined;
452
+ auth?: undefined;
453
+ flow?: undefined;
454
+ shared?: undefined;
455
+ items?: undefined;
456
+ output?: undefined;
457
+ };
458
+ required: string[];
459
+ };
460
+ } | {
461
+ name: string;
462
+ description: string;
463
+ parameters: {
464
+ type: string;
465
+ properties: {
466
+ prompt: {
467
+ type: string;
468
+ description: string;
469
+ };
470
+ model: {
471
+ type: string;
472
+ description: string;
473
+ };
474
+ baseUrl: {
475
+ type: string;
476
+ description: string;
477
+ };
478
+ hfToken?: undefined;
479
+ temperature?: undefined;
480
+ max_new_tokens?: undefined;
481
+ action?: undefined;
482
+ content?: undefined;
483
+ query?: undefined;
484
+ id?: undefined;
485
+ metadata?: undefined;
486
+ memoryPath?: undefined;
487
+ embeddingModel?: undefined;
488
+ embeddingBaseUrl?: undefined;
489
+ topK?: undefined;
490
+ text?: undefined;
491
+ input?: undefined;
492
+ transformFunction?: undefined;
405
493
  apiKey?: undefined;
494
+ siteUrl?: undefined;
495
+ siteTitle?: undefined;
496
+ type?: undefined;
497
+ selector?: undefined;
498
+ jsonPath?: undefined;
499
+ regex?: undefined;
500
+ group?: undefined;
501
+ code?: undefined;
502
+ timeout?: undefined;
503
+ args?: undefined;
504
+ requireConfirmation?: undefined;
406
505
  cseId?: undefined;
407
506
  command?: undefined;
408
507
  filePath?: undefined;
@@ -412,6 +511,9 @@ export function getToolDefinitions(): ({
412
511
  headers?: undefined;
413
512
  body?: undefined;
414
513
  auth?: undefined;
514
+ flow?: undefined;
515
+ shared?: undefined;
516
+ items?: undefined;
415
517
  output?: undefined;
416
518
  };
417
519
  required: string[];
@@ -464,11 +566,13 @@ export function getToolDefinitions(): ({
464
566
  topK?: undefined;
465
567
  text?: undefined;
466
568
  transformFunction?: undefined;
569
+ apiKey?: undefined;
570
+ siteUrl?: undefined;
571
+ siteTitle?: undefined;
467
572
  code?: undefined;
468
573
  timeout?: undefined;
469
574
  args?: undefined;
470
575
  requireConfirmation?: undefined;
471
- apiKey?: undefined;
472
576
  cseId?: undefined;
473
577
  command?: undefined;
474
578
  filePath?: undefined;
@@ -478,6 +582,9 @@ export function getToolDefinitions(): ({
478
582
  headers?: undefined;
479
583
  body?: undefined;
480
584
  auth?: undefined;
585
+ flow?: undefined;
586
+ shared?: undefined;
587
+ items?: undefined;
481
588
  output?: undefined;
482
589
  };
483
590
  required: string[];
@@ -525,12 +632,14 @@ export function getToolDefinitions(): ({
525
632
  text?: undefined;
526
633
  input?: undefined;
527
634
  transformFunction?: undefined;
635
+ apiKey?: undefined;
636
+ siteUrl?: undefined;
637
+ siteTitle?: undefined;
528
638
  type?: undefined;
529
639
  selector?: undefined;
530
640
  jsonPath?: undefined;
531
641
  regex?: undefined;
532
642
  group?: undefined;
533
- apiKey?: undefined;
534
643
  cseId?: undefined;
535
644
  command?: undefined;
536
645
  filePath?: undefined;
@@ -540,6 +649,9 @@ export function getToolDefinitions(): ({
540
649
  headers?: undefined;
541
650
  body?: undefined;
542
651
  auth?: undefined;
652
+ flow?: undefined;
653
+ shared?: undefined;
654
+ items?: undefined;
543
655
  output?: undefined;
544
656
  };
545
657
  required: string[];
@@ -571,6 +683,9 @@ export function getToolDefinitions(): ({
571
683
  text?: undefined;
572
684
  input?: undefined;
573
685
  transformFunction?: undefined;
686
+ apiKey?: undefined;
687
+ siteUrl?: undefined;
688
+ siteTitle?: undefined;
574
689
  type?: undefined;
575
690
  selector?: undefined;
576
691
  jsonPath?: undefined;
@@ -580,7 +695,6 @@ export function getToolDefinitions(): ({
580
695
  timeout?: undefined;
581
696
  args?: undefined;
582
697
  requireConfirmation?: undefined;
583
- apiKey?: undefined;
584
698
  cseId?: undefined;
585
699
  command?: undefined;
586
700
  filePath?: undefined;
@@ -590,6 +704,9 @@ export function getToolDefinitions(): ({
590
704
  headers?: undefined;
591
705
  body?: undefined;
592
706
  auth?: undefined;
707
+ flow?: undefined;
708
+ shared?: undefined;
709
+ items?: undefined;
593
710
  output?: undefined;
594
711
  };
595
712
  required: string[];
@@ -629,6 +746,8 @@ export function getToolDefinitions(): ({
629
746
  text?: undefined;
630
747
  input?: undefined;
631
748
  transformFunction?: undefined;
749
+ siteUrl?: undefined;
750
+ siteTitle?: undefined;
632
751
  type?: undefined;
633
752
  selector?: undefined;
634
753
  jsonPath?: undefined;
@@ -646,6 +765,9 @@ export function getToolDefinitions(): ({
646
765
  headers?: undefined;
647
766
  body?: undefined;
648
767
  auth?: undefined;
768
+ flow?: undefined;
769
+ shared?: undefined;
770
+ items?: undefined;
649
771
  output?: undefined;
650
772
  };
651
773
  required: string[];
@@ -678,6 +800,9 @@ export function getToolDefinitions(): ({
678
800
  text?: undefined;
679
801
  input?: undefined;
680
802
  transformFunction?: undefined;
803
+ apiKey?: undefined;
804
+ siteUrl?: undefined;
805
+ siteTitle?: undefined;
681
806
  type?: undefined;
682
807
  selector?: undefined;
683
808
  jsonPath?: undefined;
@@ -687,7 +812,6 @@ export function getToolDefinitions(): ({
687
812
  timeout?: undefined;
688
813
  args?: undefined;
689
814
  requireConfirmation?: undefined;
690
- apiKey?: undefined;
691
815
  cseId?: undefined;
692
816
  filePath?: undefined;
693
817
  directoryPath?: undefined;
@@ -696,6 +820,9 @@ export function getToolDefinitions(): ({
696
820
  headers?: undefined;
697
821
  body?: undefined;
698
822
  auth?: undefined;
823
+ flow?: undefined;
824
+ shared?: undefined;
825
+ items?: undefined;
699
826
  output?: undefined;
700
827
  };
701
828
  required: string[];
@@ -728,6 +855,9 @@ export function getToolDefinitions(): ({
728
855
  text?: undefined;
729
856
  input?: undefined;
730
857
  transformFunction?: undefined;
858
+ apiKey?: undefined;
859
+ siteUrl?: undefined;
860
+ siteTitle?: undefined;
731
861
  type?: undefined;
732
862
  selector?: undefined;
733
863
  jsonPath?: undefined;
@@ -737,7 +867,6 @@ export function getToolDefinitions(): ({
737
867
  timeout?: undefined;
738
868
  args?: undefined;
739
869
  requireConfirmation?: undefined;
740
- apiKey?: undefined;
741
870
  cseId?: undefined;
742
871
  command?: undefined;
743
872
  directoryPath?: undefined;
@@ -746,6 +875,9 @@ export function getToolDefinitions(): ({
746
875
  headers?: undefined;
747
876
  body?: undefined;
748
877
  auth?: undefined;
878
+ flow?: undefined;
879
+ shared?: undefined;
880
+ items?: undefined;
749
881
  output?: undefined;
750
882
  };
751
883
  required: string[];
@@ -781,6 +913,9 @@ export function getToolDefinitions(): ({
781
913
  text?: undefined;
782
914
  input?: undefined;
783
915
  transformFunction?: undefined;
916
+ apiKey?: undefined;
917
+ siteUrl?: undefined;
918
+ siteTitle?: undefined;
784
919
  type?: undefined;
785
920
  selector?: undefined;
786
921
  jsonPath?: undefined;
@@ -790,7 +925,6 @@ export function getToolDefinitions(): ({
790
925
  timeout?: undefined;
791
926
  args?: undefined;
792
927
  requireConfirmation?: undefined;
793
- apiKey?: undefined;
794
928
  cseId?: undefined;
795
929
  command?: undefined;
796
930
  directoryPath?: undefined;
@@ -799,6 +933,9 @@ export function getToolDefinitions(): ({
799
933
  headers?: undefined;
800
934
  body?: undefined;
801
935
  auth?: undefined;
936
+ flow?: undefined;
937
+ shared?: undefined;
938
+ items?: undefined;
802
939
  output?: undefined;
803
940
  };
804
941
  required: string[];
@@ -831,6 +968,9 @@ export function getToolDefinitions(): ({
831
968
  text?: undefined;
832
969
  input?: undefined;
833
970
  transformFunction?: undefined;
971
+ apiKey?: undefined;
972
+ siteUrl?: undefined;
973
+ siteTitle?: undefined;
834
974
  type?: undefined;
835
975
  selector?: undefined;
836
976
  jsonPath?: undefined;
@@ -840,7 +980,6 @@ export function getToolDefinitions(): ({
840
980
  timeout?: undefined;
841
981
  args?: undefined;
842
982
  requireConfirmation?: undefined;
843
- apiKey?: undefined;
844
983
  cseId?: undefined;
845
984
  command?: undefined;
846
985
  filePath?: undefined;
@@ -849,6 +988,9 @@ export function getToolDefinitions(): ({
849
988
  headers?: undefined;
850
989
  body?: undefined;
851
990
  auth?: undefined;
991
+ flow?: undefined;
992
+ shared?: undefined;
993
+ items?: undefined;
852
994
  output?: undefined;
853
995
  };
854
996
  required: string[];
@@ -918,6 +1060,9 @@ export function getToolDefinitions(): ({
918
1060
  text?: undefined;
919
1061
  input?: undefined;
920
1062
  transformFunction?: undefined;
1063
+ apiKey?: undefined;
1064
+ siteUrl?: undefined;
1065
+ siteTitle?: undefined;
921
1066
  type?: undefined;
922
1067
  selector?: undefined;
923
1068
  jsonPath?: undefined;
@@ -927,11 +1072,13 @@ export function getToolDefinitions(): ({
927
1072
  timeout?: undefined;
928
1073
  args?: undefined;
929
1074
  requireConfirmation?: undefined;
930
- apiKey?: undefined;
931
1075
  cseId?: undefined;
932
1076
  command?: undefined;
933
1077
  filePath?: undefined;
934
1078
  directoryPath?: undefined;
1079
+ flow?: undefined;
1080
+ shared?: undefined;
1081
+ items?: undefined;
935
1082
  output?: undefined;
936
1083
  };
937
1084
  required: string[];
@@ -964,6 +1111,68 @@ export function getToolDefinitions(): ({
964
1111
  text?: undefined;
965
1112
  input?: undefined;
966
1113
  transformFunction?: undefined;
1114
+ apiKey?: undefined;
1115
+ siteUrl?: undefined;
1116
+ siteTitle?: undefined;
1117
+ type?: undefined;
1118
+ selector?: undefined;
1119
+ jsonPath?: undefined;
1120
+ regex?: undefined;
1121
+ group?: undefined;
1122
+ code?: undefined;
1123
+ timeout?: undefined;
1124
+ args?: undefined;
1125
+ requireConfirmation?: undefined;
1126
+ cseId?: undefined;
1127
+ command?: undefined;
1128
+ filePath?: undefined;
1129
+ directoryPath?: undefined;
1130
+ method?: undefined;
1131
+ headers?: undefined;
1132
+ body?: undefined;
1133
+ auth?: undefined;
1134
+ flow?: undefined;
1135
+ shared?: undefined;
1136
+ items?: undefined;
1137
+ output?: undefined;
1138
+ };
1139
+ required: string[];
1140
+ };
1141
+ } | {
1142
+ name: string;
1143
+ description: string;
1144
+ parameters: {
1145
+ type: string;
1146
+ properties: {
1147
+ flow: {
1148
+ type: string;
1149
+ description: string;
1150
+ };
1151
+ shared: {
1152
+ type: string;
1153
+ description: string;
1154
+ };
1155
+ prompt?: undefined;
1156
+ model?: undefined;
1157
+ hfToken?: undefined;
1158
+ temperature?: undefined;
1159
+ max_new_tokens?: undefined;
1160
+ baseUrl?: undefined;
1161
+ action?: undefined;
1162
+ content?: undefined;
1163
+ query?: undefined;
1164
+ id?: undefined;
1165
+ metadata?: undefined;
1166
+ memoryPath?: undefined;
1167
+ embeddingModel?: undefined;
1168
+ embeddingBaseUrl?: undefined;
1169
+ topK?: undefined;
1170
+ text?: undefined;
1171
+ input?: undefined;
1172
+ transformFunction?: undefined;
1173
+ apiKey?: undefined;
1174
+ siteUrl?: undefined;
1175
+ siteTitle?: undefined;
967
1176
  type?: undefined;
968
1177
  selector?: undefined;
969
1178
  jsonPath?: undefined;
@@ -973,15 +1182,74 @@ export function getToolDefinitions(): ({
973
1182
  timeout?: undefined;
974
1183
  args?: undefined;
975
1184
  requireConfirmation?: undefined;
1185
+ cseId?: undefined;
1186
+ command?: undefined;
1187
+ filePath?: undefined;
1188
+ directoryPath?: undefined;
1189
+ url?: undefined;
1190
+ method?: undefined;
1191
+ headers?: undefined;
1192
+ body?: undefined;
1193
+ auth?: undefined;
1194
+ items?: undefined;
1195
+ output?: undefined;
1196
+ };
1197
+ required: string[];
1198
+ };
1199
+ } | {
1200
+ name: string;
1201
+ description: string;
1202
+ parameters: {
1203
+ type: string;
1204
+ properties: {
1205
+ items: {
1206
+ type: string;
1207
+ description: string;
1208
+ };
1209
+ flow: {
1210
+ type: string;
1211
+ description: string;
1212
+ };
1213
+ prompt?: undefined;
1214
+ model?: undefined;
1215
+ hfToken?: undefined;
1216
+ temperature?: undefined;
1217
+ max_new_tokens?: undefined;
1218
+ baseUrl?: undefined;
1219
+ action?: undefined;
1220
+ content?: undefined;
1221
+ query?: undefined;
1222
+ id?: undefined;
1223
+ metadata?: undefined;
1224
+ memoryPath?: undefined;
1225
+ embeddingModel?: undefined;
1226
+ embeddingBaseUrl?: undefined;
1227
+ topK?: undefined;
1228
+ text?: undefined;
1229
+ input?: undefined;
1230
+ transformFunction?: undefined;
976
1231
  apiKey?: undefined;
1232
+ siteUrl?: undefined;
1233
+ siteTitle?: undefined;
1234
+ type?: undefined;
1235
+ selector?: undefined;
1236
+ jsonPath?: undefined;
1237
+ regex?: undefined;
1238
+ group?: undefined;
1239
+ code?: undefined;
1240
+ timeout?: undefined;
1241
+ args?: undefined;
1242
+ requireConfirmation?: undefined;
977
1243
  cseId?: undefined;
978
1244
  command?: undefined;
979
1245
  filePath?: undefined;
980
1246
  directoryPath?: undefined;
1247
+ url?: undefined;
981
1248
  method?: undefined;
982
1249
  headers?: undefined;
983
1250
  body?: undefined;
984
1251
  auth?: undefined;
1252
+ shared?: undefined;
985
1253
  output?: undefined;
986
1254
  };
987
1255
  required: string[];
@@ -1014,6 +1282,9 @@ export function getToolDefinitions(): ({
1014
1282
  text?: undefined;
1015
1283
  input?: undefined;
1016
1284
  transformFunction?: undefined;
1285
+ apiKey?: undefined;
1286
+ siteUrl?: undefined;
1287
+ siteTitle?: undefined;
1017
1288
  type?: undefined;
1018
1289
  selector?: undefined;
1019
1290
  jsonPath?: undefined;
@@ -1023,7 +1294,6 @@ export function getToolDefinitions(): ({
1023
1294
  timeout?: undefined;
1024
1295
  args?: undefined;
1025
1296
  requireConfirmation?: undefined;
1026
- apiKey?: undefined;
1027
1297
  cseId?: undefined;
1028
1298
  command?: undefined;
1029
1299
  filePath?: undefined;
@@ -1033,6 +1303,9 @@ export function getToolDefinitions(): ({
1033
1303
  headers?: undefined;
1034
1304
  body?: undefined;
1035
1305
  auth?: undefined;
1306
+ flow?: undefined;
1307
+ shared?: undefined;
1308
+ items?: undefined;
1036
1309
  };
1037
1310
  required: string[];
1038
1311
  };
@@ -166,6 +166,36 @@ export function getToolDefinitions() {
166
166
  required: ["prompt"]
167
167
  }
168
168
  },
169
+ {
170
+ name: "openrouter_llm_reasoning",
171
+ description: "A powerful language model for general reasoning, problem-solving, and generating text, using OpenRouter. Use this when you need to think, plan, or generate human-like responses. Do NOT use this for external actions like searching the web or interacting with files.",
172
+ parameters: {
173
+ type: "object",
174
+ properties: {
175
+ prompt: {
176
+ type: "string",
177
+ description: "The prompt or question to send to the language model."
178
+ },
179
+ model: {
180
+ type: "string",
181
+ description: "The OpenRouter model ID (e.g., 'openai/gpt-4o', 'mistralai/mistral-7b-instruct')."
182
+ },
183
+ apiKey: {
184
+ type: "string",
185
+ description: "Your OpenRouter API key."
186
+ },
187
+ siteUrl: {
188
+ type: "string",
189
+ description: "Optional. Site URL for rankings on openrouter.ai."
190
+ },
191
+ siteTitle: {
192
+ type: "string",
193
+ description: "Optional. Site title for rankings on openrouter.ai."
194
+ }
195
+ },
196
+ required: ["prompt", "model", "apiKey"]
197
+ }
198
+ },
169
199
  {
170
200
  name: "ollama_llm_reasoning",
171
201
  description: "A powerful local language model for general reasoning, problem-solving, and generating text, running via Ollama. Use this when you need to think, plan, or generate human-like responses locally. Do NOT use this for external actions like searching the web or interacting with files.",
@@ -443,6 +473,42 @@ export function getToolDefinitions() {
443
473
  required: ["prompt"]
444
474
  }
445
475
  },
476
+ {
477
+ name: "sub_flow",
478
+ description: "Executes a sub-flow.",
479
+ parameters: {
480
+ type: "object",
481
+ properties: {
482
+ flow: {
483
+ type: "string",
484
+ description: "The name of the flow to execute, as registered in the flow registry."
485
+ },
486
+ shared: {
487
+ type: "object",
488
+ description: "The shared object to pass to the sub-flow."
489
+ }
490
+ },
491
+ required: ["flow"]
492
+ }
493
+ },
494
+ {
495
+ name: "iterator",
496
+ description: "Iterates over a list of items and executes a sub-flow for each item.",
497
+ parameters: {
498
+ type: "object",
499
+ properties: {
500
+ items: {
501
+ type: "array",
502
+ description: "The list of items to iterate over."
503
+ },
504
+ flow: {
505
+ type: "string",
506
+ description: "The name of the flow to execute for each item, as registered in the flow registry."
507
+ }
508
+ },
509
+ required: ["items", "flow"]
510
+ }
511
+ },
446
512
  {
447
513
  name: "finish",
448
514
  description: "Call this tool when you have successfully achieved the goal or if you are unable to proceed further. This will end the agent's execution.",
@@ -3,10 +3,22 @@ import { UserInputNode } from './user.js';
3
3
  import { promises as fs } from 'fs';
4
4
  import path from 'path';
5
5
  import os from 'os';
6
+ import chalk from 'chalk';
6
7
  let nodeChildProcess = null;
7
8
  if (!process.versions.bun) {
8
9
  nodeChildProcess = require('child_process');
9
10
  }
11
+ function syntaxHighlight(code) {
12
+ return code
13
+ .replace(/\b(def|class|import|from|return|if|else|elif|for|while|with|try|except|finally|raise|assert|yield|lambda|pass|continue|break)\b/g, chalk.blue.bold('$1'))
14
+ .replace(/("""[\s\S]*?""")/g, chalk.hex('#6272a4').italic('$1'))
15
+ .replace(/('''[\s\S]*?''')/g, chalk.hex('#6272a4').italic('$1'))
16
+ .replace(/(".*?")/g, chalk.hex('#f1fa8c')('$1'))
17
+ .replace(/('.*?')/g, chalk.hex('#f1fa8c')('$1'))
18
+ .replace(/#.*/g, chalk.hex('#6272a4').italic('$&'))
19
+ .replace(/\b(True|False|None)\b/g, chalk.hex('#bd93f9').bold('$1'))
20
+ .replace(/\b(self|cls)\b/g, chalk.hex('#ffb86c').italic('$1'));
21
+ }
10
22
  export class CodeInterpreterNode extends AsyncNode {
11
23
  async execAsync() {
12
24
  const { code, timeout = 30000, args = [], requireConfirmation = true, interpreterPath } = this.params;
@@ -18,13 +30,12 @@ export class CodeInterpreterNode extends AsyncNode {
18
30
  const tempFilePath = path.join(tempDir, tempFileName);
19
31
  const interpreterCommand = interpreterPath || 'python';
20
32
  console.log(`[CodeInterpreter] Proposed execution: ${interpreterCommand} ${tempFilePath}`);
21
- console.log(`[CodeInterpreter] Code to execute:\n${code}`);
22
- // --- User Confirmation ---
23
- // --- User Confirmation ---
33
+ if (!requireConfirmation)
34
+ console.log(`[CodeInterpreter] Code to execute:\n${syntaxHighlight(code)}`);
24
35
  if (requireConfirmation) {
25
36
  const confirmNode = new UserInputNode();
26
37
  confirmNode.setParams({
27
- prompt: `The agent wants to execute the following Python code:\n${code}\nDo you approve? (yes/no): `
38
+ prompt: `The agent wants to execute the following Python code:\n${syntaxHighlight(code)}\nDo you approve? (yes/no): `
28
39
  });
29
40
  const confirmFlow = new AsyncFlow(confirmNode);
30
41
  const confirmation = await confirmFlow.runAsync({});
@@ -32,13 +43,11 @@ export class CodeInterpreterNode extends AsyncNode {
32
43
  throw new Error('Code execution denied by user.');
33
44
  }
34
45
  }
35
- // --- End User Confirmation ---
36
- // --- End User Confirmation ---
37
46
  try {
38
47
  await fs.writeFile(tempFilePath, code, 'utf-8');
39
48
  let stdout = '';
40
49
  let stderr = '';
41
- let exitCode = 1; // Default to failure
50
+ let exitCode = 1;
42
51
  const abortController = new AbortController();
43
52
  const timeoutId = setTimeout(() => abortController.abort(), timeout);
44
53
  try {
@@ -49,16 +58,15 @@ export class CodeInterpreterNode extends AsyncNode {
49
58
  stderr: 'pipe',
50
59
  signal: abortController.signal,
51
60
  });
52
- // Await stdout and stderr first
53
61
  stdout = await new Response(childProcess.stdout).text();
54
62
  stderr = await new Response(childProcess.stderr).text();
55
63
  const bunExitResult = await childProcess.exited;
56
64
  if (abortController.signal.aborted) {
57
65
  stderr += `\nExecution timed out after ${timeout}ms.`;
58
- exitCode = 1; // Indicate failure due to timeout
66
+ exitCode = 1;
59
67
  }
60
68
  else {
61
- exitCode = Number(bunExitResult !== null ? bunExitResult : 1); // Ensure exitCode is a number
69
+ exitCode = Number(bunExitResult !== null ? bunExitResult : 1);
62
70
  }
63
71
  }
64
72
  else if (nodeChildProcess) {
@@ -76,25 +84,23 @@ export class CodeInterpreterNode extends AsyncNode {
76
84
  });
77
85
  stdout = Buffer.concat(stdoutChunks).toString('utf-8');
78
86
  stderr = Buffer.concat(stderrChunks).toString('utf-8');
79
- exitCode = exitCodeFromClose !== null ? exitCodeFromClose : (signalFromClose ? 1 : 1); // If signal, treat as failure
87
+ exitCode = exitCodeFromClose !== null ? exitCodeFromClose : (signalFromClose ? 1 : 1);
80
88
  }
81
89
  else {
82
90
  throw new Error('Unsupported runtime environment.');
83
91
  }
84
92
  }
85
93
  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
94
+ if (error.name === "AbortError" || error.code === "ABORT_ERR") {
95
+ stderr += `\nExecution timed out after ${timeout}ms.`;
96
+ exitCode = 1;
90
97
  }
91
98
  else if (error.code === 'ENOENT') {
92
99
  stderr += `\nError: Command '${interpreterCommand}' not found. Please ensure it is installed and in your system's PATH.`;
93
100
  exitCode = 1;
94
101
  }
95
102
  else {
96
- stderr += `
97
- Error during execution: ${error.message}`;
103
+ stderr += `\nError during execution: ${error.message}`;
98
104
  exitCode = 1;
99
105
  }
100
106
  }
@@ -104,7 +110,6 @@ Error during execution: ${error.message}`;
104
110
  return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode };
105
111
  }
106
112
  finally {
107
- // Clean up temporary file
108
113
  await fs.unlink(tempFilePath).catch(e => console.error(`Failed to delete temp file ${tempFilePath}:`, e));
109
114
  }
110
115
  }
@@ -18,3 +18,6 @@ export * from "./embedding.js";
18
18
  export * from "./semantic_memory.js";
19
19
  export * from "./semantic_memory.js";
20
20
  export * from "../agent/agent.js";
21
+ export * from "./subflow.js";
22
+ export * from "./iterator.js";
23
+ export * from "./openrouter_llm.js";
@@ -18,3 +18,6 @@ export * from './embedding.js';
18
18
  export * from './semantic_memory.js';
19
19
  export * from './semantic_memory.js';
20
20
  export * from '../agent/agent.js';
21
+ export * from './subflow.js';
22
+ export * from './iterator.js';
23
+ export * from './openrouter_llm.js';
@@ -0,0 +1,5 @@
1
+ export class IteratorNode 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,23 @@
1
+ import { AsyncNode, AsyncFlow } from '../qflow.js';
2
+ export class IteratorNode extends AsyncNode {
3
+ async execAsync() {
4
+ const { items, flow } = this.params;
5
+ if (!items || !Array.isArray(items)) {
6
+ throw new Error('IteratorNode requires an `items` parameter of type Array.');
7
+ }
8
+ if (!flow || !(flow instanceof AsyncFlow)) {
9
+ throw new Error('IteratorNode requires a `flow` parameter of type AsyncFlow.');
10
+ }
11
+ const results = [];
12
+ for (const item of items) {
13
+ const subFlowShared = { item, params: this.params };
14
+ const result = await flow.runAsync(subFlowShared);
15
+ results.push(result);
16
+ }
17
+ return results;
18
+ }
19
+ async postAsync(shared, prepRes, execRes) {
20
+ shared.iteratorResult = execRes;
21
+ return 'default';
22
+ }
23
+ }
@@ -0,0 +1,8 @@
1
+ export class OpenRouterLLMNode extends AsyncNode {
2
+ execAsync(): Promise<any>;
3
+ }
4
+ export class AgentOpenRouterLLMNode extends OpenRouterLLMNode {
5
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
6
+ preparePrompt(shared: any): void;
7
+ }
8
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,123 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ export class OpenRouterLLMNode extends AsyncNode {
3
+ constructor(maxRetries = 3, wait = 2) {
4
+ super(maxRetries, wait);
5
+ }
6
+ async execAsync() {
7
+ const { prompt, apiKey, model, siteUrl, siteTitle } = this.params;
8
+ if (!prompt) {
9
+ throw new Error('OpenRouterLLMNode requires a `prompt`.');
10
+ }
11
+ if (!apiKey) {
12
+ throw new Error('OpenRouterLLMNode requires an `apiKey`.');
13
+ }
14
+ if (!model) {
15
+ throw new Error('OpenRouterLLMNode requires a `model`.');
16
+ }
17
+ const headers = {
18
+ 'Content-Type': 'application/json',
19
+ 'Authorization': `Bearer ${apiKey}`,
20
+ };
21
+ if (siteUrl) {
22
+ headers['HTTP-Referer'] = siteUrl;
23
+ }
24
+ if (siteTitle) {
25
+ headers['X-Title'] = siteTitle;
26
+ }
27
+ console.log(`[OpenRouter] Sending prompt to ${model}...`);
28
+ try {
29
+ const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
30
+ method: 'POST',
31
+ headers: headers,
32
+ body: JSON.stringify({
33
+ model: model,
34
+ messages: [{ role: 'user', content: prompt }],
35
+ }),
36
+ });
37
+ if (!response.ok) {
38
+ const errorData = await response.json();
39
+ throw new Error(`OpenRouter API error: ${response.status} - ${JSON.stringify(errorData)}`);
40
+ }
41
+ const data = await response.json();
42
+ if (!data.choices || data.choices.length === 0 || !data.choices[0].message || typeof data.choices[0].message.content !== 'string') {
43
+ throw new Error('Invalid response structure from OpenRouter API.');
44
+ }
45
+ const llmResponse = data.choices[0].message.content.trim();
46
+ console.log(`[OpenRouter] Received response from ${model}.`);
47
+ return llmResponse;
48
+ }
49
+ catch (error) {
50
+ console.error('OpenRouterLLMNode: Error during API call:', error);
51
+ throw error;
52
+ }
53
+ }
54
+ }
55
+ export class AgentOpenRouterLLMNode extends OpenRouterLLMNode {
56
+ async execAsync() {
57
+ const { prompt, apiKey, model, siteUrl, siteTitle } = this.params; // prompt here is the stringified conversation history
58
+ if (!prompt) {
59
+ throw new Error("AgentOpenRouterLLMNode: Prompt (conversation history) is missing from params.");
60
+ }
61
+ if (!apiKey) {
62
+ throw new Error("OpenRouter API Key is not configured for AgentOpenRouterLLMNode.");
63
+ }
64
+ if (!model) {
65
+ throw new Error("AgentOpenRouterLLMNode requires a `model`.");
66
+ }
67
+ let messages;
68
+ try {
69
+ messages = JSON.parse(prompt);
70
+ // Ensure messages array contains objects with role and content
71
+ if (!Array.isArray(messages) || !messages.every(msg => msg.role && msg.content !== undefined)) {
72
+ throw new Error("Parsed prompt is not a valid messages array.");
73
+ }
74
+ }
75
+ catch (e) {
76
+ throw new Error(`AgentOpenRouterLLMNode: Invalid prompt format. Expected stringified JSON array of messages. Error: ${e.message}`);
77
+ }
78
+ const headers = {
79
+ 'Content-Type': 'application/json',
80
+ 'Authorization': `Bearer ${apiKey}`,
81
+ };
82
+ if (siteUrl) {
83
+ headers['HTTP-Referer'] = siteUrl;
84
+ }
85
+ if (siteTitle) {
86
+ headers['X-Title'] = siteTitle;
87
+ }
88
+ console.log(`[AgentOpenRouter] Sending prompt to ${model}...`);
89
+ try {
90
+ const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
91
+ method: 'POST',
92
+ headers: headers,
93
+ body: JSON.stringify({
94
+ model: model,
95
+ messages: messages, // Use the parsed messages array directly
96
+ }),
97
+ });
98
+ if (!response.ok) {
99
+ const errorData = await response.json();
100
+ throw new Error(`OpenRouter API error: ${response.status} - ${JSON.stringify(errorData)}`);
101
+ }
102
+ const data = await response.json();
103
+ if (!data.choices || data.choices.length === 0 || !data.choices[0].message || typeof data.choices[0].message.content !== 'string') {
104
+ throw new Error('Invalid response structure from OpenRouter API or missing content.');
105
+ }
106
+ const llmResponse = data.choices[0].message.content.trim();
107
+ console.log(`[AgentOpenRouter] Received response from ${model}.`);
108
+ return llmResponse; // Return the actual content
109
+ }
110
+ catch (error) {
111
+ console.error('AgentOpenRouterLLMNode: Error during API call:', error);
112
+ throw error;
113
+ }
114
+ }
115
+ async postAsync(shared, prepRes, execRes) {
116
+ shared.llmResponse = execRes; // Store the full LLM response object
117
+ return execRes; // Return the full LLM response object
118
+ }
119
+ // preparePrompt is no longer needed as execAsync handles the prompt directly
120
+ preparePrompt(shared) {
121
+ throw new Error("preparePrompt should not be called on AgentOpenRouterLLMNode. Prompt is handled in execAsync.");
122
+ }
123
+ }
@@ -0,0 +1,5 @@
1
+ export class SubFlowNode 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,16 @@
1
+ import { AsyncNode, AsyncFlow } from '../qflow.js';
2
+ export class SubFlowNode extends AsyncNode {
3
+ async execAsync() {
4
+ const { flow, shared } = this.params;
5
+ if (!flow || !(flow instanceof AsyncFlow)) {
6
+ throw new Error('SubFlowNode requires an `flow` parameter of type AsyncFlow.');
7
+ }
8
+ const subFlowShared = shared || {};
9
+ const result = await flow.runAsync(subFlowShared);
10
+ return result;
11
+ }
12
+ async postAsync(shared, prepRes, execRes) {
13
+ shared.subFlowResult = execRes;
14
+ return 'default';
15
+ }
16
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.25",
3
+ "version": "1.0.27",
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",
@@ -42,6 +42,7 @@
42
42
  },
43
43
  "homepage": "https://github.com/fractal-solutions/qflow#readme",
44
44
  "dependencies": {
45
+ "chalk": "^5.5.0",
45
46
  "cheerio": "^1.0.0-rc.12"
46
47
  },
47
48
  "devDependencies": {