Class: Ollama::Handlers::Print

Inherits:
Object
  • Object
show all
Includes:
Concern
Defined in:
lib/ollama/handlers/print.rb

Overview

A handler that prints response content to the output stream.

The Print handler is designed to output text responses from Ollama API commands to a specified output stream. It extracts content from responses and displays it directly, making it useful for interactive terminal applications where immediate feedback is desired.

Examples:

Using the Print handler with a chat command

ollama.chat(model: 'llama3.1', messages:, &Print)

Using the Print handler with a generate command

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

Instance Attribute Summary

Attributes included from Concern

#output, #result

Instance Method Summary collapse

Methods included from Concern

#to_proc

Constructor Details

#initialize(output: $stdout) ⇒ Print

The initialize method sets up a new handler instance with the specified output destination and enables synchronous writing to the output stream.

Parameters:

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

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



20
21
22
23
# File 'lib/ollama/handlers/print.rb', line 20

def initialize(output: $stdout)
  super
  @output.sync = true
end

Instance Method Details

#call(response) ⇒ self

The call method processes a response by printing its content to the output stream.

This method extracts content from the response object and prints it to the configured output stream. If the response indicates completion, it adds a newline character after printing. The method returns the handler instance itself to allow for method chaining.

Parameters:

Returns:

  • (self)

    returns the handler instance after processing the response



36
37
38
39
40
41
42
# File 'lib/ollama/handlers/print.rb', line 36

def call(response)
  if content = response.response || response.message&.content
    @output.print content
  end
  response.done and @output.puts
  self
end