Class: LLM::Console::Markdown

Inherits:
Object
  • Object
show all
Includes:
Table
Defined in:
lib/llm/console/markdown.rb,
lib/llm/console/markdown/table.rb

Overview

This class is designed to represent a markdown string (typically from a model's response) as a tree of objects where each object contains a piece of text, and also optional style information for that text (eg bold, underscore, ...)

Defined Under Namespace

Modules: Table Classes: Parser

Instance Method Summary collapse

Methods included from Table

#walk_table

Constructor Details

#initialize(text, width) ⇒ LLM::Console::Markdown

Parameters:

  • text (String)
  • width (Integer)


19
20
21
22
23
24
25
26
27
28
29
# File 'lib/llm/console/markdown.rb', line 19

def initialize(text, width)
  ##
  # 'Parser' treats HTML, smart quotes,
  # and typographic symbols as literal
  # text, so the original input comes
  # through unchanged.
  options = {input: Parser}
  @doc = Kramdown::Document.new(fenced_code_blocks([*text].flatten.join("\n")), options)
  @width = width
  @ast = []
end

Instance Method Details

#ast ⇒ Array<Node>

Returns:

  • (Array<Node>)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/llm/console/markdown.rb', line 33

def ast
  @ast.tap do
    ##
    # Recursively travels the markdown document and
    # populates the `@ast` variable along the way.
    # The AST is composed of structured data that
    # carries both text and styling information that
    # is applied by the UI thread.
    walk(@doc.root)

    ##
    # This is required because the AST collects
    # empty nodes towards the end of the tree.
    # If we don't pop them we end up with excessive
    # amount of newlines between turns.
    last = @ast.last
    while last and last[:text].to_s.strip.empty?
      @ast.pop
      last = @ast.last
    end
  end
end