Repository navigation
Expand file tree
/
Copy pathchunkingUtils.js
More file actions
394 lines (331 loc) · 12.5 KB
/
Copy pathchunkingUtils.js
File metadata and controls
394 lines (331 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import { countTokens as legacyCountTokens } from './embeddingUtils.js';
import { cosineSimilarity } from './similarityUtils.js';
// -----------------------------------------------------------
// -- Linked List Node for Multi-Pass Merge Algorithm --
// -----------------------------------------------------------
/**
* Creates a linked list node for merge algorithm
* @param {string} text - Chunk text content
* @param {number[]} embedding - Embedding vector (or null if not yet computed)
* @param {number} tokenCount - Token count for this chunk
* @returns {Object} Linked list node
*/
function createMergeNode(text, embedding, tokenCount) {
return {
text,
embedding,
tokenCount,
prev: null,
next: null,
processed: false
};
}
/**
* Builds a doubly-linked list from an array of chunks
* @param {Object[]} chunks - Array of chunk objects with text and tokenCount
* @param {Map} embeddingsMap - Map of text to embedding vectors
* @returns {Object|null} Head node of linked list, or null if empty
*/
function buildLinkedList(chunks, embeddingsMap) {
if (!chunks || chunks.length === 0) return null;
let head = null;
let prev = null;
for (const chunk of chunks) {
const node = createMergeNode(
chunk.text,
embeddingsMap?.get(chunk.text) || null,
chunk.tokenCount
);
if (!head) head = node;
if (prev) {
prev.next = node;
node.prev = prev;
}
prev = node;
}
return head;
}
/**
* Converts a linked list back to an array of chunk objects
* @param {Object|null} head - Head node of linked list
* @returns {Object[]} Array of chunk objects with text, tokenCount, embedding
*/
function linkedListToChunks(head) {
const chunks = [];
let current = head;
while (current) {
chunks.push({
text: current.text,
tokenCount: current.tokenCount,
embedding: current.embedding
});
current = current.next;
}
return chunks;
}
// -----------------------------------------------------------
// -- Merge Candidate Logic --
// -----------------------------------------------------------
/**
* Evaluates if two adjacent nodes can be merged
* @param {Object} node - First node
* @param {Object} nextNode - Second node (node.next)
* @param {number} maxTokens - Maximum tokens per chunk
* @param {number} similarityThreshold - Minimum similarity to merge
* @returns {Object|null} Merge candidate or null if not mergeable (including when embeddings are missing)
*/
function _getMergeCandidate(node, nextNode, maxTokens, similarityThreshold) {
if (!node || !nextNode) return null;
// Skip if either node is missing embedding (cannot compute similarity)
if (!node.embedding || !nextNode.embedding) return null;
const combinedSize = node.tokenCount + nextNode.tokenCount;
if (combinedSize > maxTokens) return null;
// Compute similarity between adjacent chunks
const similarity = cosineSimilarity(node.embedding, nextNode.embedding);
if (similarity < similarityThreshold) return null;
return {
node,
nextNode,
similarity,
combinedSize
};
}
/**
* Collects all valid merge candidates from the linked list
* @param {Object} head - Head node of linked list
* @param {number} maxTokens - Maximum tokens per chunk
* @param {number} similarityThreshold - Minimum similarity to merge
* @returns {Object[]} Array of merge candidate objects
*/
function collectMergeCandidates(head, maxTokens, similarityThreshold) {
const candidates = [];
let current = head;
while (current && current.next) {
const candidate = _getMergeCandidate(
current,
current.next,
maxTokens,
similarityThreshold
);
if (candidate) {
candidates.push(candidate);
}
current = current.next;
}
return candidates;
}
// -----------------------------------------------------------
// -- Multi-Pass Merge Algorithm Core --
// -----------------------------------------------------------
/**
* Executes a single merge operation between two adjacent nodes
* @param {Object} candidate - Merge candidate with node, nextNode, combinedSize
* @returns {Object} The merged node
*/
function executeMerge(candidate) {
const { node, nextNode } = candidate;
// Combine text
node.text = node.text + ' ' + nextNode.text;
node.tokenCount = candidate.combinedSize;
// Clear embedding (will be recomputed if needed)
node.embedding = null;
// Update linked list pointers
node.next = nextNode.next;
if (nextNode.next) {
nextNode.next.prev = node;
}
// Mark as processed this pass
node.processed = true;
return node;
}
/**
* Recomputes embeddings for merged nodes and resets processed flags
* @param {Object[]} mergedNodes - Array of nodes that were merged this pass
* @param {Function} embedBatch - Batch embedding function
* @returns {Promise<void>}
*/
async function refreshMergedEmbeddings(mergedNodes, embedBatch) {
if (mergedNodes.length === 0) return;
const texts = mergedNodes.map(node => node.text);
const embeddings = await embedBatch(texts);
mergedNodes.forEach((node, index) => {
node.embedding = embeddings[index];
node.processed = false; // Reset for next pass
});
}
/**
* Determines how many merges to perform in a single pass
* @param {number} candidateCount - Number of available merge candidates
* @param {Object} options - Merge throttling options
* @param {number} options.maxMergesPerPass - Absolute maximum merges per pass
* @param {number} options.maxMergesPerPassPercentage - Percentage of candidates to merge
* @param {number} options.uncappedCandidateMerges - Below this count, allow all merges
* @returns {number} Number of merges to perform this pass
*/
function calculateMergeLimit(candidateCount, options) {
const {
maxMergesPerPass,
maxMergesPerPassPercentage,
uncappedCandidateMerges
} = options;
// Soft minimum: if few candidates, allow all
if (candidateCount <= uncappedCandidateMerges) {
return candidateCount;
}
// Percentage cap
const percentageLimit = Math.floor(candidateCount * maxMergesPerPassPercentage / 100);
// Absolute cap
return Math.min(percentageLimit, maxMergesPerPass);
}
/**
* Executes one merge pass over the linked list
* @param {Object} head - Head node of linked list
* @param {number} maxTokens - Maximum tokens per chunk
* @param {number} similarityThreshold - Minimum similarity to merge
* @param {Object} options - Merge throttling options
* @param {Function} embedBatch - Batch embedding function
* @returns {Promise<{head: Object, mergeCount: number}>} Updated head and number of merges performed
*/
async function executeMergePass(head, maxTokens, similarityThreshold, options, embedBatch) {
// Collect all candidates
const candidates = collectMergeCandidates(head, maxTokens, similarityThreshold);
if (candidates.length === 0) {
return { head, mergeCount: 0 };
}
// Sort by similarity (highest first)
candidates.sort((a, b) => b.similarity - a.similarity);
// Determine how many to merge this pass
const mergeLimit = calculateMergeLimit(candidates.length, options);
// Execute merges (skip if either node already processed this pass)
const mergedNodes = [];
let mergeCount = 0;
for (const candidate of candidates) {
if (mergeCount >= mergeLimit) break;
if (candidate.node.processed || candidate.nextNode.processed) continue;
const mergedNode = executeMerge(candidate);
mergedNodes.push(mergedNode);
mergeCount++;
}
// Refresh embeddings for merged nodes
await refreshMergedEmbeddings(mergedNodes, embedBatch);
return { head, mergeCount };
}
// -----------------------------------------------------------
// -- Function to create chunks of text based on similarity --
// -----------------------------------------------------------
// `countTokens` is injected by the v3 instance pipeline (chunker-owned
// tokenizer). The default falls back to the legacy module-global tokenizer in
// embeddingUtils.js so pre-v3 deep importers that call initializeTokenizer /
// initializeEmbeddingUtils first keep working unchanged.
export function createChunks(sentences, similarities, maxTokenSize, similarityThreshold, logging, countTokens = legacyCountTokens) {
let chunks = [];
let currentChunk = [sentences[0]];
if (logging) {
console.log('Initial sentence:', sentences[0]);
}
for (let i = 1; i < sentences.length; i++) {
const nextSentence = sentences[i];
// For cramit (when similarities is null), only check token size
if (!similarities) {
const currentChunkText = currentChunk.join(" ");
const currentChunkSize = countTokens(currentChunkText);
const nextSentenceTokenCount = countTokens(nextSentence);
if (currentChunkSize + nextSentenceTokenCount <= maxTokenSize) {
currentChunk.push(nextSentence);
} else {
chunks.push(currentChunkText);
currentChunk = [nextSentence];
}
continue;
}
// Check similarity first for chunkit
if (similarities[i - 1] >= similarityThreshold) {
if (logging) {
console.log(`Adding sentence ${i} with similarity ${similarities[i - 1]}`);
}
// Then check token size
const currentChunkText = currentChunk.join(" ");
const currentChunkSize = countTokens(currentChunkText);
const nextSentenceTokenCount = countTokens(nextSentence);
if (currentChunkSize + nextSentenceTokenCount <= maxTokenSize) {
currentChunk.push(nextSentence);
} else {
chunks.push(currentChunkText);
currentChunk = [nextSentence];
}
} else {
if (logging) {
console.log(`Starting new chunk at sentence ${i}, similarity was ${similarities[i - 1]}`);
}
chunks.push(currentChunk.join(" "));
currentChunk = [nextSentence];
}
}
if (currentChunk.length > 0) {
chunks.push(currentChunk.join(" "));
}
return chunks;
}
// --------------------------------------------------------------
// -- Optimize and Rebalance Chunks (Multi-Pass Merge Algorithm) --
// --------------------------------------------------------------
/**
* Optimizes and rebalances chunks using multi-pass merge algorithm
* @param {Object[]} chunks - Array of chunk objects with text and tokenCount
* @param {Map} embeddingsMap - Map of text to embedding vectors
* @param {number} maxTokens - Maximum tokens per chunk
* @param {number} similarityThreshold - Minimum similarity to merge
* @param {Object} mergeOptions - Merge throttling options
* @param {number} mergeOptions.maxMergesPerPass - Absolute maximum merges per pass
* @param {number} mergeOptions.maxUncappedPasses - Maximum passes before stopping
* @param {number} mergeOptions.maxMergesPerPassPercentage - Percentage of candidates to merge
* @param {number} mergeOptions.uncappedCandidateMerges - Below this count, allow all merges
* @param {Function} embedBatch - Batch embedding function
* @returns {Promise<Object[]>} Optimized array of chunk objects
*/
export async function optimizeAndRebalanceChunks(
chunks,
embeddingsMap,
maxTokens,
similarityThreshold,
mergeOptions,
embedBatch
) {
if (!chunks || chunks.length <= 1) return chunks || [];
const { maxUncappedPasses } = mergeOptions;
// Build linked list from chunks
let head = buildLinkedList(chunks, embeddingsMap);
// Multi-pass merge loop
let passCount = 0;
while (passCount < maxUncappedPasses) {
const { mergeCount } = await executeMergePass(
head,
maxTokens,
similarityThreshold,
mergeOptions,
embedBatch
);
passCount++;
// Debug logging every 10 passes to track progress
if (passCount > 0 && passCount % 10 === 0) {
console.debug(`Merge pass ${passCount}: ${mergeCount} merges performed`);
}
// Stop if no merges occurred (converged)
if (mergeCount === 0) break;
}
// Warning if hitting maxUncappedPasses limit (potential infinite loop protection)
if (passCount >= maxUncappedPasses) {
console.warn(`Merge algorithm reached maximum passes (${maxUncappedPasses})`);
}
// Convert back to chunks array
return linkedListToChunks(head);
}
// ------------------------------------------------
// -- Helper function to apply prefix to a chunk --
// ------------------------------------------------
export function applyPrefixToChunk(chunkPrefix, chunk) {
if (chunkPrefix && chunkPrefix.trim()) {
return `${chunkPrefix}: ${chunk}`;
}
return chunk;
};