@fractal-solutions/qflow 1.0.21 → 1.0.22

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,8 +125,9 @@ 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):**](#7-inter-node-communication-with-shared-state-advanced-example) The core of agentic behavior.
128
+ * [**LLMs (DeepSeek, OpenAI, Gemini, Ollama, Hugging Face):**](#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
+ * [**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`).
130
131
  * [**Agent:**](#12-interactive-agent-example) Orchestrating tools and LLM reasoning to achieve complex goals.
131
132
  * [**Embedding:**](#18-embedding-node) For generating vector embeddings from text using Ollama.
132
133
  * [**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).
@@ -31,7 +31,8 @@ export class AgentNode extends AsyncNode {
31
31
  let llmResponse;
32
32
  try {
33
33
  llmResponse = await this.getLLMAction();
34
- console.log(`LLM Raw Response: ${llmResponse}`);
34
+ //console.log(`LLM Raw Response (before parsing):`, llmResponse); // Added logging
35
+ //console.log(`LLM Raw Response Type (before parsing):`, typeof llmResponse); // Added logging
35
36
  }
36
37
  catch (e) {
37
38
  console.error("Error getting LLM action:", e.message);
@@ -113,18 +114,53 @@ export class AgentNode extends AsyncNode {
113
114
  return llmResult;
114
115
  }
115
116
  parseLLMResponse(llmResponse) {
116
- // Remove markdown code block wrapper if present
117
- const cleanedResponse = llmResponse.replace(/^```json\n|\n```$/g, '').trim();
118
- try {
119
- const parsed = JSON.parse(cleanedResponse);
120
- if (parsed.thought && parsed.tool && parsed.tool.tool && parsed.tool.parameters !== undefined) {
121
- return parsed;
117
+ let parsed;
118
+ let thought = '';
119
+ let toolCall = {};
120
+ // Check if llmResponse is already a parsed object (e.g., from AgentHuggingFaceLLMNode's raw data)
121
+ // This is a temporary measure for debugging, ideally llmResponse should always be a string
122
+ let rawData = llmResponse;
123
+ if (typeof llmResponse === 'string') {
124
+ try {
125
+ rawData = JSON.parse(llmResponse);
126
+ }
127
+ catch (e) {
128
+ // If it's not JSON, assume it's a direct text response from LLM
129
+ // This path should ideally not be taken if LLM is tool-calling capable
130
+ return { thought: "Direct LLM response", tool: { tool: "finish", parameters: { output: llmResponse } } };
122
131
  }
123
- throw new Error("Missing required keys in LLM response (thought, tool.tool, tool.parameters).");
124
132
  }
125
- catch (e) {
126
- throw new Error(`Invalid JSON or unexpected format: ${e.message}. Cleaned Response: ${cleanedResponse}`);
133
+ // Prioritize tool_calls if present (OpenAI function calling format)
134
+ if (rawData.choices && rawData.choices.length > 0 && rawData.choices[0].message) {
135
+ const message = rawData.choices[0].message;
136
+ if (message.tool_calls && message.tool_calls.length > 0) {
137
+ const firstToolCall = message.tool_calls[0];
138
+ toolCall = {
139
+ tool: firstToolCall.function.name,
140
+ parameters: JSON.parse(firstToolCall.function.arguments)
141
+ };
142
+ thought = message.reasoning_content || `Calling tool: ${toolCall.tool}`; // Use reasoning_content if available
143
+ return { thought, tool: toolCall };
144
+ }
145
+ else if (typeof message.content === 'string' && message.content.trim().startsWith('{')) {
146
+ // If no tool_calls, but content is JSON (for thought/tool/finish)
147
+ try {
148
+ parsed = JSON.parse(message.content);
149
+ if (parsed.thought && parsed.tool && parsed.tool.tool && parsed.tool.parameters !== undefined) {
150
+ return parsed;
151
+ }
152
+ throw new Error("Missing required keys in LLM response (thought, tool.tool, tool.parameters).");
153
+ }
154
+ catch (e) {
155
+ throw new Error(`Invalid JSON or unexpected format in message.content: ${e.message}. Content: ${message.content}`);
156
+ }
157
+ }
158
+ else if (typeof message.content === 'string') {
159
+ // If content is plain text, assume it's a direct answer
160
+ return { thought: "Direct LLM response", tool: { tool: "finish", parameters: { output: message.content } } };
161
+ }
127
162
  }
163
+ throw new Error(`Invalid LLM response structure. Raw Data: ${JSON.stringify(rawData)}`);
128
164
  }
129
165
  async postAsync(shared, prepRes, execRes) {
130
166
  shared.agentOutput = execRes;
@@ -1,4 +1,69 @@
1
1
  export function getToolDefinitions(): ({
2
+ name: string;
3
+ description: string;
4
+ parameters: {
5
+ type: string;
6
+ properties: {
7
+ prompt: {
8
+ type: string;
9
+ description: string;
10
+ };
11
+ model: {
12
+ type: string;
13
+ description: string;
14
+ };
15
+ hfToken: {
16
+ type: string;
17
+ description: string;
18
+ };
19
+ temperature: {
20
+ type: string;
21
+ description: string;
22
+ };
23
+ max_new_tokens: {
24
+ type: string;
25
+ description: string;
26
+ };
27
+ baseUrl: {
28
+ type: string;
29
+ description: string;
30
+ };
31
+ action?: undefined;
32
+ content?: undefined;
33
+ query?: undefined;
34
+ id?: undefined;
35
+ metadata?: undefined;
36
+ memoryPath?: undefined;
37
+ embeddingModel?: undefined;
38
+ embeddingBaseUrl?: undefined;
39
+ topK?: undefined;
40
+ text?: undefined;
41
+ input?: undefined;
42
+ transformFunction?: undefined;
43
+ type?: undefined;
44
+ selector?: undefined;
45
+ jsonPath?: undefined;
46
+ regex?: undefined;
47
+ group?: undefined;
48
+ code?: undefined;
49
+ timeout?: undefined;
50
+ args?: undefined;
51
+ requireConfirmation?: undefined;
52
+ apiKey?: undefined;
53
+ cseId?: undefined;
54
+ command?: undefined;
55
+ filePath?: undefined;
56
+ directoryPath?: undefined;
57
+ url?: undefined;
58
+ method?: undefined;
59
+ headers?: undefined;
60
+ body?: undefined;
61
+ auth?: undefined;
62
+ output?: undefined;
63
+ };
64
+ required: string[];
65
+ };
66
+ } | {
2
67
  name: string;
3
68
  description: string;
4
69
  parameters: {
@@ -41,12 +106,15 @@ export function getToolDefinitions(): ({
41
106
  type: string;
42
107
  description: string;
43
108
  };
44
- text?: undefined;
109
+ prompt?: undefined;
45
110
  model?: undefined;
111
+ hfToken?: undefined;
112
+ temperature?: undefined;
113
+ max_new_tokens?: undefined;
46
114
  baseUrl?: undefined;
115
+ text?: undefined;
47
116
  input?: undefined;
48
117
  transformFunction?: undefined;
49
- prompt?: undefined;
50
118
  type?: undefined;
51
119
  selector?: undefined;
52
120
  jsonPath?: undefined;
@@ -88,6 +156,10 @@ export function getToolDefinitions(): ({
88
156
  type: string;
89
157
  description: string;
90
158
  };
159
+ prompt?: undefined;
160
+ hfToken?: undefined;
161
+ temperature?: undefined;
162
+ max_new_tokens?: undefined;
91
163
  action?: undefined;
92
164
  content?: undefined;
93
165
  query?: undefined;
@@ -99,7 +171,6 @@ export function getToolDefinitions(): ({
99
171
  topK?: undefined;
100
172
  input?: undefined;
101
173
  transformFunction?: undefined;
102
- prompt?: undefined;
103
174
  type?: undefined;
104
175
  selector?: undefined;
105
176
  jsonPath?: undefined;
@@ -137,6 +208,12 @@ export function getToolDefinitions(): ({
137
208
  type: string;
138
209
  description: string;
139
210
  };
211
+ prompt?: undefined;
212
+ model?: undefined;
213
+ hfToken?: undefined;
214
+ temperature?: undefined;
215
+ max_new_tokens?: undefined;
216
+ baseUrl?: undefined;
140
217
  action?: undefined;
141
218
  content?: undefined;
142
219
  query?: undefined;
@@ -147,9 +224,6 @@ export function getToolDefinitions(): ({
147
224
  embeddingBaseUrl?: undefined;
148
225
  topK?: undefined;
149
226
  text?: undefined;
150
- model?: undefined;
151
- baseUrl?: undefined;
152
- prompt?: undefined;
153
227
  type?: undefined;
154
228
  selector?: undefined;
155
229
  jsonPath?: undefined;
@@ -200,16 +274,19 @@ export function getToolDefinitions(): ({
200
274
  type: string;
201
275
  description: string;
202
276
  };
277
+ prompt?: undefined;
278
+ model?: undefined;
279
+ hfToken?: undefined;
280
+ temperature?: undefined;
281
+ max_new_tokens?: undefined;
282
+ baseUrl?: undefined;
203
283
  metadata?: undefined;
204
284
  embeddingModel?: undefined;
205
285
  embeddingBaseUrl?: undefined;
206
286
  topK?: undefined;
207
287
  text?: undefined;
208
- model?: undefined;
209
- baseUrl?: undefined;
210
288
  input?: undefined;
211
289
  transformFunction?: undefined;
212
- prompt?: undefined;
213
290
  type?: undefined;
214
291
  selector?: undefined;
215
292
  jsonPath?: undefined;
@@ -243,6 +320,11 @@ export function getToolDefinitions(): ({
243
320
  type: string;
244
321
  description: string;
245
322
  };
323
+ model?: undefined;
324
+ hfToken?: undefined;
325
+ temperature?: undefined;
326
+ max_new_tokens?: undefined;
327
+ baseUrl?: undefined;
246
328
  action?: undefined;
247
329
  content?: undefined;
248
330
  query?: undefined;
@@ -253,8 +335,6 @@ export function getToolDefinitions(): ({
253
335
  embeddingBaseUrl?: undefined;
254
336
  topK?: undefined;
255
337
  text?: undefined;
256
- model?: undefined;
257
- baseUrl?: undefined;
258
338
  input?: undefined;
259
339
  transformFunction?: undefined;
260
340
  type?: undefined;
@@ -298,6 +378,9 @@ export function getToolDefinitions(): ({
298
378
  type: string;
299
379
  description: string;
300
380
  };
381
+ hfToken?: undefined;
382
+ temperature?: undefined;
383
+ max_new_tokens?: undefined;
301
384
  action?: undefined;
302
385
  content?: undefined;
303
386
  query?: undefined;
@@ -364,6 +447,12 @@ export function getToolDefinitions(): ({
364
447
  type: string;
365
448
  description: string;
366
449
  };
450
+ prompt?: undefined;
451
+ model?: undefined;
452
+ hfToken?: undefined;
453
+ temperature?: undefined;
454
+ max_new_tokens?: undefined;
455
+ baseUrl?: undefined;
367
456
  action?: undefined;
368
457
  content?: undefined;
369
458
  query?: undefined;
@@ -374,10 +463,7 @@ export function getToolDefinitions(): ({
374
463
  embeddingBaseUrl?: undefined;
375
464
  topK?: undefined;
376
465
  text?: undefined;
377
- model?: undefined;
378
- baseUrl?: undefined;
379
466
  transformFunction?: undefined;
380
- prompt?: undefined;
381
467
  code?: undefined;
382
468
  timeout?: undefined;
383
469
  args?: undefined;
@@ -421,6 +507,12 @@ export function getToolDefinitions(): ({
421
507
  type: string;
422
508
  description: string;
423
509
  };
510
+ prompt?: undefined;
511
+ model?: undefined;
512
+ hfToken?: undefined;
513
+ temperature?: undefined;
514
+ max_new_tokens?: undefined;
515
+ baseUrl?: undefined;
424
516
  action?: undefined;
425
517
  content?: undefined;
426
518
  query?: undefined;
@@ -431,11 +523,8 @@ export function getToolDefinitions(): ({
431
523
  embeddingBaseUrl?: undefined;
432
524
  topK?: undefined;
433
525
  text?: undefined;
434
- model?: undefined;
435
- baseUrl?: undefined;
436
526
  input?: undefined;
437
527
  transformFunction?: undefined;
438
- prompt?: undefined;
439
528
  type?: undefined;
440
529
  selector?: undefined;
441
530
  jsonPath?: undefined;
@@ -465,6 +554,12 @@ export function getToolDefinitions(): ({
465
554
  type: string;
466
555
  description: string;
467
556
  };
557
+ prompt?: undefined;
558
+ model?: undefined;
559
+ hfToken?: undefined;
560
+ temperature?: undefined;
561
+ max_new_tokens?: undefined;
562
+ baseUrl?: undefined;
468
563
  action?: undefined;
469
564
  content?: undefined;
470
565
  id?: undefined;
@@ -474,11 +569,8 @@ export function getToolDefinitions(): ({
474
569
  embeddingBaseUrl?: undefined;
475
570
  topK?: undefined;
476
571
  text?: undefined;
477
- model?: undefined;
478
- baseUrl?: undefined;
479
572
  input?: undefined;
480
573
  transformFunction?: undefined;
481
- prompt?: undefined;
482
574
  type?: undefined;
483
575
  selector?: undefined;
484
576
  jsonPath?: undefined;
@@ -520,6 +612,12 @@ export function getToolDefinitions(): ({
520
612
  type: string;
521
613
  description: string;
522
614
  };
615
+ prompt?: undefined;
616
+ model?: undefined;
617
+ hfToken?: undefined;
618
+ temperature?: undefined;
619
+ max_new_tokens?: undefined;
620
+ baseUrl?: undefined;
523
621
  action?: undefined;
524
622
  content?: undefined;
525
623
  id?: undefined;
@@ -529,11 +627,8 @@ export function getToolDefinitions(): ({
529
627
  embeddingBaseUrl?: undefined;
530
628
  topK?: undefined;
531
629
  text?: undefined;
532
- model?: undefined;
533
- baseUrl?: undefined;
534
630
  input?: undefined;
535
631
  transformFunction?: undefined;
536
- prompt?: undefined;
537
632
  type?: undefined;
538
633
  selector?: undefined;
539
634
  jsonPath?: undefined;
@@ -565,6 +660,12 @@ export function getToolDefinitions(): ({
565
660
  type: string;
566
661
  description: string;
567
662
  };
663
+ prompt?: undefined;
664
+ model?: undefined;
665
+ hfToken?: undefined;
666
+ temperature?: undefined;
667
+ max_new_tokens?: undefined;
668
+ baseUrl?: undefined;
568
669
  action?: undefined;
569
670
  content?: undefined;
570
671
  query?: undefined;
@@ -575,11 +676,8 @@ export function getToolDefinitions(): ({
575
676
  embeddingBaseUrl?: undefined;
576
677
  topK?: undefined;
577
678
  text?: undefined;
578
- model?: undefined;
579
- baseUrl?: undefined;
580
679
  input?: undefined;
581
680
  transformFunction?: undefined;
582
- prompt?: undefined;
583
681
  type?: undefined;
584
682
  selector?: undefined;
585
683
  jsonPath?: undefined;
@@ -612,6 +710,12 @@ export function getToolDefinitions(): ({
612
710
  type: string;
613
711
  description: string;
614
712
  };
713
+ prompt?: undefined;
714
+ model?: undefined;
715
+ hfToken?: undefined;
716
+ temperature?: undefined;
717
+ max_new_tokens?: undefined;
718
+ baseUrl?: undefined;
615
719
  action?: undefined;
616
720
  content?: undefined;
617
721
  query?: undefined;
@@ -622,11 +726,8 @@ export function getToolDefinitions(): ({
622
726
  embeddingBaseUrl?: undefined;
623
727
  topK?: undefined;
624
728
  text?: undefined;
625
- model?: undefined;
626
- baseUrl?: undefined;
627
729
  input?: undefined;
628
730
  transformFunction?: undefined;
629
- prompt?: undefined;
630
731
  type?: undefined;
631
732
  selector?: undefined;
632
733
  jsonPath?: undefined;
@@ -663,6 +764,12 @@ export function getToolDefinitions(): ({
663
764
  type: string;
664
765
  description: string;
665
766
  };
767
+ prompt?: undefined;
768
+ model?: undefined;
769
+ hfToken?: undefined;
770
+ temperature?: undefined;
771
+ max_new_tokens?: undefined;
772
+ baseUrl?: undefined;
666
773
  action?: undefined;
667
774
  query?: undefined;
668
775
  id?: undefined;
@@ -672,11 +779,8 @@ export function getToolDefinitions(): ({
672
779
  embeddingBaseUrl?: undefined;
673
780
  topK?: undefined;
674
781
  text?: undefined;
675
- model?: undefined;
676
- baseUrl?: undefined;
677
782
  input?: undefined;
678
783
  transformFunction?: undefined;
679
- prompt?: undefined;
680
784
  type?: undefined;
681
785
  selector?: undefined;
682
786
  jsonPath?: undefined;
@@ -709,6 +813,12 @@ export function getToolDefinitions(): ({
709
813
  type: string;
710
814
  description: string;
711
815
  };
816
+ prompt?: undefined;
817
+ model?: undefined;
818
+ hfToken?: undefined;
819
+ temperature?: undefined;
820
+ max_new_tokens?: undefined;
821
+ baseUrl?: undefined;
712
822
  action?: undefined;
713
823
  content?: undefined;
714
824
  query?: undefined;
@@ -719,11 +829,8 @@ export function getToolDefinitions(): ({
719
829
  embeddingBaseUrl?: undefined;
720
830
  topK?: undefined;
721
831
  text?: undefined;
722
- model?: undefined;
723
- baseUrl?: undefined;
724
832
  input?: undefined;
725
833
  transformFunction?: undefined;
726
- prompt?: undefined;
727
834
  type?: undefined;
728
835
  selector?: undefined;
729
836
  jsonPath?: undefined;
@@ -793,6 +900,12 @@ export function getToolDefinitions(): ({
793
900
  };
794
901
  description: string;
795
902
  };
903
+ prompt?: undefined;
904
+ model?: undefined;
905
+ hfToken?: undefined;
906
+ temperature?: undefined;
907
+ max_new_tokens?: undefined;
908
+ baseUrl?: undefined;
796
909
  action?: undefined;
797
910
  content?: undefined;
798
911
  query?: undefined;
@@ -803,11 +916,8 @@ export function getToolDefinitions(): ({
803
916
  embeddingBaseUrl?: undefined;
804
917
  topK?: undefined;
805
918
  text?: undefined;
806
- model?: undefined;
807
- baseUrl?: undefined;
808
919
  input?: undefined;
809
920
  transformFunction?: undefined;
810
- prompt?: undefined;
811
921
  type?: undefined;
812
922
  selector?: undefined;
813
923
  jsonPath?: undefined;
@@ -836,6 +946,12 @@ export function getToolDefinitions(): ({
836
946
  type: string;
837
947
  description: string;
838
948
  };
949
+ prompt?: undefined;
950
+ model?: undefined;
951
+ hfToken?: undefined;
952
+ temperature?: undefined;
953
+ max_new_tokens?: undefined;
954
+ baseUrl?: undefined;
839
955
  action?: undefined;
840
956
  content?: undefined;
841
957
  query?: undefined;
@@ -846,11 +962,8 @@ export function getToolDefinitions(): ({
846
962
  embeddingBaseUrl?: undefined;
847
963
  topK?: undefined;
848
964
  text?: undefined;
849
- model?: undefined;
850
- baseUrl?: undefined;
851
965
  input?: undefined;
852
966
  transformFunction?: undefined;
853
- prompt?: undefined;
854
967
  type?: undefined;
855
968
  selector?: undefined;
856
969
  jsonPath?: undefined;
@@ -883,6 +996,12 @@ export function getToolDefinitions(): ({
883
996
  type: string;
884
997
  description: string;
885
998
  };
999
+ prompt?: undefined;
1000
+ model?: undefined;
1001
+ hfToken?: undefined;
1002
+ temperature?: undefined;
1003
+ max_new_tokens?: undefined;
1004
+ baseUrl?: undefined;
886
1005
  action?: undefined;
887
1006
  content?: undefined;
888
1007
  query?: undefined;
@@ -893,11 +1012,8 @@ export function getToolDefinitions(): ({
893
1012
  embeddingBaseUrl?: undefined;
894
1013
  topK?: undefined;
895
1014
  text?: undefined;
896
- model?: undefined;
897
- baseUrl?: undefined;
898
1015
  input?: undefined;
899
1016
  transformFunction?: undefined;
900
- prompt?: undefined;
901
1017
  type?: undefined;
902
1018
  selector?: undefined;
903
1019
  jsonPath?: undefined;
@@ -1,5 +1,39 @@
1
1
  export function getToolDefinitions() {
2
2
  return [
3
+ {
4
+ name: "huggingface_llm_reasoning",
5
+ description: "A powerful language model for general reasoning, problem-solving, and generating text, using Hugging Face's OpenAI-compatible router. 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.",
6
+ parameters: {
7
+ type: "object",
8
+ properties: {
9
+ prompt: {
10
+ type: "string",
11
+ description: "The prompt or question to send to the language model."
12
+ },
13
+ model: {
14
+ type: "string",
15
+ description: "The Hugging Face model ID (e.g., 'HuggingFaceH4/zephyr-7b-beta', 'openai/gpt-oss-20b:novita')."
16
+ },
17
+ hfToken: {
18
+ type: "string",
19
+ description: "Your Hugging Face API token."
20
+ },
21
+ temperature: {
22
+ type: "number",
23
+ description: "Optional. Controls randomness. Defaults to 0.7."
24
+ },
25
+ max_new_tokens: {
26
+ type: "number",
27
+ description: "Optional. Maximum number of tokens to generate. Defaults to 500."
28
+ },
29
+ baseUrl: {
30
+ type: "string",
31
+ description: "Optional. The base URL of the Hugging Face router API. Defaults to 'https://router.huggingface.co/v1'."
32
+ }
33
+ },
34
+ required: ["prompt", "model", "hfToken"]
35
+ }
36
+ },
3
37
  {
4
38
  name: "semantic_memory_node",
5
39
  description: "Stores and retrieves text-based memories using vector embeddings for semantic search. Requires a local Ollama server running an embedding model (e.g., 'nomic-embed-text').",
@@ -17,7 +17,13 @@ export class AgentGeminiLLMNode extends GeminiLLMNode {
17
17
  }
18
18
  export class AgentOllamaLLMNode extends OllamaLLMNode {
19
19
  }
20
+ export class AgentHuggingFaceLLMNode extends HuggingFaceLLMNode {
21
+ preparePrompt(shared: any): void;
22
+ execAsync(prepRes: any, shared: any): Promise<{}>;
23
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
24
+ }
20
25
  import { DeepSeekLLMNode } from './llm.js';
21
26
  import { OpenAILLMNode } from './llm.js';
22
27
  import { GeminiLLMNode } from './llm.js';
23
28
  import { OllamaLLMNode } from './llm.js';
29
+ import { HuggingFaceLLMNode } from './llm.js';
@@ -1,4 +1,4 @@
1
- import { DeepSeekLLMNode, OpenAILLMNode, GeminiLLMNode, OllamaLLMNode } from './llm.js';
1
+ import { DeepSeekLLMNode, OpenAILLMNode, GeminiLLMNode, OllamaLLMNode, HuggingFaceLLMNode } from './llm.js';
2
2
  /**
3
3
  * A specialized DeepSeekLLMNode for use within the AgentNode.
4
4
  * It expects the full prompt (conversation history) to be provided directly via setParams.
@@ -218,3 +218,76 @@ export class AgentOllamaLLMNode extends OllamaLLMNode {
218
218
  }
219
219
  }
220
220
  }
221
+ export class AgentHuggingFaceLLMNode extends HuggingFaceLLMNode {
222
+ preparePrompt(shared) {
223
+ const messages = JSON.parse(this.params.prompt);
224
+ // Hugging Face router (OpenAI-compatible) expects a messages array.
225
+ // We'll pass the parsed messages directly.
226
+ this.params.messages = messages;
227
+ }
228
+ async execAsync(prepRes, shared) {
229
+ this.preparePrompt(shared); // Prepare the prompt from shared state
230
+ const { messages, model, hfToken, temperature, max_new_tokens, baseUrl } = this.params;
231
+ if (!messages || messages.length === 0) {
232
+ throw new Error('AgentHuggingFaceLLMNode requires `messages`.');
233
+ }
234
+ if (!model) {
235
+ throw new Error('AgentHuggingFaceLLMNode requires a `model`.');
236
+ }
237
+ if (!hfToken) {
238
+ throw new Error('AgentHuggingFaceLLMNode requires a `hfToken`.');
239
+ }
240
+ const url = `${baseUrl || 'https://router.huggingface.co/v1'}/chat/completions`;
241
+ const headers = {
242
+ 'Content-Type': 'application/json',
243
+ 'Authorization': `Bearer ${hfToken}`,
244
+ };
245
+ const body = JSON.stringify({
246
+ model: model,
247
+ messages: messages,
248
+ temperature: temperature || 0.7,
249
+ max_tokens: max_new_tokens || 500,
250
+ });
251
+ console.log(`[AgentHuggingFace] Sending prompt to ${model} at ${url}...`);
252
+ try {
253
+ const response = await fetch(url, {
254
+ method: 'POST',
255
+ headers: headers,
256
+ body: body,
257
+ });
258
+ if (!response.ok) {
259
+ let errorData;
260
+ try {
261
+ errorData = await response.json();
262
+ }
263
+ catch (e) {
264
+ errorData = await response.text(); // Get raw text if not JSON
265
+ }
266
+ throw new Error(`Hugging Face API error: ${response.status} ${response.statusText} - ${JSON.stringify(errorData)}`);
267
+ }
268
+ const data = await response.json();
269
+ //console.log("HuggingFace Agent Raw Data:", JSON.stringify(data, null, 2)); // Added logging
270
+ let llmResponse = '';
271
+ if (data && data.choices && data.choices.length > 0 && data.choices[0].message && typeof data.choices[0].message.content === 'string') {
272
+ llmResponse = data.choices[0].message.content.trim();
273
+ }
274
+ else if (data && Array.isArray(data) && data[0] && typeof data[0].generated_text === 'string') {
275
+ // Fallback for models that return directly generated_text (e.g., older HF inference API)
276
+ llmResponse = data[0].generated_text.trim();
277
+ }
278
+ else {
279
+ throw new Error('Invalid or unexpected response structure from Hugging Face API.');
280
+ }
281
+ console.log(`[AgentHuggingFace] Received response from ${model}.`);
282
+ return data; // Return the full data object for AgentNode to parse
283
+ }
284
+ catch (error) {
285
+ console.error('AgentHuggingFaceLLMNode: Error during API call:', error);
286
+ throw error;
287
+ }
288
+ }
289
+ async postAsync(shared, prepRes, execRes) {
290
+ shared.llmResponse = execRes; // Store the full LLM response object
291
+ return execRes; // Return the full LLM response object
292
+ }
293
+ }
@@ -12,4 +12,7 @@ export class OllamaLLMNode extends AsyncNode {
12
12
  preparePrompt(shared: any): void;
13
13
  execAsync(prepRes: any, shared: any): Promise<any>;
14
14
  }
15
+ export class HuggingFaceLLMNode extends AsyncNode {
16
+ execAsync(): Promise<any>;
17
+ }
15
18
  import { AsyncNode } from '../qflow.js';
package/dist/nodes/llm.js CHANGED
@@ -159,3 +159,56 @@ export class OllamaLLMNode extends AsyncNode {
159
159
  }
160
160
  }
161
161
  }
162
+ export class HuggingFaceLLMNode extends AsyncNode {
163
+ constructor(maxRetries = 3, wait = 2) {
164
+ super(maxRetries, wait);
165
+ }
166
+ async execAsync() {
167
+ const { prompt, model, hfToken, temperature = 0.7, max_new_tokens = 500, baseUrl = 'https://router.huggingface.co/v1' } = this.params;
168
+ if (!prompt) {
169
+ throw new Error('HuggingFaceLLMNode requires a `prompt`.');
170
+ }
171
+ if (!model) {
172
+ throw new Error('HuggingFaceLLMNode requires a `model` (e.g., "openai/gpt-oss-20b:novita").');
173
+ }
174
+ if (!hfToken) {
175
+ throw new Error('HuggingFaceLLMNode requires a `hfToken` (Hugging Face API token).');
176
+ }
177
+ // Hugging Face router uses OpenAI-compatible API
178
+ const url = `${baseUrl}/chat/completions`;
179
+ const headers = {
180
+ 'Content-Type': 'application/json',
181
+ 'Authorization': `Bearer ${hfToken}`,
182
+ };
183
+ const body = JSON.stringify({
184
+ model: model,
185
+ messages: [{ role: 'user', content: prompt }],
186
+ temperature: temperature,
187
+ max_tokens: max_new_tokens,
188
+ // Add other OpenAI-compatible parameters as needed
189
+ });
190
+ console.log(`[HuggingFace] Sending prompt to ${model} at ${baseUrl}...`);
191
+ try {
192
+ const response = await fetch(url, {
193
+ method: 'POST',
194
+ headers: headers,
195
+ body: body,
196
+ });
197
+ if (!response.ok) {
198
+ const errorData = await response.json();
199
+ throw new Error(`Hugging Face API error: ${response.status} - ${JSON.stringify(errorData)}`);
200
+ }
201
+ const data = await response.json();
202
+ if (!data.choices || data.choices.length === 0 || !data.choices[0].message || typeof data.choices[0].message.content !== 'string') {
203
+ throw new Error('Invalid response structure from Hugging Face API.');
204
+ }
205
+ const llmResponse = data.choices[0].message.content.trim();
206
+ console.log(`[HuggingFace] Received response from ${model}.`);
207
+ return llmResponse;
208
+ }
209
+ catch (error) {
210
+ console.error('HuggingFaceLLMNode: Error during API call:', error);
211
+ throw error;
212
+ }
213
+ }
214
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.21",
3
+ "version": "1.0.22",
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",