| 1 | import { ChunkWithoutID } from "../../"; |
| 2 | import { countTokens } from "../../llm/countTokens"; |
| 3 | |
| 4 | import { basicChunker } from "./basic"; |
| 5 | |
| 6 | export function cleanFragment( |
| 7 | fragment: string | undefined, |
| 8 | ): string | undefined { |
| 9 | if (!fragment) { |
| 10 | return undefined; |
| 11 | } |
| 12 | |
| 13 | // Remove leading and trailing whitespaces |
| 14 | fragment = fragment.trim(); |
| 15 | |
| 16 | // If there's a ](, which would mean a link, remove everything after it |
| 17 | const parenIndex = fragment.indexOf("]("); |
| 18 | if (parenIndex !== -1) { |
| 19 | fragment = fragment.slice(0, parenIndex); |
| 20 | } |
| 21 | |
| 22 | // Remove all special characters except alphanumeric, hyphen, space, and underscore |
| 23 | fragment = fragment.replace(/[^\w-\s]/g, "").trim(); |
| 24 | |
| 25 | // Convert to lowercase |
| 26 | fragment = fragment.toLowerCase(); |
| 27 | |
| 28 | // Replace spaces with hyphens |
| 29 | fragment = fragment.replace(/\s+/g, "-"); |
| 30 | |
| 31 | return fragment; |
| 32 | } |
| 33 | |
| 34 | export function cleanHeader(header: string | undefined): string | undefined { |
| 35 | if (!header) { |
| 36 | return undefined; |
| 37 | } |
| 38 | |
| 39 | // Remove leading and trailing whitespaces |
| 40 | header = header.trim(); |
| 41 | |
| 42 | // If there's a (, remove everything after it |
| 43 | const parenIndex = header.indexOf("("); |
| 44 | if (parenIndex !== -1) { |
| 45 | header = header.slice(0, parenIndex); |
| 46 | } |
| 47 | |
| 48 | // Remove all special characters except alphanumeric, hyphen, space, and underscore |
| 49 | header = header |
| 50 | .replace(/[^\w-\s]/g, "") |
| 51 | .replace("¶", "") |
| 52 | .trim(); |
| 53 | |
| 54 | return header; |
| 55 | } |
| 56 | |
| 57 | function findHeader(lines: string[]): string | undefined { |
| 58 | return lines.find((line) => line.startsWith("#"))?.split("# ")[1]; |
| 59 | } |
| 60 | |
| 61 | export async function* markdownChunker( |
| 62 | content: string, |
| 63 | maxChunkSize: number, |
| 64 | hLevel: number, |
| 65 | ): AsyncGenerator<ChunkWithoutID> { |
| 66 | if (countTokens(content) <= maxChunkSize) { |
| 67 | const header = findHeader(content.split("\n")); |
| 68 | yield { |
| 69 | content, |
| 70 | startLine: 0, |
| 71 | endLine: content.split("\n").length, |
| 72 | otherMetadata: { |
| 73 | fragment: cleanFragment(header), |
| 74 | title: cleanHeader(header), |
| 75 | }, |
| 76 | }; |
| 77 | return; |
| 78 | } |
| 79 | if (hLevel > 4) { |
| 80 | const header = findHeader(content.split("\n")); |
| 81 | |
| 82 | for await (const chunk of basicChunker(content, maxChunkSize)) { |
| 83 | yield { |
| 84 | ...chunk, |
| 85 | otherMetadata: { |
| 86 | fragment: cleanFragment(header), |
| 87 | title: cleanHeader(header), |
| 88 | }, |
| 89 | }; |
| 90 | } |
| 91 | return; |
| 92 | } |
| 93 | |
| 94 | const h = `${"#".repeat(hLevel + 1)} `; |
| 95 | const lines = content.split("\n"); |
| 96 | const sections = []; |
| 97 | |
| 98 | let currentSectionStartLine = 0; |
| 99 | let currentSection: string[] = []; |
| 100 | |
| 101 | for (let i = 0; i < lines.length; i++) { |
| 102 | if (lines[i].startsWith(h) || i === 0) { |
| 103 | if (currentSection.length) { |
| 104 | const isHeader = currentSection[0].startsWith(h); |
| 105 | sections.push({ |
| 106 | header: isHeader ? currentSection[0] : findHeader(currentSection), |
| 107 | content: currentSection.slice(isHeader ? 1 : 0).join("\n"), |
| 108 | startLine: currentSectionStartLine, |
| 109 | endLine: currentSectionStartLine + currentSection.length, |
| 110 | }); |
| 111 | } |
| 112 | currentSection = [lines[i]]; |
| 113 | currentSectionStartLine = i; |
| 114 | } else { |
| 115 | currentSection.push(lines[i]); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | if (currentSection.length) { |
| 120 | const isHeader = currentSection[0].startsWith(h); |
| 121 | sections.push({ |
| 122 | header: isHeader ? currentSection[0] : findHeader(currentSection), |
| 123 | content: currentSection.slice(isHeader ? 1 : 0).join("\n"), |
| 124 | startLine: currentSectionStartLine, |
| 125 | endLine: currentSectionStartLine + currentSection.length, |
| 126 | }); |
| 127 | } |
| 128 | |
| 129 | for (const section of sections) { |
| 130 | for await (const chunk of markdownChunker( |
| 131 | section.content, |
| 132 | maxChunkSize - (section.header ? countTokens(section.header) : 0), |
| 133 | hLevel + 1, |
| 134 | )) { |
| 135 | yield { |
| 136 | content: `${section.header}\n${chunk.content}`, |
| 137 | startLine: section.startLine + chunk.startLine, |
| 138 | endLine: section.startLine + chunk.endLine, |
| 139 | otherMetadata: { |
| 140 | fragment: |
| 141 | chunk.otherMetadata?.fragment || cleanFragment(section.header), |
| 142 | title: chunk.otherMetadata?.title || cleanHeader(section.header), |
| 143 | }, |
| 144 | }; |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /** |
| 150 | * Recursively chunks by header level (h1-h6) |
| 151 | * The final chunk will always include all parent headers |
| 152 | * TODO: Merge together neighboring chunks if their sum doesn't exceed maxChunkSize |
| 153 | */ |