n8n-nodes-berget-mk 0.5.2 → 0.5.4

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.
@@ -1,5 +1,28 @@
1
1
  import { type IExecuteFunctions, type ILoadOptionsFunctions, type INodePropertyOptions } from 'n8n-workflow';
2
2
  export declare const BERGET_API_BASE_URL = "https://api.berget.ai/v1";
3
+ /**
4
+ * Loads a LangChain module at call time instead of at module load time.
5
+ *
6
+ * The three sub-nodes (Chat Model, Embeddings Model, Reranker) need
7
+ * `@langchain/openai` / `@langchain/core`, which are declared as real runtime
8
+ * dependencies (see the dependency strategy section in CLAUDE.md). They are
9
+ * still not guaranteed to be present: n8n installs a community package by
10
+ * running `npm install` inside the package's own directory, and if that step
11
+ * does not deliver them, the modules are simply missing on disk.
12
+ *
13
+ * When these were imported at the top of each sub-node file, a missing module
14
+ * threw while n8n's loader was requiring the file, which failed the *entire*
15
+ * package — including the Berget AI action node (chat, image, rerank, speech),
16
+ * which never touches LangChain. Requiring lazily keeps that blast radius to
17
+ * the one sub-node that actually needs the module, and turns a package-wide
18
+ * load failure into a clear error at the point of use.
19
+ *
20
+ * Returns undefined rather than throwing so callers can raise a
21
+ * NodeOperationError carrying their own node context.
22
+ */
23
+ export declare function requireOptionalModule<T>(specifier: string): T | undefined;
24
+ /** Shared guidance appended to the error when a LangChain module is missing. */
25
+ export declare const LANGCHAIN_MISSING_HINT = "This sub-node needs the LangChain packages that ship as dependencies of n8n-nodes-berget-mk, but they were not found on disk. Reinstall the community package in Settings > Community nodes. The other Berget AI nodes are unaffected and continue to work.";
3
26
  export interface BergetModel {
4
27
  id: string;
5
28
  name?: string;
@@ -3,7 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.BERGET_API_BASE_URL = void 0;
6
+ exports.LANGCHAIN_MISSING_HINT = exports.BERGET_API_BASE_URL = void 0;
7
+ exports.requireOptionalModule = requireOptionalModule;
7
8
  exports.fetchBergetModels = fetchBergetModels;
8
9
  exports.loadModelOptions = loadModelOptions;
9
10
  exports.bergetRequest = bergetRequest;
@@ -12,6 +13,37 @@ exports.throwBergetError = throwBergetError;
12
13
  const axios_1 = __importDefault(require("axios"));
13
14
  const n8n_workflow_1 = require("n8n-workflow");
14
15
  exports.BERGET_API_BASE_URL = 'https://api.berget.ai/v1';
16
+ /**
17
+ * Loads a LangChain module at call time instead of at module load time.
18
+ *
19
+ * The three sub-nodes (Chat Model, Embeddings Model, Reranker) need
20
+ * `@langchain/openai` / `@langchain/core`, which are declared as real runtime
21
+ * dependencies (see the dependency strategy section in CLAUDE.md). They are
22
+ * still not guaranteed to be present: n8n installs a community package by
23
+ * running `npm install` inside the package's own directory, and if that step
24
+ * does not deliver them, the modules are simply missing on disk.
25
+ *
26
+ * When these were imported at the top of each sub-node file, a missing module
27
+ * threw while n8n's loader was requiring the file, which failed the *entire*
28
+ * package — including the Berget AI action node (chat, image, rerank, speech),
29
+ * which never touches LangChain. Requiring lazily keeps that blast radius to
30
+ * the one sub-node that actually needs the module, and turns a package-wide
31
+ * load failure into a clear error at the point of use.
32
+ *
33
+ * Returns undefined rather than throwing so callers can raise a
34
+ * NodeOperationError carrying their own node context.
35
+ */
36
+ function requireOptionalModule(specifier) {
37
+ try {
38
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
39
+ return require(specifier);
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
45
+ /** Shared guidance appended to the error when a LangChain module is missing. */
46
+ exports.LANGCHAIN_MISSING_HINT = 'This sub-node needs the LangChain packages that ship as dependencies of n8n-nodes-berget-mk, but they were not found on disk. Reinstall the community package in Settings > Community nodes. The other Berget AI nodes are unaffected and continue to work.';
15
47
  async function fetchBergetModels(context) {
16
48
  var _a, _b;
17
49
  const credentials = await context.getCredentials('bergetAiApi');
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BergetAiChatModel = void 0;
4
- const openai_1 = require("@langchain/openai");
5
4
  const n8n_workflow_1 = require("n8n-workflow");
6
5
  const shared_1 = require("../BergetAi/shared");
7
6
  class BergetAiChatModel {
@@ -145,6 +144,13 @@ class BergetAiChatModel {
145
144
  }
146
145
  async supplyData(itemIndex) {
147
146
  var _a, _b, _c, _d, _e;
147
+ // Required lazily so a missing LangChain install fails only this sub-node
148
+ // instead of the whole package. See requireOptionalModule in shared.ts.
149
+ const langchainOpenAi = (0, shared_1.requireOptionalModule)('@langchain/openai');
150
+ if (!langchainOpenAi) {
151
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Could not load "@langchain/openai"', { description: shared_1.LANGCHAIN_MISSING_HINT });
152
+ }
153
+ const { ChatOpenAI } = langchainOpenAi;
148
154
  const credentials = await this.getCredentials('bergetAiApi');
149
155
  const modelName = this.getNodeParameter('model', itemIndex);
150
156
  const options = this.getNodeParameter('options', itemIndex, {});
@@ -155,7 +161,7 @@ class BergetAiChatModel {
155
161
  if (options.responseFormat && options.responseFormat !== 'text') {
156
162
  modelKwargs.response_format = { type: options.responseFormat };
157
163
  }
158
- const model = new openai_1.ChatOpenAI({
164
+ const model = new ChatOpenAI({
159
165
  apiKey: credentials.apiKey,
160
166
  model: modelName,
161
167
  configuration: {
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BergetAiEmbeddingsModel = void 0;
4
- const openai_1 = require("@langchain/openai");
5
4
  const n8n_workflow_1 = require("n8n-workflow");
6
5
  const shared_1 = require("../BergetAi/shared");
7
6
  class BergetAiEmbeddingsModel {
@@ -92,6 +91,13 @@ class BergetAiEmbeddingsModel {
92
91
  }
93
92
  async supplyData(itemIndex) {
94
93
  var _a, _b, _c;
94
+ // Required lazily so a missing LangChain install fails only this sub-node
95
+ // instead of the whole package. See requireOptionalModule in shared.ts.
96
+ const langchainOpenAi = (0, shared_1.requireOptionalModule)('@langchain/openai');
97
+ if (!langchainOpenAi) {
98
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Could not load "@langchain/openai"', { description: shared_1.LANGCHAIN_MISSING_HINT });
99
+ }
100
+ const { OpenAIEmbeddings } = langchainOpenAi;
95
101
  const credentials = await this.getCredentials('bergetAiApi');
96
102
  const modelName = this.getNodeParameter('model', itemIndex);
97
103
  const options = this.getNodeParameter('options', itemIndex, {});
@@ -101,7 +107,7 @@ class BergetAiEmbeddingsModel {
101
107
  // despite their OpenAPI spec documenting it. The field is kept in the
102
108
  // UI so users can opt in once Berget fixes the backend without a
103
109
  // package update. See CHANGELOG 0.4.8 for details.
104
- const embeddings = new openai_1.OpenAIEmbeddings({
110
+ const embeddings = new OpenAIEmbeddings({
105
111
  apiKey: credentials.apiKey,
106
112
  model: modelName,
107
113
  configuration: {
@@ -4,76 +4,76 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.BergetAiReranker = void 0;
7
- const documents_1 = require("@langchain/core/documents");
8
- const document_compressors_1 = require("@langchain/core/retrievers/document_compressors");
9
7
  const axios_1 = __importDefault(require("axios"));
10
8
  const n8n_workflow_1 = require("n8n-workflow");
11
9
  const shared_1 = require("../BergetAi/shared");
12
10
  /**
13
- * LangChain-compatible document compressor that calls Berget AI's `/v1/rerank`
14
- * endpoint to reorder a list of documents by relevance to a query. Plugs into
15
- * any n8n node that accepts an AiReranker connection type (Vector Store
16
- * retrievers, QA Chain, etc.).
17
- *
18
- * Berget's API returns results with 0-based indices into the input documents
19
- * array. We preserve the original LangChain Document metadata across the round
20
- * trip so downstream consumers don't lose pageContent source references.
11
+ * Builds the reranker instance, resolving its LangChain base class at call
12
+ * time rather than at module load. `BaseDocumentCompressor` has to be a real
13
+ * value to be extended, so the class body lives inside this factory; declaring
14
+ * it at module scope would re-introduce the top-level require that made a
15
+ * missing LangChain install fail the entire package.
21
16
  */
22
- class BergetReranker extends document_compressors_1.BaseDocumentCompressor {
23
- constructor(params) {
24
- super();
25
- this.apiKey = params.apiKey;
26
- this.model = params.model;
27
- this.topN = params.topN;
28
- this.timeoutMs = params.timeoutMs;
29
- }
30
- // LangChain's tracer / callback infrastructure may JSON-serialize this
31
- // instance for logging. ChatOpenAI / OpenAIEmbeddings opt their apiKey
32
- // out via lc_secrets, but BaseDocumentCompressor has no equivalent. We
33
- // override toJSON() to be safe — never let the API key end up in a log.
34
- toJSON() {
35
- return {
36
- lc_namespace: ['berget', 'reranker'],
37
- model: this.model,
38
- topN: this.topN,
39
- timeoutMs: this.timeoutMs,
40
- };
41
- }
42
- async compressDocuments(documents, query, _callbacks) {
43
- var _a, _b, _c;
44
- if (documents.length === 0)
45
- return [];
46
- const documentStrings = documents.map((d) => d.pageContent);
47
- const response = await axios_1.default.post(`${shared_1.BERGET_API_BASE_URL}/rerank`, {
48
- model: this.model,
49
- query,
50
- documents: documentStrings,
51
- top_n: Math.min(this.topN, documents.length),
52
- return_documents: false,
53
- }, {
54
- headers: {
55
- Authorization: `Bearer ${this.apiKey}`,
56
- 'Content-Type': 'application/json',
57
- },
58
- timeout: this.timeoutMs,
59
- });
60
- const payload = (_a = response.data) !== null && _a !== void 0 ? _a : {};
61
- const results = (_c = (_b = payload.results) !== null && _b !== void 0 ? _b : payload.data) !== null && _c !== void 0 ? _c : [];
62
- return results.map((result) => {
63
- var _a, _b, _c, _d;
64
- const original = documents[result.index];
65
- const fallbackText = typeof result.document === 'string'
66
- ? result.document
67
- : (_b = (_a = result.document) === null || _a === void 0 ? void 0 : _a.text) !== null && _b !== void 0 ? _b : '';
68
- return new documents_1.Document({
69
- pageContent: (_c = original === null || original === void 0 ? void 0 : original.pageContent) !== null && _c !== void 0 ? _c : fallbackText,
70
- metadata: {
71
- ...((_d = original === null || original === void 0 ? void 0 : original.metadata) !== null && _d !== void 0 ? _d : {}),
72
- relevance_score: result.relevance_score,
17
+ function createBergetReranker(documentsModule, compressorsModule, params) {
18
+ const { Document } = documentsModule;
19
+ const { BaseDocumentCompressor } = compressorsModule;
20
+ class BergetReranker extends BaseDocumentCompressor {
21
+ constructor(params) {
22
+ super();
23
+ this.apiKey = params.apiKey;
24
+ this.model = params.model;
25
+ this.topN = params.topN;
26
+ this.timeoutMs = params.timeoutMs;
27
+ }
28
+ // LangChain's tracer / callback infrastructure may JSON-serialize this
29
+ // instance for logging. ChatOpenAI / OpenAIEmbeddings opt their apiKey
30
+ // out via lc_secrets, but BaseDocumentCompressor has no equivalent. We
31
+ // override toJSON() to be safe — never let the API key end up in a log.
32
+ toJSON() {
33
+ return {
34
+ lc_namespace: ['berget', 'reranker'],
35
+ model: this.model,
36
+ topN: this.topN,
37
+ timeoutMs: this.timeoutMs,
38
+ };
39
+ }
40
+ async compressDocuments(documents, query, _callbacks) {
41
+ var _a, _b, _c;
42
+ if (documents.length === 0)
43
+ return [];
44
+ const documentStrings = documents.map((d) => d.pageContent);
45
+ const response = await axios_1.default.post(`${shared_1.BERGET_API_BASE_URL}/rerank`, {
46
+ model: this.model,
47
+ query,
48
+ documents: documentStrings,
49
+ top_n: Math.min(this.topN, documents.length),
50
+ return_documents: false,
51
+ }, {
52
+ headers: {
53
+ Authorization: `Bearer ${this.apiKey}`,
54
+ 'Content-Type': 'application/json',
73
55
  },
56
+ timeout: this.timeoutMs,
74
57
  });
75
- });
58
+ const payload = (_a = response.data) !== null && _a !== void 0 ? _a : {};
59
+ const results = (_c = (_b = payload.results) !== null && _b !== void 0 ? _b : payload.data) !== null && _c !== void 0 ? _c : [];
60
+ return results.map((result) => {
61
+ var _a, _b, _c, _d;
62
+ const original = documents[result.index];
63
+ const fallbackText = typeof result.document === 'string'
64
+ ? result.document
65
+ : (_b = (_a = result.document) === null || _a === void 0 ? void 0 : _a.text) !== null && _b !== void 0 ? _b : '';
66
+ return new Document({
67
+ pageContent: (_c = original === null || original === void 0 ? void 0 : original.pageContent) !== null && _c !== void 0 ? _c : fallbackText,
68
+ metadata: {
69
+ ...((_d = original === null || original === void 0 ? void 0 : original.metadata) !== null && _d !== void 0 ? _d : {}),
70
+ relevance_score: result.relevance_score,
71
+ },
72
+ });
73
+ });
74
+ }
76
75
  }
76
+ return new BergetReranker(params);
77
77
  }
78
78
  class BergetAiReranker {
79
79
  constructor() {
@@ -152,7 +152,16 @@ class BergetAiReranker {
152
152
  const model = this.getNodeParameter('model', itemIndex);
153
153
  const topN = this.getNodeParameter('topN', itemIndex, 3);
154
154
  const options = this.getNodeParameter('options', itemIndex, {});
155
- const reranker = new BergetReranker({
155
+ // Required lazily so a missing LangChain install fails only this sub-node
156
+ // instead of the whole package. See requireOptionalModule in shared.ts.
157
+ const documentsModule = (0, shared_1.requireOptionalModule)('@langchain/core/documents');
158
+ const compressorsModule = (0, shared_1.requireOptionalModule)('@langchain/core/retrievers/document_compressors');
159
+ if (!documentsModule || !compressorsModule) {
160
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Could not load "@langchain/core"', {
161
+ description: shared_1.LANGCHAIN_MISSING_HINT,
162
+ });
163
+ }
164
+ const reranker = createBergetReranker(documentsModule, compressorsModule, {
156
165
  apiKey: credentials.apiKey,
157
166
  model,
158
167
  topN,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "n8n-nodes-berget-mk",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
4
4
  "description": "n8n community node for Berget AI. Multi-resource action node (chat, image analysis, rerank, speech-to-text) plus Chat Model, Embeddings Model, and Reranker sub-nodes that plug into n8n's built-in AI Agent and Vector Store nodes.",
5
5
  "keywords": [
6
6
  "n8n-community-node-package",
@@ -27,7 +27,6 @@
27
27
  "publishConfig": {
28
28
  "access": "public"
29
29
  },
30
- "main": "index.js",
31
30
  "scripts": {
32
31
  "build": "rm -rf dist && tsc && node scripts/copy-assets.js",
33
32
  "dev": "tsc --watch",
@@ -37,30 +36,22 @@
37
36
  "dist"
38
37
  ],
39
38
  "dependencies": {
39
+ "@langchain/core": "^1.1.39",
40
+ "@langchain/openai": "^1.4.3",
40
41
  "axios": "^1.19.0",
41
42
  "form-data": "^4.0.6"
42
43
  },
43
44
  "devDependencies": {
44
- "@langchain/core": "^1.1.39",
45
- "@langchain/openai": "^1.4.3",
46
45
  "@types/node": "^20.11.0",
47
46
  "n8n-workflow": "^2.16.0",
48
47
  "typescript": "^5.3.0"
49
48
  },
50
49
  "peerDependencies": {
51
- "@langchain/core": "*",
52
- "@langchain/openai": "*",
53
50
  "n8n-workflow": "*"
54
51
  },
55
52
  "peerDependenciesMeta": {
56
53
  "n8n-workflow": {
57
54
  "optional": true
58
- },
59
- "@langchain/core": {
60
- "optional": true
61
- },
62
- "@langchain/openai": {
63
- "optional": true
64
55
  }
65
56
  },
66
57
  "overrides": {