Class: Ollama::Handlers::Markdown

Inherits:
Object
  • Object
show all
Includes:
Concern, Term::ANSIColor
Defined in:
lib/ollama/handlers/markdown.rb

Overview

A handler that processes responses by rendering them as ANSI-markdown output.

This class is designed to display streaming or non-streaming responses in a formatted markdown style using ANSI escape codes for terminal rendering. It supports both continuous and single-message display modes, making it suitable for interactive terminal applications where styled text output is desired.

Examples:

Displaying a response as markdown

ollama.generate(model: 'llama3.1', prompt: 'Hello World', &Markdown)

Instance Attribute Summary

Attributes included from Concern

#output, #result

Instance Method Summary collapse

Methods included from Concern

#to_proc

Constructor Details

#initialize(output: $stdout, stream: true) ⇒ Markdown

The initialize method sets up a new handler instance with the specified output destination and streaming behavior.

Parameters:

  • output (IO) (defaults to: $stdout)

    the output stream to be used for handling responses, defaults to $stdout

  • stream (TrueClass, FalseClass) (defaults to: true)

    whether to enable streaming mode, defaults to true



23
24
25
26
27
28
# File 'lib/ollama/handlers/markdown.rb', line 23

def initialize(output: $stdout, stream: true)
  super(output:)
  @stream      = stream
  @output.sync = @stream
  @content     = ''
end

Instance Method Details

#call(response) ⇒ self

The call method processes a response by rendering its content as ANSI-markdown.

This method handles the display of response content in a formatted markdown style using ANSI escape codes for terminal rendering. It supports both streaming and non-streaming modes, allowing for continuous updates or single-message display.

to be rendered

response

Parameters:

Returns:

  • (self)

    returns the handler instance itself after processing the



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/ollama/handlers/markdown.rb', line 43

def call(response)
  if content = response.response || response.message&.content
    if @stream
      @content << content
      markdown_content = Kramdown::ANSI.parse(@content)
      @output.print clear_screen, move_home, markdown_content
    else
      markdown_content = Kramdown::ANSI.parse(content)
      @output.print markdown_content
    end
  end
  self
end