n8n-nodes-berget-mk 0.5.3 → 0.5.5

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
@@ -4,7 +4,7 @@ n8n community nodes for [Berget AI](https://berget.ai), packaged as a single ins
4
4
 
5
5
  Four nodes:
6
6
 
7
- - **Berget AI** — multi-resource action node for one-shot calls. Resources: **Chat** (completions, classification, JSON Schema structured output, reasoning effort for GPT-OSS / GLM-4.7 / etc.), **Image Analysis** (vision-capable models), **Rerank** (document reranking), and **Speech to Text** (Swedish-tuned KB-Whisper, with optional diarization and word-level alignment). Can also be exposed as a tool to an AI Agent. (OCR is temporarily hidden — see [CHANGELOG.md](CHANGELOG.md) for `0.4.4` for details.)
7
+ - **Berget AI** — multi-resource action node for one-shot calls. Resources: **Chat** (completions, classification, JSON Schema structured output, reasoning effort for reasoning-capable models), **Image Analysis** (vision-capable models), **Rerank** (document reranking), and **Speech to Text** (Swedish-tuned KB-Whisper, with optional diarization and word-level alignment). Can also be exposed as a tool to an AI Agent. (OCR is temporarily hidden — see [CHANGELOG.md](CHANGELOG.md) for `0.4.4` and `0.5.5` for details.)
8
8
  - **Berget AI Chat Model** — sub-node that plugs into n8n's built-in **AI Agent**, **Basic LLM Chain**, and other LangChain-based nodes. Exposes reasoning effort and the full standard LLM parameter set.
9
9
  - **Berget AI Embeddings Model** — sub-node that plugs into n8n's **Vector Store** nodes (Supabase, Qdrant, Pinecone, PGVector, etc.) and **Question and Answer Chain**.
10
10
  - **Berget AI Reranker** — sub-node that plugs into Vector Store retrievers via the `AiReranker` connection, reordering candidates by relevance before they reach the agent or chain.
@@ -19,7 +19,9 @@ In n8n: **Settings → Community Nodes → Install** and enter:
19
19
  n8n-nodes-berget-mk
20
20
  ```
21
21
 
22
- Then add a **Berget AI API** credential with your API key from [berget.ai](https://berget.ai).
22
+ Then add a **Berget AI API** credential with your API key from [berget.ai](https://berget.ai). The credential's **Test** checks the key against Berget for real; it costs no tokens.
23
+
24
+ Requires Node.js 22 or later, which current n8n releases require anyway.
23
25
 
24
26
  ## Typical workflows
25
27
 
@@ -29,7 +31,7 @@ Then add a **Berget AI API** credential with your API key from [berget.ai](https
29
31
 
30
32
  For classification or structured extraction tasks, set **Options → Response Format = JSON Object** or **JSON Schema** (with a schema you provide). The model is forced to return parseable JSON — no regex scraping of free-form text. The parsed JSON is exposed as a top-level **`output`** field on the node's response, so a downstream **IF**, **Set**, or **Switch** node can reference its properties directly with expressions like `{{ $json.output.category }}` or `{{ $json.output.contains }}` — no extra parse step needed.
31
33
 
32
- For reasoning-capable models (`openai/gpt-oss-120b`, `zai-org/GLM-4.7-FP8`, etc.), set **Options → Reasoning Effort = High** to crank up the model's thinking budget. The parameter is silently ignored by non-reasoning models, so it's safe to leave on. (Berget does not currently flag reasoning-capable models in `/v1/models`, so the model dropdown is not filtered — pick the reasoning model yourself.)
34
+ For reasoning-capable models, set **Options → Reasoning Effort = High** to crank up the model's thinking budget. The parameter is silently ignored by non-reasoning models, so it's safe to leave on. The model's reasoning text comes back next to the answer, in `choices[0].message.reasoning_content`. (Berget does not currently flag reasoning-capable models in `/v1/models`, so the model dropdown is not filtered — pick the reasoning model yourself.)
33
35
 
34
36
  ### Agent with tools and memory
35
37
 
@@ -55,10 +57,12 @@ For reasoning-capable models (`openai/gpt-oss-120b`, `zai-org/GLM-4.7-FP8`, etc.
55
57
 
56
58
  1. Drop **Berget AI** onto the canvas, pick Resource = **Speech to Text**.
57
59
  2. Provide the binary input data from a Form Trigger or HTTP Request.
58
- 3. Optional: enable **Options → Diarize (Speaker Identification)** — the response will include a `speaker_transcript` field formatted as readable per-speaker paragraphs (`SPEAKER_00:\n...\n\nSPEAKER_01:\n...`), alongside the raw segment-level timestamps and word-level data.
60
+ 3. Optional: enable **Options → Diarize (Speaker Identification)** — the response will include a `speaker_transcript` field formatted as readable per-speaker paragraphs (`SPEAKER_00:\n...\n\nSPEAKER_01:\n...`), alongside the raw segment-level timestamps and word-level data. The Whisper-based models support this; `klang/pianissimo` does not.
59
61
  4. Optional: enable **Word-Level Alignment** for per-word timestamps useful in subtitle generation.
60
62
  5. Optional: add **Hotwords** (comma-separated) for proper nouns and domain vocabulary.
61
63
 
64
+ Whichever **Response Format** you pick, the transcript is at `{{ $json.text }}` — for **Text**, **SRT** and **VTT** that field holds the plain-text, SRT or VTT output.
65
+
62
66
  ## Changelog
63
67
 
64
68
  See [CHANGELOG.md](CHANGELOG.md) for what's changed between releases.
@@ -1,9 +1,8 @@
1
- import { IAuthenticateGeneric, ICredentialTestRequest, ICredentialType, INodeProperties } from 'n8n-workflow';
1
+ import { IAuthenticateGeneric, ICredentialType, INodeProperties } from 'n8n-workflow';
2
2
  export declare class BergetAiApi implements ICredentialType {
3
3
  name: string;
4
4
  displayName: string;
5
5
  documentationUrl: string;
6
6
  properties: INodeProperties[];
7
7
  authenticate: IAuthenticateGeneric;
8
- test: ICredentialTestRequest;
9
8
  }
@@ -25,13 +25,16 @@ class BergetAiApi {
25
25
  },
26
26
  },
27
27
  };
28
- this.test = {
29
- request: {
30
- baseURL: 'https://api.berget.ai/v1',
31
- url: '/models',
32
- method: 'GET',
33
- },
34
- };
28
+ // There is deliberately no `test` request here. Through 0.5.4 the test was
29
+ // `GET /v1/models`, but that endpoint is public: it answers HTTP 200 for
30
+ // any key, or none, so n8n reported "Connection tested successfully" no
31
+ // matter what was typed. A declarative test request cannot do better,
32
+ // because the only free way to check a key is a POST that a valid key
33
+ // answers with HTTP 400, and n8n counts every non-2xx as a failure.
34
+ //
35
+ // The test lives in the Berget AI node instead: `testedBy` on its
36
+ // credentials entry points at `methods.credentialTest.bergetAiApiTest`,
37
+ // which calls testBergetApiKey() in nodes/BergetAi/shared.ts.
35
38
  }
36
39
  }
37
40
  exports.BergetAiApi = BergetAiApi;
@@ -1,7 +1,10 @@
1
- import { type IExecuteFunctions, type ILoadOptionsFunctions, type INodeExecutionData, type INodePropertyOptions, type INodeType, type INodeTypeDescription } from 'n8n-workflow';
1
+ import { type ICredentialsDecrypted, type ICredentialTestFunctions, type IExecuteFunctions, type ILoadOptionsFunctions, type INodeCredentialTestResult, type INodeExecutionData, type INodePropertyOptions, type INodeType, type INodeTypeDescription } from 'n8n-workflow';
2
2
  export declare class BergetAi implements INodeType {
3
3
  description: INodeTypeDescription;
4
4
  methods: {
5
+ credentialTest: {
6
+ bergetAiApiTest(this: ICredentialTestFunctions, credential: ICredentialsDecrypted): Promise<INodeCredentialTestResult>;
7
+ };
5
8
  loadOptions: {
6
9
  getChatModels(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]>;
7
10
  getVisionModels(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]>;
@@ -14,6 +14,17 @@ const shared_1 = require("./shared");
14
14
  // ---------------------------------------------------------------------------
15
15
  // OCR is temporarily hidden from the UI (since v0.4.4, 2026-04-10).
16
16
  //
17
+ // UPDATE 2026-11-30: the reason below no longer holds. Berget has rebuilt OCR
18
+ // and it works again: sync /v1/ocr answers HTTP 200 in about two seconds, and
19
+ // the async submit + poll flow completes with the exact body ocr.ts sends,
20
+ // for both URLs and base64 data URIs. The resource is still hidden only
21
+ // because re-enabling it is more than the four uncomments described here:
22
+ // the request options changed (`ocrMethod` and `includeImages` are gone from
23
+ // the spec and are ignored; `query` for focused OCR and `options.doOcr` are
24
+ // new), so ocr.ts should be brought in line first. See CHANGELOG 0.5.5.
25
+ //
26
+ // Original note:
27
+ //
17
28
  // Why: Berget AI removed OCR from their public pricing/models page, and the
18
29
  // sync /v1/ocr endpoint returns HTTP 500 OCR_SERVICE_ERROR on every request.
19
30
  // Async submissions are accepted but jobs sit in 'processing' indefinitely.
@@ -55,6 +66,10 @@ class BergetAi {
55
66
  {
56
67
  name: 'bergetAiApi',
57
68
  required: true,
69
+ // The credential is tested by methods.credentialTest below rather
70
+ // than by a `test` request on the credential class, because no GET
71
+ // endpoint on Berget's API can tell a valid key from an invalid one.
72
+ testedBy: 'bergetAiApiTest',
58
73
  },
59
74
  ],
60
75
  inputs: [n8n_workflow_1.NodeConnectionTypes.Main],
@@ -104,6 +119,17 @@ class BergetAi {
104
119
  ],
105
120
  };
106
121
  this.methods = {
122
+ credentialTest: {
123
+ async bergetAiApiTest(credential) {
124
+ var _a;
125
+ const apiKey = (_a = credential.data) === null || _a === void 0 ? void 0 : _a.apiKey;
126
+ if (typeof apiKey !== 'string' || apiKey.trim() === '') {
127
+ return { status: 'Error', message: 'No API key set' };
128
+ }
129
+ const { ok, message } = await (0, shared_1.testBergetApiKey)(apiKey);
130
+ return { status: ok ? 'OK' : 'Error', message };
131
+ },
132
+ },
107
133
  loadOptions: {
108
134
  async getChatModels() {
109
135
  return (0, shared_1.loadModelOptions)(this, (m) => m.model_type === 'text');
@@ -152,7 +178,10 @@ class BergetAi {
152
178
  pairedItem: { item: i },
153
179
  });
154
180
  }
155
- catch (error) {
181
+ catch (caught) {
182
+ // A raw axios error carries the API key in its request config and
183
+ // must never reach n8n. See toSafeError in shared.ts.
184
+ const error = (0, shared_1.toNodeError)(this, caught, i);
156
185
  if (this.continueOnFail()) {
157
186
  returnData.push({
158
187
  json: {
@@ -84,7 +84,7 @@ exports.chatProperties = [
84
84
  { name: 'High', value: 'high', description: 'Favor accuracy, use more reasoning tokens' },
85
85
  ],
86
86
  default: 'medium',
87
- description: 'Controls how much thinking a reasoning-capable model performs (GPT-OSS, GLM-4.7, DeepSeek R1, etc.). Berget does not flag reasoning-capable models in /v1/models, so the dropdown is not filtered — pick a reasoning model yourself. The parameter is silently ignored by non-reasoning models.',
87
+ description: 'Controls how much thinking a reasoning-capable model performs. Berget does not flag reasoning-capable models in /v1/models, so the dropdown is not filtered — pick a reasoning model yourself. The parameter is silently ignored by non-reasoning models. The reasoning text is returned next to the answer, in choices[0].message.reasoning_content.',
88
88
  },
89
89
  {
90
90
  displayName: 'Response Format',
@@ -137,7 +137,8 @@ function sleep(ms) {
137
137
  return new Promise((resolve) => setTimeout(resolve, ms));
138
138
  }
139
139
  async function executeOcr(context, itemIndex) {
140
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
140
+ var _a, _b, _c, _d;
141
+ var _e, _f, _g, _h, _j, _k, _l, _m, _o;
141
142
  const credentials = await context.getCredentials('bergetAiApi');
142
143
  const apiKey = credentials.apiKey;
143
144
  const documentType = context.getNodeParameter('ocrDocumentType', itemIndex);
@@ -159,10 +160,10 @@ async function executeOcr(context, itemIndex) {
159
160
  document: { url: documentUrl, type: 'document' },
160
161
  async: true,
161
162
  options: {
162
- outputFormat: (_a = options.outputFormat) !== null && _a !== void 0 ? _a : 'md',
163
- tableMode: (_b = options.tableMode) !== null && _b !== void 0 ? _b : 'accurate',
164
- ocrMethod: (_c = options.ocrMethod) !== null && _c !== void 0 ? _c : 'easyocr',
165
- includeImages: (_d = options.includeImages) !== null && _d !== void 0 ? _d : false,
163
+ outputFormat: (_e = options.outputFormat) !== null && _e !== void 0 ? _e : 'md',
164
+ tableMode: (_f = options.tableMode) !== null && _f !== void 0 ? _f : 'accurate',
165
+ ocrMethod: (_g = options.ocrMethod) !== null && _g !== void 0 ? _g : 'easyocr',
166
+ includeImages: (_h = options.includeImages) !== null && _h !== void 0 ? _h : false,
166
167
  },
167
168
  };
168
169
  const submission = await (0, shared_1.bergetRequest)(apiKey, 'POST', '/ocr', requestBody);
@@ -190,14 +191,14 @@ async function executeOcr(context, itemIndex) {
190
191
  return {
191
192
  taskId,
192
193
  resultUrl,
193
- status: (_e = submissionData.status) !== null && _e !== void 0 ? _e : 'pending',
194
+ status: (_j = submissionData.status) !== null && _j !== void 0 ? _j : 'pending',
194
195
  processing_mode: 'asynchronous',
195
196
  message: 'Document processing started. Use the taskId with an HTTP Request node against resultUrl to retrieve the extracted content later.',
196
197
  };
197
198
  }
198
199
  // Poll loop.
199
- const timeoutSeconds = (_f = options.pollingTimeoutSeconds) !== null && _f !== void 0 ? _f : DEFAULT_POLLING_TIMEOUT_SECONDS;
200
- const intervalSeconds = Math.max((_g = options.pollingIntervalSeconds) !== null && _g !== void 0 ? _g : DEFAULT_POLLING_INTERVAL_SECONDS, 1);
200
+ const timeoutSeconds = (_k = options.pollingTimeoutSeconds) !== null && _k !== void 0 ? _k : DEFAULT_POLLING_TIMEOUT_SECONDS;
201
+ const intervalSeconds = Math.max((_l = options.pollingIntervalSeconds) !== null && _l !== void 0 ? _l : DEFAULT_POLLING_INTERVAL_SECONDS, 1);
201
202
  const deadline = Date.now() + timeoutSeconds * 1000;
202
203
  while (Date.now() < deadline) {
203
204
  const poll = await (0, shared_1.bergetRequest)(apiKey, 'GET', `/ocr/result/${encodeURIComponent(taskId)}`);
@@ -217,14 +218,14 @@ async function executeOcr(context, itemIndex) {
217
218
  // { error: { message: 'OCR job is still processing', type: 'OCR_JOB_PROCESSING', param: { status, retryAfter } } }
218
219
  // If status is 'failed', surface that as an error instead of looping.
219
220
  const d = poll.data;
220
- const observedStatus = (_h = d.status) !== null && _h !== void 0 ? _h : (_k = (_j = d.error) === null || _j === void 0 ? void 0 : _j.param) === null || _k === void 0 ? void 0 : _k.status;
221
+ const observedStatus = (_m = d.status) !== null && _m !== void 0 ? _m : (_b = (_a = d.error) === null || _a === void 0 ? void 0 : _a.param) === null || _b === void 0 ? void 0 : _b.status;
221
222
  if (observedStatus === 'failed') {
222
223
  (0, shared_1.throwBergetError)(context, itemIndex, 'OCR', 202, poll.data, ` — taskId: ${taskId}`);
223
224
  }
224
225
  // Honor the server's retryAfter hint (milliseconds). If shorter than
225
226
  // the user-configured floor, stick with the floor. Cap at the
226
227
  // remaining deadline so we don't oversleep past the timeout.
227
- const serverHintMs = (_l = d.retryAfter) !== null && _l !== void 0 ? _l : (_o = (_m = d.error) === null || _m === void 0 ? void 0 : _m.param) === null || _o === void 0 ? void 0 : _o.retryAfter;
228
+ const serverHintMs = (_o = d.retryAfter) !== null && _o !== void 0 ? _o : (_d = (_c = d.error) === null || _c === void 0 ? void 0 : _c.param) === null || _d === void 0 ? void 0 : _d.retryAfter;
228
229
  const minMs = intervalSeconds * 1000;
229
230
  const remainingMs = Math.max(0, deadline - Date.now());
230
231
  const waitMs = Math.min(Math.max(serverHintMs !== null && serverHintMs !== void 0 ? serverHintMs : minMs, minMs), remainingMs);
@@ -79,7 +79,7 @@ exports.rerankProperties = [
79
79
  name: 'return_documents',
80
80
  type: 'boolean',
81
81
  default: true,
82
- description: 'Whether to include the document text in the response',
82
+ description: 'Whether to include the document text in the response. As of 2026-11 Berget includes it regardless of this setting, so turning it off currently has no effect.',
83
83
  },
84
84
  ],
85
85
  ...showForRerank,
@@ -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;
@@ -15,7 +38,65 @@ export interface BergetModel {
15
38
  streaming?: boolean;
16
39
  };
17
40
  }
41
+ /**
42
+ * Raised when a request to Berget could not be completed. Carries a message
43
+ * and nothing else, which is what makes it safe for n8n to store — see
44
+ * toSafeError().
45
+ */
46
+ export declare class BergetRequestError extends Error {
47
+ constructor(message: string);
48
+ }
49
+ /**
50
+ * Convert anything thrown while calling Berget into an error that is safe to
51
+ * hand to n8n. Every axios call in this package must go through this.
52
+ *
53
+ * axios rejects with an AxiosError whose own enumerable properties include
54
+ * `config` and `request`, and `config.headers.Authorization` is the user's
55
+ * API key. Older n8n (before 2.37.0, bar the late 2.35.x and 2.36.x patch
56
+ * releases) stores an error thrown by a node by spreading it
57
+ * (`{ ...error, message, stack }` in workflow-execute.ts), which copies those
58
+ * properties into the saved execution, where anyone who can open the
59
+ * execution can read the key. Wrapping the AxiosError in a NodeOperationError
60
+ * does not help: the original is kept as `cause` and serialised along with it.
61
+ *
62
+ * So the AxiosError itself must never leave this package. A fresh error is
63
+ * built from the parts that are safe to show: the HTTP status and Berget's
64
+ * error body when there was a response, otherwise the network error code.
65
+ * Anything that is not an axios error is returned unchanged.
66
+ */
67
+ export declare function toSafeError(error: unknown, resourceLabel?: string): Error;
68
+ /**
69
+ * Last line of defence in a node's execute(): turns a request failure into a
70
+ * NodeOperationError so n8n shows it like any other node error. Built from the
71
+ * message string, never from the error object, so no `cause` is retained.
72
+ * Errors that did not come from a Berget request pass through untouched.
73
+ */
74
+ export declare function toNodeError(context: IExecuteFunctions, error: unknown, itemIndex: number): unknown;
18
75
  export declare function fetchBergetModels(context: ILoadOptionsFunctions): Promise<BergetModel[]>;
76
+ /**
77
+ * Check an API key against Berget without spending any tokens.
78
+ *
79
+ * `GET /v1/models` is public: it answers HTTP 200 with no key or a made-up
80
+ * key, so it cannot tell a good key from a bad one. The POST endpoints check
81
+ * the key before they validate the body, so an empty body is a free probe
82
+ * (verified 2026-11-30):
83
+ *
84
+ * valid key -> 400 VALIDATION_ERROR (accepted, then the empty body is rejected)
85
+ * unknown `sk_ber_` key -> 402 WALLET_NOT_SETUP
86
+ * not shaped like a key -> 401 invalid_token
87
+ * no key -> 401 missing_auth
88
+ *
89
+ * This catches a wrong, revoked or mangled key. It is not a guarantee that
90
+ * every character of the key was checked: that is up to Berget.
91
+ *
92
+ * If Berget ever validates the body first, every key gets a 400 and this
93
+ * reports OK for all of them, which is the behaviour it replaces. It cannot
94
+ * start rejecting good keys.
95
+ */
96
+ export declare function testBergetApiKey(apiKey: string): Promise<{
97
+ ok: boolean;
98
+ message: string;
99
+ }>;
19
100
  export declare function loadModelOptions(context: ILoadOptionsFunctions, filter: (model: BergetModel) => boolean): Promise<INodePropertyOptions[]>;
20
101
  export declare function bergetRequest(apiKey: string, method: 'GET' | 'POST', path: string, body?: unknown, extraHeaders?: Record<string, string>): Promise<{
21
102
  status: number;
@@ -3,8 +3,12 @@ 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.BergetRequestError = exports.LANGCHAIN_MISSING_HINT = exports.BERGET_API_BASE_URL = void 0;
7
+ exports.requireOptionalModule = requireOptionalModule;
8
+ exports.toSafeError = toSafeError;
9
+ exports.toNodeError = toNodeError;
7
10
  exports.fetchBergetModels = fetchBergetModels;
11
+ exports.testBergetApiKey = testBergetApiKey;
8
12
  exports.loadModelOptions = loadModelOptions;
9
13
  exports.bergetRequest = bergetRequest;
10
14
  exports.formatBergetError = formatBergetError;
@@ -12,16 +16,148 @@ exports.throwBergetError = throwBergetError;
12
16
  const axios_1 = __importDefault(require("axios"));
13
17
  const n8n_workflow_1 = require("n8n-workflow");
14
18
  exports.BERGET_API_BASE_URL = 'https://api.berget.ai/v1';
19
+ /**
20
+ * Loads a LangChain module at call time instead of at module load time.
21
+ *
22
+ * The three sub-nodes (Chat Model, Embeddings Model, Reranker) need
23
+ * `@langchain/openai` / `@langchain/core`, which are declared as real runtime
24
+ * dependencies (see the dependency strategy section in CLAUDE.md). They are
25
+ * still not guaranteed to be present: n8n installs a community package by
26
+ * running `npm install` inside the package's own directory, and if that step
27
+ * does not deliver them, the modules are simply missing on disk.
28
+ *
29
+ * When these were imported at the top of each sub-node file, a missing module
30
+ * threw while n8n's loader was requiring the file, which failed the *entire*
31
+ * package — including the Berget AI action node (chat, image, rerank, speech),
32
+ * which never touches LangChain. Requiring lazily keeps that blast radius to
33
+ * the one sub-node that actually needs the module, and turns a package-wide
34
+ * load failure into a clear error at the point of use.
35
+ *
36
+ * Returns undefined rather than throwing so callers can raise a
37
+ * NodeOperationError carrying their own node context.
38
+ */
39
+ function requireOptionalModule(specifier) {
40
+ try {
41
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
42
+ return require(specifier);
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ }
48
+ /** Shared guidance appended to the error when a LangChain module is missing. */
49
+ 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.';
50
+ /**
51
+ * Raised when a request to Berget could not be completed. Carries a message
52
+ * and nothing else, which is what makes it safe for n8n to store — see
53
+ * toSafeError().
54
+ */
55
+ class BergetRequestError extends Error {
56
+ constructor(message) {
57
+ super(message);
58
+ this.name = 'BergetRequestError';
59
+ }
60
+ }
61
+ exports.BergetRequestError = BergetRequestError;
62
+ /**
63
+ * Convert anything thrown while calling Berget into an error that is safe to
64
+ * hand to n8n. Every axios call in this package must go through this.
65
+ *
66
+ * axios rejects with an AxiosError whose own enumerable properties include
67
+ * `config` and `request`, and `config.headers.Authorization` is the user's
68
+ * API key. Older n8n (before 2.37.0, bar the late 2.35.x and 2.36.x patch
69
+ * releases) stores an error thrown by a node by spreading it
70
+ * (`{ ...error, message, stack }` in workflow-execute.ts), which copies those
71
+ * properties into the saved execution, where anyone who can open the
72
+ * execution can read the key. Wrapping the AxiosError in a NodeOperationError
73
+ * does not help: the original is kept as `cause` and serialised along with it.
74
+ *
75
+ * So the AxiosError itself must never leave this package. A fresh error is
76
+ * built from the parts that are safe to show: the HTTP status and Berget's
77
+ * error body when there was a response, otherwise the network error code.
78
+ * Anything that is not an axios error is returned unchanged.
79
+ */
80
+ function toSafeError(error, resourceLabel = 'request') {
81
+ if (axios_1.default.isAxiosError(error)) {
82
+ if (error.response) {
83
+ return new BergetRequestError(formatBergetError(resourceLabel, error.response.status, error.response.data));
84
+ }
85
+ const code = error.code ? ` (${error.code})` : '';
86
+ return new BergetRequestError(`Berget AI ${resourceLabel} error: could not reach the Berget API${code} — ${error.message}`);
87
+ }
88
+ return error instanceof Error ? error : new Error(String(error));
89
+ }
90
+ /**
91
+ * Last line of defence in a node's execute(): turns a request failure into a
92
+ * NodeOperationError so n8n shows it like any other node error. Built from the
93
+ * message string, never from the error object, so no `cause` is retained.
94
+ * Errors that did not come from a Berget request pass through untouched.
95
+ */
96
+ function toNodeError(context, error, itemIndex) {
97
+ if (error instanceof BergetRequestError || axios_1.default.isAxiosError(error)) {
98
+ return new n8n_workflow_1.NodeOperationError(context.getNode(), toSafeError(error).message, { itemIndex });
99
+ }
100
+ return error;
101
+ }
15
102
  async function fetchBergetModels(context) {
16
- var _a, _b;
103
+ var _a;
104
+ var _b;
17
105
  const credentials = await context.getCredentials('bergetAiApi');
18
- const response = await axios_1.default.get(`${exports.BERGET_API_BASE_URL}/models`, {
19
- headers: {
20
- Authorization: `Bearer ${credentials.apiKey}`,
21
- 'Content-Type': 'application/json',
22
- },
23
- });
24
- return ((_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : []);
106
+ try {
107
+ const response = await axios_1.default.get(`${exports.BERGET_API_BASE_URL}/models`, {
108
+ headers: {
109
+ Authorization: `Bearer ${credentials.apiKey}`,
110
+ 'Content-Type': 'application/json',
111
+ },
112
+ });
113
+ return ((_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : []);
114
+ }
115
+ catch (error) {
116
+ throw toSafeError(error, 'model list');
117
+ }
118
+ }
119
+ /**
120
+ * Check an API key against Berget without spending any tokens.
121
+ *
122
+ * `GET /v1/models` is public: it answers HTTP 200 with no key or a made-up
123
+ * key, so it cannot tell a good key from a bad one. The POST endpoints check
124
+ * the key before they validate the body, so an empty body is a free probe
125
+ * (verified 2026-11-30):
126
+ *
127
+ * valid key -> 400 VALIDATION_ERROR (accepted, then the empty body is rejected)
128
+ * unknown `sk_ber_` key -> 402 WALLET_NOT_SETUP
129
+ * not shaped like a key -> 401 invalid_token
130
+ * no key -> 401 missing_auth
131
+ *
132
+ * This catches a wrong, revoked or mangled key. It is not a guarantee that
133
+ * every character of the key was checked: that is up to Berget.
134
+ *
135
+ * If Berget ever validates the body first, every key gets a 400 and this
136
+ * reports OK for all of them, which is the behaviour it replaces. It cannot
137
+ * start rejecting good keys.
138
+ */
139
+ async function testBergetApiKey(apiKey) {
140
+ let status;
141
+ let data;
142
+ try {
143
+ const response = await axios_1.default.post(`${exports.BERGET_API_BASE_URL}/chat/completions`, {}, {
144
+ headers: {
145
+ Authorization: `Bearer ${apiKey}`,
146
+ 'Content-Type': 'application/json',
147
+ },
148
+ validateStatus: () => true,
149
+ timeout: 15000,
150
+ });
151
+ status = response.status;
152
+ data = response.data;
153
+ }
154
+ catch (error) {
155
+ return { ok: false, message: toSafeError(error, 'credential test').message };
156
+ }
157
+ if ((status >= 200 && status < 300) || status === 400 || status === 422) {
158
+ return { ok: true, message: 'Connection successful' };
159
+ }
160
+ return { ok: false, message: formatBergetError('credential test', status, data) };
25
161
  }
26
162
  async function loadModelOptions(context, filter) {
27
163
  const models = await fetchBergetModels(context);
@@ -34,18 +170,25 @@ async function loadModelOptions(context, filter) {
34
170
  .sort((a, b) => a.name.localeCompare(b.name));
35
171
  }
36
172
  async function bergetRequest(apiKey, method, path, body, extraHeaders) {
37
- const response = await axios_1.default.request({
38
- method,
39
- url: `${exports.BERGET_API_BASE_URL}${path}`,
40
- data: body,
41
- headers: {
42
- Authorization: `Bearer ${apiKey}`,
43
- 'Content-Type': 'application/json',
44
- ...extraHeaders,
45
- },
46
- validateStatus: () => true,
47
- });
48
- return { status: response.status, data: response.data };
173
+ try {
174
+ const response = await axios_1.default.request({
175
+ method,
176
+ url: `${exports.BERGET_API_BASE_URL}${path}`,
177
+ data: body,
178
+ headers: {
179
+ Authorization: `Bearer ${apiKey}`,
180
+ 'Content-Type': 'application/json',
181
+ ...extraHeaders,
182
+ },
183
+ validateStatus: () => true,
184
+ });
185
+ return { status: response.status, data: response.data };
186
+ }
187
+ catch (error) {
188
+ // validateStatus accepts every HTTP status, so only network-level
189
+ // failures (DNS, refused, reset, timeout) land here.
190
+ throw toSafeError(error);
191
+ }
49
192
  }
50
193
  /**
51
194
  * Format a Berget API error response into a human-readable string.
@@ -60,6 +203,7 @@ function formatBergetError(resourceLabel, status, data) {
60
203
  const d = data;
61
204
  // Shape A (OpenAPI-documented): { error: "message string", code: "...", details: ... }
62
205
  // Shape B (OpenAI-compatible): { error: { message: "...", type: "...", code: "..." } }
206
+ // (the only shape seen on any endpoint in the 2026-11-30 sweep)
63
207
  // Shape C (some endpoints): { message: "..." }
64
208
  // Shape D (bare string on some): "error text"
65
209
  let messageText;
@@ -99,6 +243,14 @@ function formatBergetError(resourceLabel, status, data) {
99
243
  else if (typeof data === 'string' && data.trim().length > 0) {
100
244
  parts.push(data.trim().slice(0, 500));
101
245
  }
246
+ // Berget answers an unknown or mistyped key with HTTP 402 "No subscription
247
+ // found for this API key", which reads like a billing problem. Say so.
248
+ if (status === 402) {
249
+ parts.push('Berget returns this for an unrecognised API key as well as for an account without an active subscription, so check the key in the Berget AI credential first');
250
+ }
251
+ else if (status === 401 || status === 403) {
252
+ parts.push('check the API key in the Berget AI credential');
253
+ }
102
254
  return parts.join(' — ');
103
255
  }
104
256
  /**
@@ -71,7 +71,7 @@ exports.speechProperties = [
71
71
  name: 'diarize',
72
72
  type: 'boolean',
73
73
  default: false,
74
- description: 'Whether to identify which speaker said what. When enabled, the response will include a "speaker_transcript" field formatted like:\n\nSPEAKER_00:\nFirst speaker\'s lines.\n\nSPEAKER_01:\nReply from the second speaker.\n\nThe raw segment + word-level timestamps with per-word speaker labels are also preserved in the response under "segments" if you need to drill in. Works best with 2-4 distinct speakers; overlapping speech is a known limitation. The Response Format is automatically upgraded to "Verbose JSON" if it was left at JSON or Text, so the data is actually returned.',
74
+ description: 'Whether to identify which speaker said what. When enabled, the response will include a "speaker_transcript" field formatted like:\n\nSPEAKER_00:\nFirst speaker\'s lines.\n\nSPEAKER_01:\nReply from the second speaker.\n\nThe raw segment + word-level timestamps with per-word speaker labels are also preserved in the response under "segments" if you need to drill in. Works best with 2-4 distinct speakers; overlapping speech is a known limitation. Supported by the Whisper-based models; klang/pianissimo ignores this option, and no "speaker_transcript" is added for it. The Response Format is automatically upgraded to "Verbose JSON" if it was left at JSON or Text, so the data is actually returned.',
75
75
  },
76
76
  {
77
77
  displayName: 'Word-Level Alignment',
@@ -171,19 +171,32 @@ async function executeSpeech(context, itemIndex) {
171
171
  if (options.temperature !== undefined) {
172
172
  formData.append('temperature', String(options.temperature));
173
173
  }
174
- const response = await axios_1.default.post(`${shared_1.BERGET_API_BASE_URL}/audio/transcriptions`, formData, {
175
- headers: {
176
- Authorization: `Bearer ${credentials.apiKey}`,
177
- ...formData.getHeaders(),
178
- },
179
- validateStatus: () => true,
180
- maxContentLength: Infinity,
181
- maxBodyLength: Infinity,
182
- });
174
+ let response;
175
+ try {
176
+ response = await axios_1.default.post(`${shared_1.BERGET_API_BASE_URL}/audio/transcriptions`, formData, {
177
+ headers: {
178
+ Authorization: `Bearer ${credentials.apiKey}`,
179
+ ...formData.getHeaders(),
180
+ },
181
+ validateStatus: () => true,
182
+ maxContentLength: Infinity,
183
+ maxBodyLength: Infinity,
184
+ });
185
+ }
186
+ catch (error) {
187
+ throw (0, shared_1.toSafeError)(error, 'speech');
188
+ }
183
189
  if (response.status !== 200) {
184
190
  (0, shared_1.throwBergetError)(context, itemIndex, 'speech', response.status, response.data);
185
191
  }
186
192
  const data = response.data;
193
+ // The text, srt and vtt formats come back as text/plain, so axios hands us
194
+ // a string rather than an object. n8n requires an item's `json` to be an
195
+ // object, so wrap it. `text` is the key the JSON format already uses, which
196
+ // keeps `{{ $json.text }}` working whichever format is selected.
197
+ if (typeof data === 'string') {
198
+ return { text: data };
199
+ }
187
200
  // When the user enabled Diarize and we got a structured verbose_json back,
188
201
  // also produce a "speaker_transcript" field — a single human-readable string
189
202
  // formatted like:
@@ -216,10 +229,12 @@ async function executeSpeech(context, itemIndex) {
216
229
  * Shape A (flat): { segments: [...], language, text }
217
230
  * Shape B (nested): { segments: { segments: [...], ... }, language, text }
218
231
  *
219
- * Shape B is what the API returns for verbose_json with diarize=true (as of
220
- * 2026-04). We check both so the speaker_transcript builder works regardless
221
- * of which shape we get, and so future API changes that flatten or re-nest
222
- * don't silently break the output.
232
+ * Shape B is what the API returned for verbose_json with diarize=true in
233
+ * 2026-04. By 2026-11-30 it had switched to Shape A, with `speaker` on each
234
+ * segment and word-level data in a separate top-level `words` array. We check
235
+ * both so the speaker_transcript builder works regardless of which shape we
236
+ * get, and so future API changes that flatten or re-nest don't silently break
237
+ * the output.
223
238
  */
224
239
  function extractSegments(data) {
225
240
  const top = data.segments;
@@ -246,8 +261,15 @@ function extractSegments(data) {
246
261
  *
247
262
  * Segment text is preferred over re-joining words because the model produces
248
263
  * better punctuation and capitalization at segment level.
264
+ *
265
+ * Returns '' when no segment carries a speaker at all. Not every model
266
+ * diarizes: klang/pianissimo accepts diarize=true and silently ignores it,
267
+ * returning one unlabelled segment. Labelling that whole transcript "UNKNOWN"
268
+ * would suggest diarization ran and found nobody, so no speaker_transcript is
269
+ * produced in that case.
249
270
  */
250
271
  function buildSpeakerTranscript(segments) {
272
+ var _a;
251
273
  if (!Array.isArray(segments) || segments.length === 0)
252
274
  return '';
253
275
  const labeled = segments.map((seg) => {
@@ -257,18 +279,21 @@ function buildSpeakerTranscript(segments) {
257
279
  speaker = seg.words[0].speaker;
258
280
  }
259
281
  const text = ((_a = seg.text) !== null && _a !== void 0 ? _a : '').trim();
260
- return { speaker: speaker !== null && speaker !== void 0 ? speaker : 'UNKNOWN', text };
282
+ return { speaker, text };
261
283
  });
284
+ if (!labeled.some((seg) => seg.speaker))
285
+ return '';
262
286
  const groups = [];
263
287
  for (const seg of labeled) {
264
288
  if (!seg.text)
265
289
  continue;
290
+ const speaker = (_a = seg.speaker) !== null && _a !== void 0 ? _a : 'UNKNOWN';
266
291
  const last = groups[groups.length - 1];
267
- if (last && last.speaker === seg.speaker) {
292
+ if (last && last.speaker === speaker) {
268
293
  last.text += ' ' + seg.text;
269
294
  }
270
295
  else {
271
- groups.push({ speaker: seg.speaker, text: seg.text });
296
+ groups.push({ speaker, text: seg.text });
272
297
  }
273
298
  }
274
299
  return groups.map((g) => `${g.speaker}:\n${g.text}`).join('\n\n');
@@ -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 {
@@ -77,7 +76,7 @@ class BergetAiChatModel {
77
76
  name: 'reasoningEffort',
78
77
  type: 'options',
79
78
  default: 'medium',
80
- description: 'Controls how much thinking a reasoning-capable model performs (GPT-OSS, DeepSeek R1, etc.). The parameter is sent to the model, but note: the @langchain/openai JS package does not currently surface reasoning tokens back to the n8n Agent, so you will see the final answer only. The higher effort still affects answer quality even though the chain-of-thought is not visible.',
79
+ description: 'Controls how much thinking a reasoning-capable model performs. Models that do not reason ignore it. The reasoning text is kept apart from the answer: it comes back on the model\'s message as additional_kwargs.reasoning_content, so it is not part of the text the parent node (AI Agent, Chain) works with.',
81
80
  options: [
82
81
  {
83
82
  name: 'Low',
@@ -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 {
@@ -61,7 +60,7 @@ class BergetAiEmbeddingsModel {
61
60
  type: 'number',
62
61
  typeOptions: { minValue: 0 },
63
62
  default: 0,
64
- description: "⚠️ CURRENTLY BROKEN ON BERGET'S API. Leave at 0 (default) to omit the parameter entirely — this is the only reliable mode as of 2026-04. Setting any positive value causes Berget to return HTTP 503 EMBEDDING_CREATION_ERROR for every request, even when the value matches the model's native dimension (e.g. 1024 for intfloat/multilingual-e5-large-instruct). Berget's OpenAPI spec documents the dimensions parameter but the backend currently rejects it for all embedding models we've tested. The field is kept here so that when Berget fixes their backend, you can set a dimension without a package update. Default behaviour (dimensions=0) returns the model's native vector size.",
63
+ description: "Leave at 0 (default) to get the model's native vector size (1024 for both current models). Neither of Berget's embedding models, intfloat/multilingual-e5-large and intfloat/multilingual-e5-large-instruct, supports a custom output size: any positive value here makes Berget reject every request with HTTP 400 \"does not support matryoshka representation\", even when it equals the native size (checked 2026-11-30). The field is kept so that a future model which does support it can be used without a package update.",
65
64
  },
66
65
  {
67
66
  displayName: 'Strip New Lines',
@@ -92,16 +91,24 @@ 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, {});
98
- // Dimensions is intentionally only passed through when > 0. Berget's
99
- // backend currently returns HTTP 503 EMBEDDING_CREATION_ERROR for any
100
- // request that includes the dimensions field (verified 2026-04-11),
101
- // despite their OpenAPI spec documenting it. The field is kept in the
102
- // UI so users can opt in once Berget fixes the backend without a
103
- // package update. See CHANGELOG 0.4.8 for details.
104
- const embeddings = new openai_1.OpenAIEmbeddings({
104
+ // Dimensions is intentionally only passed through when > 0. Neither of
105
+ // Berget's current embedding models supports a custom output size, and
106
+ // the API rejects any request that includes the field: HTTP 400 "does
107
+ // not support matryoshka representation" as of 2026-11-30. (In 2026-04
108
+ // the same request got HTTP 503 EMBEDDING_CREATION_ERROR; see CHANGELOG
109
+ // 0.4.8.) The field is kept in the UI so a future model that supports
110
+ // it can be used without a package update.
111
+ const embeddings = new OpenAIEmbeddings({
105
112
  apiKey: credentials.apiKey,
106
113
  model: modelName,
107
114
  configuration: {
@@ -4,76 +4,94 @@ 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,
73
- },
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
+ // Berget rejects the whole request with HTTP 400 if any document is an
43
+ // empty string, so those are left out: an empty chunk cannot be
44
+ // relevant to anything. `candidates` is what gets sent, and the
45
+ // indices Berget returns point into it.
46
+ const candidates = documents.filter((d) => typeof d.pageContent === 'string' && d.pageContent.length > 0);
47
+ if (candidates.length === 0)
48
+ return [];
49
+ // The parent node surfaces whatever this throws, and n8n stores it
50
+ // with the execution, so it must never be a raw axios error. See
51
+ // toSafeError in shared.ts.
52
+ let response;
53
+ try {
54
+ response = await axios_1.default.post(`${shared_1.BERGET_API_BASE_URL}/rerank`, {
55
+ model: this.model,
56
+ query,
57
+ documents: candidates.map((d) => d.pageContent),
58
+ top_n: Math.min(this.topN, candidates.length),
59
+ return_documents: false,
60
+ }, {
61
+ headers: {
62
+ Authorization: `Bearer ${this.apiKey}`,
63
+ 'Content-Type': 'application/json',
64
+ },
65
+ timeout: this.timeoutMs,
66
+ validateStatus: () => true,
67
+ });
68
+ }
69
+ catch (error) {
70
+ throw (0, shared_1.toSafeError)(error, 'rerank');
71
+ }
72
+ if (response.status !== 200) {
73
+ throw new shared_1.BergetRequestError((0, shared_1.formatBergetError)('rerank', response.status, response.data));
74
+ }
75
+ const payload = (_a = response.data) !== null && _a !== void 0 ? _a : {};
76
+ const results = (_c = (_b = payload.results) !== null && _b !== void 0 ? _b : payload.data) !== null && _c !== void 0 ? _c : [];
77
+ return results.map((result) => {
78
+ var _a;
79
+ var _b, _c, _d;
80
+ const original = candidates[result.index];
81
+ const fallbackText = typeof result.document === 'string'
82
+ ? result.document
83
+ : (_b = (_a = result.document) === null || _a === void 0 ? void 0 : _a.text) !== null && _b !== void 0 ? _b : '';
84
+ return new Document({
85
+ pageContent: (_c = original === null || original === void 0 ? void 0 : original.pageContent) !== null && _c !== void 0 ? _c : fallbackText,
86
+ metadata: {
87
+ ...((_d = original === null || original === void 0 ? void 0 : original.metadata) !== null && _d !== void 0 ? _d : {}),
88
+ relevance_score: result.relevance_score,
89
+ },
90
+ });
74
91
  });
75
- });
92
+ }
76
93
  }
94
+ return new BergetReranker(params);
77
95
  }
78
96
  class BergetAiReranker {
79
97
  constructor() {
@@ -152,7 +170,16 @@ class BergetAiReranker {
152
170
  const model = this.getNodeParameter('model', itemIndex);
153
171
  const topN = this.getNodeParameter('topN', itemIndex, 3);
154
172
  const options = this.getNodeParameter('options', itemIndex, {});
155
- const reranker = new BergetReranker({
173
+ // Required lazily so a missing LangChain install fails only this sub-node
174
+ // instead of the whole package. See requireOptionalModule in shared.ts.
175
+ const documentsModule = (0, shared_1.requireOptionalModule)('@langchain/core/documents');
176
+ const compressorsModule = (0, shared_1.requireOptionalModule)('@langchain/core/retrievers/document_compressors');
177
+ if (!documentsModule || !compressorsModule) {
178
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Could not load "@langchain/core"', {
179
+ description: shared_1.LANGCHAIN_MISSING_HINT,
180
+ });
181
+ }
182
+ const reranker = createBergetReranker(documentsModule, compressorsModule, {
156
183
  apiKey: credentials.apiKey,
157
184
  model,
158
185
  topN,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "n8n-nodes-berget-mk",
3
- "version": "0.5.3",
3
+ "version": "0.5.5",
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",
@@ -36,15 +36,15 @@
36
36
  "dist"
37
37
  ],
38
38
  "dependencies": {
39
- "@langchain/core": "^1.1.39",
40
- "@langchain/openai": "^1.4.3",
41
- "axios": "^1.19.0",
39
+ "@langchain/core": "^1.5.1",
40
+ "@langchain/openai": "^1.8.5",
41
+ "axios": "^1.21.1",
42
42
  "form-data": "^4.0.6"
43
43
  },
44
44
  "devDependencies": {
45
- "@types/node": "^20.11.0",
46
- "n8n-workflow": "^2.16.0",
47
- "typescript": "^5.3.0"
45
+ "@types/node": "^22.20.7",
46
+ "n8n-workflow": "~2.49.6",
47
+ "typescript": "^7.0.2"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "n8n-workflow": "*"
@@ -54,12 +54,8 @@
54
54
  "optional": true
55
55
  }
56
56
  },
57
- "overrides": {
58
- "uuid": "^14.0.0",
59
- "form-data": "^4.0.6"
60
- },
61
57
  "engines": {
62
- "node": ">=18.0.0"
58
+ "node": ">=22.0.0"
63
59
  },
64
60
  "n8n": {
65
61
  "n8nNodesApiVersion": 1,