Class: Ollama::Handlers::Single

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

Overview

A handler that collects responses and returns either a single response or an array of responses.

The Single handler is designed to accumulate responses during command execution and provides a result that is either the single response when only one is present, or the complete array of responses when multiple are collected.

Examples:

Using the Single handler to collect a single response

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

Instance Attribute Summary

Attributes included from Concern

#output

Instance Method Summary collapse

Methods included from Concern

#to_proc

Constructor Details

#initialize(output: $stdout) ⇒ Single

The initialize method sets up a new handler instance with the specified output destination and initializes an empty array for collecting responses.

defaults to $stdout

Parameters:

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

    the output stream to be used for handling responses,



19
20
21
22
# File 'lib/ollama/handlers/single.rb', line 19

def initialize(output: $stdout)
  super
  @array = []
end

Instance Method Details

#call(response) ⇒ self

The call method processes a response by appending it to an internal array.

This method is responsible for handling individual responses during command execution by storing them in an internal array for later retrieval. It supports method chaining by returning the handler instance itself after processing.

Parameters:

  • response (Ollama::Response)

    the response object to be processed and stored

Returns:

  • (self)

    returns the handler instance itself after processing the response



34
35
36
37
# File 'lib/ollama/handlers/single.rb', line 34

def call(response)
  @array << response
  self
end

#resultOllama::Response, ...

The result method returns the collected response data from handler operations.

This method provides access to the accumulated results after a command has been executed with a handler that collects responses. It returns either a single response when only one result is present, or the complete array of responses when multiple results are collected.

Returns:

  • (Ollama::Response, Array<Ollama::Response>, nil)

    the collected response data, which may be a single response, an array of responses, or nil if no responses were collected



49
50
51
# File 'lib/ollama/handlers/single.rb', line 49

def result
  @array.size <= 1 ? @array.first : @array
end