Class: Ask::RAG::TextSplitter::Markdown
- Defined in:
- lib/ask/rag/text_splitter/markdown.rb
Overview
Splits Markdown text by headers, preserving header hierarchy in metadata.
Each chunk starts at a header and includes all content until the next header at the same or higher level. Header context is tracked in metadata so retrieval results know which section they came from.
Constant Summary collapse
- HEADER_PATTERN =
/^(#{'#'}{1,6})\s+(.+)$/
Instance Method Summary collapse
Methods inherited from Base
Constructor Details
This class inherits a constructor from Ask::RAG::TextSplitter::Base
Instance Method Details
#split_text(text) ⇒ Object
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 |
# File 'lib/ask/rag/text_splitter/markdown.rb', line 20 def split_text(text) chunks = [] current_header = {} current_lines = [] text.each_line do |line| if (match = line.match(HEADER_PATTERN)) # Save previous section if current_lines.any? chunks << build_chunk(current_lines.join, current_header) end level = match[1].length heading_text = match[2].strip # Clear lower-level headers current_header.select! { |k, _| HEADER_LEVELS[k] && HEADER_LEVELS[k] < level } current_header["h#{level}".to_sym] = heading_text current_lines = [] else current_lines << line end end # Last section chunks << build_chunk(current_lines.join, current_header) if current_lines.any? chunks end |