(text: string, separatorIndex = 0)
| 40 | } |
| 41 | |
| 42 | private splitRecursively(text: string, separatorIndex = 0): string[] { |
| 43 | const tokenCount = estimateTokens(text) |
| 44 | |
| 45 | if (tokenCount <= this.chunkSize) { |
| 46 | return text.trim() ? [text] : [] |
| 47 | } |
| 48 | |
| 49 | if (separatorIndex >= this.separators.length) { |
| 50 | const chunkSizeChars = tokensToChars(this.chunkSize) |
| 51 | return splitAtWordBoundaries(text, chunkSizeChars) |
| 52 | } |
| 53 | |
| 54 | const separator = this.separators[separatorIndex] |
| 55 | const parts = text.split(separator).filter((part) => part.trim()) |
| 56 | |
| 57 | if (parts.length <= 1) { |
| 58 | return this.splitRecursively(text, separatorIndex + 1) |
| 59 | } |
| 60 | |
| 61 | const chunks: string[] = [] |
| 62 | let currentChunk = '' |
| 63 | |
| 64 | for (const part of parts) { |
| 65 | const testChunk = currentChunk + (currentChunk ? separator : '') + part |
| 66 | |
| 67 | if (estimateTokens(testChunk) <= this.chunkSize) { |
| 68 | currentChunk = testChunk |
| 69 | } else { |
| 70 | if (currentChunk.trim()) { |
| 71 | chunks.push(currentChunk.trim()) |
| 72 | } |
| 73 | |
| 74 | if (estimateTokens(part) > this.chunkSize) { |
| 75 | const subChunks = this.splitRecursively(part, separatorIndex + 1) |
| 76 | for (const subChunk of subChunks) { |
| 77 | chunks.push(subChunk) |
| 78 | } |
| 79 | currentChunk = '' |
| 80 | } else { |
| 81 | currentChunk = part |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | if (currentChunk.trim()) { |
| 87 | chunks.push(currentChunk.trim()) |
| 88 | } |
| 89 | |
| 90 | return chunks |
| 91 | } |
| 92 | |
| 93 | async chunk(text: string): Promise<Chunk[]> { |
| 94 | if (!text?.trim()) { |
no test coverage detected