| 95 | } |
| 96 | |
| 97 | export function buildChunks(texts: string[], overlapTokens: number): Chunk[] { |
| 98 | let previousEndIndex = 0 |
| 99 | const overlapChars = tokensToChars(overlapTokens) |
| 100 | |
| 101 | return texts.map((text, index) => { |
| 102 | let startIndex: number |
| 103 | let actualContentLength: number |
| 104 | |
| 105 | if (index === 0 || overlapTokens <= 0) { |
| 106 | startIndex = previousEndIndex |
| 107 | actualContentLength = text.length |
| 108 | } else { |
| 109 | const prevChunk = texts[index - 1] |
| 110 | const overlapLength = Math.min(overlapChars, prevChunk.length, text.length) |
| 111 | startIndex = previousEndIndex - overlapLength |
| 112 | actualContentLength = text.length - overlapLength |
| 113 | } |
| 114 | |
| 115 | const safeStart = Math.max(0, startIndex) |
| 116 | const endIndex = safeStart + Math.max(0, actualContentLength) |
| 117 | |
| 118 | previousEndIndex = endIndex |
| 119 | |
| 120 | return { |
| 121 | text, |
| 122 | tokenCount: estimateTokens(text), |
| 123 | metadata: { |
| 124 | startIndex: safeStart, |
| 125 | endIndex, |
| 126 | }, |
| 127 | } |
| 128 | }) |
| 129 | } |
| 130 | |
| 131 | export function resolveChunkerOptions(options: { |
| 132 | chunkSize?: number |