@fractal-solutions/qflow 1.0.26 → 1.0.28

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).
@@ -1,11 +1,12 @@
1
1
  export class AgentNode extends AsyncNode {
2
- constructor(llmNode: any, availableTools: any, summarizeLLM: any, flowRegistry?: {});
2
+ constructor(llmNode: any, availableTools: any, summarizeLLM: any, flowRegistry?: {}, requireFinishConfirmation?: boolean);
3
3
  llmNode: any;
4
4
  availableTools: any;
5
5
  summarizeLLM: any;
6
6
  flowRegistry: {};
7
7
  conversationHistory: any[];
8
8
  maxSteps: number;
9
+ requireFinishConfirmation: boolean;
9
10
  execAsync(): Promise<any>;
10
11
  getSystemPrompt(): string;
11
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, flowRegistry = {}) {
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.");
@@ -14,6 +15,7 @@ export class AgentNode extends AsyncNode {
14
15
  this.flowRegistry = flowRegistry;
15
16
  this.conversationHistory = [];
16
17
  this.maxSteps = 20;
18
+ this.requireFinishConfirmation = requireFinishConfirmation;
17
19
  }
18
20
  async execAsync() {
19
21
  const { goal } = this.params;
@@ -53,6 +55,19 @@ export class AgentNode extends AsyncNode {
53
55
  this.conversationHistory.push({ role: "assistant", content: JSON.stringify({ thought, tool: toolCall }) });
54
56
  if (toolCall.tool === "finish") {
55
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
+ }
56
71
  logger.final(finalOutput);
57
72
  break;
58
73
  }
@@ -127,12 +142,19 @@ export class AgentNode extends AsyncNode {
127
142
  let rawData = llmResponse;
128
143
  if (typeof llmResponse === 'string') {
129
144
  try {
130
- 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).");
131
150
  }
132
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
133
154
  return { thought: "Direct LLM response", tool: { tool: "finish", parameters: { output: llmResponse } } };
134
155
  }
135
156
  }
157
+ // Prioritize tool_calls if present (OpenAI function calling format)
136
158
  if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0].message) {
137
159
  const message = rawData.choices[0].message;
138
160
  if (message.tool_calls && message.tool_calls.length > 0) {
@@ -145,6 +167,7 @@ export class AgentNode extends AsyncNode {
145
167
  return { thought, tool: toolCall };
146
168
  }
147
169
  else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
170
+ // If no tool_calls, but content is JSON (for thought/tool/finish)
148
171
  try {
149
172
  parsed = JSON.parse(message.content);
150
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;
@@ -118,6 +120,9 @@ export function getToolDefinitions(): ({
118
120
  text?: undefined;
119
121
  input?: undefined;
120
122
  transformFunction?: undefined;
123
+ apiKey?: undefined;
124
+ siteUrl?: undefined;
125
+ siteTitle?: undefined;
121
126
  type?: undefined;
122
127
  selector?: undefined;
123
128
  jsonPath?: undefined;
@@ -127,7 +132,6 @@ export function getToolDefinitions(): ({
127
132
  timeout?: undefined;
128
133
  args?: undefined;
129
134
  requireConfirmation?: undefined;
130
- apiKey?: undefined;
131
135
  cseId?: undefined;
132
136
  command?: undefined;
133
137
  filePath?: undefined;
@@ -177,6 +181,9 @@ export function getToolDefinitions(): ({
177
181
  topK?: undefined;
178
182
  input?: undefined;
179
183
  transformFunction?: undefined;
184
+ apiKey?: undefined;
185
+ siteUrl?: undefined;
186
+ siteTitle?: undefined;
180
187
  type?: undefined;
181
188
  selector?: undefined;
182
189
  jsonPath?: undefined;
@@ -186,7 +193,6 @@ export function getToolDefinitions(): ({
186
193
  timeout?: undefined;
187
194
  args?: undefined;
188
195
  requireConfirmation?: undefined;
189
- apiKey?: undefined;
190
196
  cseId?: undefined;
191
197
  command?: undefined;
192
198
  filePath?: undefined;
@@ -233,6 +239,9 @@ export function getToolDefinitions(): ({
233
239
  embeddingBaseUrl?: undefined;
234
240
  topK?: undefined;
235
241
  text?: undefined;
242
+ apiKey?: undefined;
243
+ siteUrl?: undefined;
244
+ siteTitle?: undefined;
236
245
  type?: undefined;
237
246
  selector?: undefined;
238
247
  jsonPath?: undefined;
@@ -242,7 +251,6 @@ export function getToolDefinitions(): ({
242
251
  timeout?: undefined;
243
252
  args?: undefined;
244
253
  requireConfirmation?: undefined;
245
- apiKey?: undefined;
246
254
  cseId?: undefined;
247
255
  command?: undefined;
248
256
  filePath?: undefined;
@@ -299,6 +307,9 @@ export function getToolDefinitions(): ({
299
307
  text?: undefined;
300
308
  input?: undefined;
301
309
  transformFunction?: undefined;
310
+ apiKey?: undefined;
311
+ siteUrl?: undefined;
312
+ siteTitle?: undefined;
302
313
  type?: undefined;
303
314
  selector?: undefined;
304
315
  jsonPath?: undefined;
@@ -308,7 +319,6 @@ export function getToolDefinitions(): ({
308
319
  timeout?: undefined;
309
320
  args?: undefined;
310
321
  requireConfirmation?: undefined;
311
- apiKey?: undefined;
312
322
  cseId?: undefined;
313
323
  command?: undefined;
314
324
  filePath?: undefined;
@@ -352,6 +362,9 @@ export function getToolDefinitions(): ({
352
362
  text?: undefined;
353
363
  input?: undefined;
354
364
  transformFunction?: undefined;
365
+ apiKey?: undefined;
366
+ siteUrl?: undefined;
367
+ siteTitle?: undefined;
355
368
  type?: undefined;
356
369
  selector?: undefined;
357
370
  jsonPath?: undefined;
@@ -361,7 +374,6 @@ export function getToolDefinitions(): ({
361
374
  timeout?: undefined;
362
375
  args?: undefined;
363
376
  requireConfirmation?: undefined;
364
- apiKey?: undefined;
365
377
  cseId?: undefined;
366
378
  command?: undefined;
367
379
  filePath?: undefined;
@@ -392,13 +404,22 @@ export function getToolDefinitions(): ({
392
404
  type: string;
393
405
  description: string;
394
406
  };
395
- baseUrl: {
407
+ apiKey: {
408
+ type: string;
409
+ description: string;
410
+ };
411
+ siteUrl: {
412
+ type: string;
413
+ description: string;
414
+ };
415
+ siteTitle: {
396
416
  type: string;
397
417
  description: string;
398
418
  };
399
419
  hfToken?: undefined;
400
420
  temperature?: undefined;
401
421
  max_new_tokens?: undefined;
422
+ baseUrl?: undefined;
402
423
  action?: undefined;
403
424
  content?: undefined;
404
425
  query?: undefined;
@@ -420,7 +441,67 @@ export function getToolDefinitions(): ({
420
441
  timeout?: undefined;
421
442
  args?: undefined;
422
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;
423
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;
424
505
  cseId?: undefined;
425
506
  command?: undefined;
426
507
  filePath?: undefined;
@@ -485,11 +566,13 @@ export function getToolDefinitions(): ({
485
566
  topK?: undefined;
486
567
  text?: undefined;
487
568
  transformFunction?: undefined;
569
+ apiKey?: undefined;
570
+ siteUrl?: undefined;
571
+ siteTitle?: undefined;
488
572
  code?: undefined;
489
573
  timeout?: undefined;
490
574
  args?: undefined;
491
575
  requireConfirmation?: undefined;
492
- apiKey?: undefined;
493
576
  cseId?: undefined;
494
577
  command?: undefined;
495
578
  filePath?: undefined;
@@ -549,12 +632,14 @@ export function getToolDefinitions(): ({
549
632
  text?: undefined;
550
633
  input?: undefined;
551
634
  transformFunction?: undefined;
635
+ apiKey?: undefined;
636
+ siteUrl?: undefined;
637
+ siteTitle?: undefined;
552
638
  type?: undefined;
553
639
  selector?: undefined;
554
640
  jsonPath?: undefined;
555
641
  regex?: undefined;
556
642
  group?: undefined;
557
- apiKey?: undefined;
558
643
  cseId?: undefined;
559
644
  command?: undefined;
560
645
  filePath?: undefined;
@@ -598,6 +683,9 @@ export function getToolDefinitions(): ({
598
683
  text?: undefined;
599
684
  input?: undefined;
600
685
  transformFunction?: undefined;
686
+ apiKey?: undefined;
687
+ siteUrl?: undefined;
688
+ siteTitle?: undefined;
601
689
  type?: undefined;
602
690
  selector?: undefined;
603
691
  jsonPath?: undefined;
@@ -607,7 +695,6 @@ export function getToolDefinitions(): ({
607
695
  timeout?: undefined;
608
696
  args?: undefined;
609
697
  requireConfirmation?: undefined;
610
- apiKey?: undefined;
611
698
  cseId?: undefined;
612
699
  command?: undefined;
613
700
  filePath?: undefined;
@@ -659,6 +746,8 @@ export function getToolDefinitions(): ({
659
746
  text?: undefined;
660
747
  input?: undefined;
661
748
  transformFunction?: undefined;
749
+ siteUrl?: undefined;
750
+ siteTitle?: undefined;
662
751
  type?: undefined;
663
752
  selector?: undefined;
664
753
  jsonPath?: undefined;
@@ -711,6 +800,9 @@ export function getToolDefinitions(): ({
711
800
  text?: undefined;
712
801
  input?: undefined;
713
802
  transformFunction?: undefined;
803
+ apiKey?: undefined;
804
+ siteUrl?: undefined;
805
+ siteTitle?: undefined;
714
806
  type?: undefined;
715
807
  selector?: undefined;
716
808
  jsonPath?: undefined;
@@ -720,7 +812,6 @@ export function getToolDefinitions(): ({
720
812
  timeout?: undefined;
721
813
  args?: undefined;
722
814
  requireConfirmation?: undefined;
723
- apiKey?: undefined;
724
815
  cseId?: undefined;
725
816
  filePath?: undefined;
726
817
  directoryPath?: undefined;
@@ -764,6 +855,9 @@ export function getToolDefinitions(): ({
764
855
  text?: undefined;
765
856
  input?: undefined;
766
857
  transformFunction?: undefined;
858
+ apiKey?: undefined;
859
+ siteUrl?: undefined;
860
+ siteTitle?: undefined;
767
861
  type?: undefined;
768
862
  selector?: undefined;
769
863
  jsonPath?: undefined;
@@ -773,7 +867,6 @@ export function getToolDefinitions(): ({
773
867
  timeout?: undefined;
774
868
  args?: undefined;
775
869
  requireConfirmation?: undefined;
776
- apiKey?: undefined;
777
870
  cseId?: undefined;
778
871
  command?: undefined;
779
872
  directoryPath?: undefined;
@@ -820,6 +913,9 @@ export function getToolDefinitions(): ({
820
913
  text?: undefined;
821
914
  input?: undefined;
822
915
  transformFunction?: undefined;
916
+ apiKey?: undefined;
917
+ siteUrl?: undefined;
918
+ siteTitle?: undefined;
823
919
  type?: undefined;
824
920
  selector?: undefined;
825
921
  jsonPath?: undefined;
@@ -829,7 +925,6 @@ export function getToolDefinitions(): ({
829
925
  timeout?: undefined;
830
926
  args?: undefined;
831
927
  requireConfirmation?: undefined;
832
- apiKey?: undefined;
833
928
  cseId?: undefined;
834
929
  command?: undefined;
835
930
  directoryPath?: undefined;
@@ -873,6 +968,9 @@ export function getToolDefinitions(): ({
873
968
  text?: undefined;
874
969
  input?: undefined;
875
970
  transformFunction?: undefined;
971
+ apiKey?: undefined;
972
+ siteUrl?: undefined;
973
+ siteTitle?: undefined;
876
974
  type?: undefined;
877
975
  selector?: undefined;
878
976
  jsonPath?: undefined;
@@ -882,7 +980,6 @@ export function getToolDefinitions(): ({
882
980
  timeout?: undefined;
883
981
  args?: undefined;
884
982
  requireConfirmation?: undefined;
885
- apiKey?: undefined;
886
983
  cseId?: undefined;
887
984
  command?: undefined;
888
985
  filePath?: undefined;
@@ -963,6 +1060,9 @@ export function getToolDefinitions(): ({
963
1060
  text?: undefined;
964
1061
  input?: undefined;
965
1062
  transformFunction?: undefined;
1063
+ apiKey?: undefined;
1064
+ siteUrl?: undefined;
1065
+ siteTitle?: undefined;
966
1066
  type?: undefined;
967
1067
  selector?: undefined;
968
1068
  jsonPath?: undefined;
@@ -972,7 +1072,6 @@ export function getToolDefinitions(): ({
972
1072
  timeout?: undefined;
973
1073
  args?: undefined;
974
1074
  requireConfirmation?: undefined;
975
- apiKey?: undefined;
976
1075
  cseId?: undefined;
977
1076
  command?: undefined;
978
1077
  filePath?: undefined;
@@ -1012,6 +1111,9 @@ export function getToolDefinitions(): ({
1012
1111
  text?: undefined;
1013
1112
  input?: undefined;
1014
1113
  transformFunction?: undefined;
1114
+ apiKey?: undefined;
1115
+ siteUrl?: undefined;
1116
+ siteTitle?: undefined;
1015
1117
  type?: undefined;
1016
1118
  selector?: undefined;
1017
1119
  jsonPath?: undefined;
@@ -1021,7 +1123,6 @@ export function getToolDefinitions(): ({
1021
1123
  timeout?: undefined;
1022
1124
  args?: undefined;
1023
1125
  requireConfirmation?: undefined;
1024
- apiKey?: undefined;
1025
1126
  cseId?: undefined;
1026
1127
  command?: undefined;
1027
1128
  filePath?: undefined;
@@ -1069,6 +1170,9 @@ export function getToolDefinitions(): ({
1069
1170
  text?: undefined;
1070
1171
  input?: undefined;
1071
1172
  transformFunction?: undefined;
1173
+ apiKey?: undefined;
1174
+ siteUrl?: undefined;
1175
+ siteTitle?: undefined;
1072
1176
  type?: undefined;
1073
1177
  selector?: undefined;
1074
1178
  jsonPath?: undefined;
@@ -1078,7 +1182,6 @@ export function getToolDefinitions(): ({
1078
1182
  timeout?: undefined;
1079
1183
  args?: undefined;
1080
1184
  requireConfirmation?: undefined;
1081
- apiKey?: undefined;
1082
1185
  cseId?: undefined;
1083
1186
  command?: undefined;
1084
1187
  filePath?: undefined;
@@ -1125,6 +1228,9 @@ export function getToolDefinitions(): ({
1125
1228
  text?: undefined;
1126
1229
  input?: undefined;
1127
1230
  transformFunction?: undefined;
1231
+ apiKey?: undefined;
1232
+ siteUrl?: undefined;
1233
+ siteTitle?: undefined;
1128
1234
  type?: undefined;
1129
1235
  selector?: undefined;
1130
1236
  jsonPath?: undefined;
@@ -1134,7 +1240,6 @@ export function getToolDefinitions(): ({
1134
1240
  timeout?: undefined;
1135
1241
  args?: undefined;
1136
1242
  requireConfirmation?: undefined;
1137
- apiKey?: undefined;
1138
1243
  cseId?: undefined;
1139
1244
  command?: undefined;
1140
1245
  filePath?: undefined;
@@ -1177,6 +1282,9 @@ export function getToolDefinitions(): ({
1177
1282
  text?: undefined;
1178
1283
  input?: undefined;
1179
1284
  transformFunction?: undefined;
1285
+ apiKey?: undefined;
1286
+ siteUrl?: undefined;
1287
+ siteTitle?: undefined;
1180
1288
  type?: undefined;
1181
1289
  selector?: undefined;
1182
1290
  jsonPath?: undefined;
@@ -1186,7 +1294,6 @@ export function getToolDefinitions(): ({
1186
1294
  timeout?: undefined;
1187
1295
  args?: undefined;
1188
1296
  requireConfirmation?: undefined;
1189
- apiKey?: undefined;
1190
1297
  cseId?: undefined;
1191
1298
  command?: undefined;
1192
1299
  filePath?: undefined;
@@ -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.",
@@ -20,3 +20,4 @@ export * from "./semantic_memory.js";
20
20
  export * from "../agent/agent.js";
21
21
  export * from "./subflow.js";
22
22
  export * from "./iterator.js";
23
+ export * from "./openrouter_llm.js";
@@ -20,3 +20,4 @@ export * from './semantic_memory.js';
20
20
  export * from '../agent/agent.js';
21
21
  export * from './subflow.js';
22
22
  export * from './iterator.js';
23
+ export * from './openrouter_llm.js';
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.26",
3
+ "version": "1.0.28",
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",