Class: OllamaChat::FollowChat

Inherits:
Object
  • Object
show all
Includes:
Ollama, Ollama::Handlers::Concern, Feedback, MessageFormat, Utils::ValueFormatter, Term::ANSIColor
Defined in:
lib/ollama_chat/follow_chat.rb

Overview

A class that handles chat responses and manages the flow of conversation between the user and Ollama models.

This class is responsible for processing Ollama API responses, updating message history, displaying formatted output to the terminal, and managing voice synthesis for spoken responses. It acts as a handler for streaming responses and ensures proper formatting and display of both regular content and thinking annotations.

Constant Summary

Constants included from Feedback

OllamaChat::Feedback::PREFIXES

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Feedback

#feedback

Methods included from Utils::ValueFormatter

#format_bytes, #format_tokens

Methods included from MessageFormat

#display_sender, #message_type, #role_color, #role_template, #sender_name_displayed, #talk_annotate, #think_annotate

Constructor Details

#initialize(chat:, messages:, group_uuid: nil, voice: nil, output: STDOUT) ⇒ OllamaChat::FollowChat

Initializes a new instance of OllamaChat::FollowChat.

Parameters:

  • chat (OllamaChat::Chat) —

    The chat object, which represents the conversation context.

  • messages (#to_a) —

    A collection of message objects, representing the conversation history.

  • group_uuid (String, nil) (defaults to: nil) —

    The group UUID for the conversation.

  • voice (String, nil) (defaults to: nil) —

    (optional) The voice to speak with.

  • output (IO) (defaults to: STDOUT) —

    (optional) The output stream where terminal output should be printed. Defaults to STDOUT.



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/ollama_chat/follow_chat.rb', line 29

def initialize(chat:, messages:, group_uuid: nil, voice: nil, output: STDOUT)
  super(output:)
  @chat       = chat
  output.sync = true
  @messages   = messages
  @group_uuid = group_uuid
  @sender     = nil
  @say        = if voice && @chat.voice_handler.respond_to?(:new)
                  @chat.voice_handler.new(chat:, voice:)
                else
                  NOP
                end
end

Instance Attribute Details

#chat ⇒ OllamaChat::Chat (readonly)

Returns the chat object representing the conversation context.

Returns:



46
47
48
# File 'lib/ollama_chat/follow_chat.rb', line 46

def chat
  @chat
end

#messages ⇒ OllamaChat::MessageList<OllamaChat::Message> (readonly)

Returns the conversation history (an array of message objects).

Returns:



52
53
54
# File 'lib/ollama_chat/follow_chat.rb', line 52

def messages
  @messages
end

Instance Method Details

#call(response) ⇒ OllamaChat::FollowChat

Invokes the chat flow based on the provided Ollama server response.

The response is expected to be a parsed JSON object containing information about the user input and the assistant's response.

If the response indicates an assistant message, this method:

1. Ensures that an assistant response exists in the message history (if
 not already present).
2. Updates the last message with the new content and thinking (if
 applicable).
3. Displays the formatted terminal output for the user.
4. Outputs the voice response (if configured).

Regardless of whether an assistant message is present, this method also outputs evaluation statistics (if applicable).

Parameters:

  • response (Ollama::Response) —

    The parsed JSON response from the Ollama server.

Returns:



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/ollama_chat/follow_chat.rb', line 74

def call(response)
  debug_output(response)

  if response&.message&.role == 'assistant'
    ensure_assistant_response_exists
    update_last_message(response)
    if chat.stream.on?
      display_formatted_terminal_output(height: Tins::Terminal.lines - 1)
    else
      if display_output
        display_formatted_terminal_output
      end
    end
    @say.call(response)
  end

  output_eval_stats(response)

  chat.tool_call_processor.handle(response)

  self
end

#debug_output(response) ⇒ Object (private)

The debug_output method conditionally outputs the response object using jj when debugging is enabled.

Parameters:

  • response (Object) —

    the response object to be outputted



295
296
297
# File 'lib/ollama_chat/follow_chat.rb', line 295

def debug_output(response)
  chat.debug and chat.log(:debug, response.to_json)
end

#display_formatted_terminal_output(height: 0) ⇒ Object (private)

The display_formatted_terminal_output method formats and outputs the terminal content by processing the last message's content and thinking, then prints it to the output. It handles markdown parsing and annotation based on chat settings, and ensures proper formatting with clear screen and move home commands. The method takes into account whether markdown and thinking modes are enabled to determine how to process and display the content.

Parameters:

  • height (Integer) (defaults to: 0) —

    the maximum number of lines to truncate the output to. Defaults to 0 (no truncation).



214
215
216
217
218
219
# File 'lib/ollama_chat/follow_chat.rb', line 214

def display_formatted_terminal_output(height: 0)
  output.print(
    move_home, erase_in_display(nil),
    last_message_with_user(height:)
  )
end

#display_output ⇒ nil, String (private)

The display_output method shows the last message in the conversation.

This method delegates to the messages object's show_last method, which displays the most recent non-user message in the conversation history. It is typically used to provide message to the user about the last response from the assistant.

Returns:

  • (nil, String) —

    the pager command or nil if no paging was performed.



229
230
231
232
233
234
235
236
237
# File 'lib/ollama_chat/follow_chat.rb', line 229

def display_output
  @messages.use_pager do |output|
    if chat.markdown.on?
      display_formatted_terminal_output(output)
    else
      output.print(last_message_with_user)
    end
  end
end

#ensure_assistant_response_exists ⇒ Object (private)

The ensure_assistant_response_exists method ensures that the last message in the conversation is from the assistant role.

If the last message is not from an assistant, it adds a new assistant message with empty content and optionally includes thinking content if the chat's think mode is enabled. It also updates the sender display variable to reflect the assistant's message type and styling.



125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/ollama_chat/follow_chat.rb', line 125

def ensure_assistant_response_exists
  if @messages&.last&.role != 'assistant'
    message = Message.new(
      role:        'assistant',
      sender_name: chat.assistant,
      content:     '',
      thinking:    ('' if chat.think?),
      group_uuid:  @group_uuid
    )
    @messages << message
    @sender = display_sender(message)
  end
end

#eval_stats(stats) ⇒ String (private)

The eval_stats method processes a statistics hash and formats it into a colored, readable string output.

Parameters:

  • stats (Hash) —

    the statistics hash containing evaluation metrics

Returns:

  • (String) —

    a formatted string with statistical information about the evaluation process including durations, counts, and rates, styled with colors and formatting



267
268
269
270
271
272
273
274
# File 'lib/ollama_chat/follow_chat.rb', line 267

def eval_stats(stats)
  stats_text = stats.
    deep_transform(value: -> idx, v { idx =~ /_rate\z/ ? bold(v) + color(111) : v }).
    map { _1 * ?= } * ' '
  '📊 ' + color(111) {
    Kramdown::ANSI::Width.wrap(stats_text, percentage: 90).gsub(/(?<!\A)^/, '   ')
  }
end

#last_message_with_user(height: 0) ⇒ String (private)

The last_message_with_user method constructs a formatted string by combining user information, newline characters, thinking annotations, and content for display in the terminal output.

Parameters:

  • height (Integer) (defaults to: 0) —

    the maximum number of lines to truncate the output to. Defaults to 0 (no truncation).

Returns:

  • (String) —

    the formatted message string containing the user identifier, newline character, thinking annotation (if present), and content formatted for terminal display



190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/ollama_chat/follow_chat.rb', line 190

def last_message_with_user(height: 0)
  content, thinking = prepare_last_message
  content ||= ''
  result = if thinking.present?
             [ @sender + ":\n", thinking, ?\n, content ]
           else
             [ @sender + ":\n", content ]
           end * ''
  if height > 0
    result = truncate_for_terminal(result, max_lines: height)
  end
  result
end

#output_eval_stats(response) ⇒ Object (private)

The output_eval_stats method extracts performance statistics from the response, logs them to the chat history, and prints a formatted summary to the terminal.

Parameters:

  • response (Object) —

    the response object containing evaluation data



280
281
282
283
284
285
286
287
288
289
# File 'lib/ollama_chat/follow_chat.rb', line 280

def output_eval_stats(response)
  response.done or return
  stats = stats_hash(response)
  chat.log(:info, 'Ollama chat response received', data: { stats: })
  feedback(<<~EOT)

    \u{1F9E0} #{bold { 'Context Usage' }}: #{chat.context_usage_colored}
    #{eval_stats(stats)}
  EOT
end

#prepare_last_message ⇒ Array<String, String>, Array<String, nil> (private)

The prepare_last_message method processes and formats content and thinking annotations for display.

This method prepares the final content and thinking text by applying appropriate formatting based on the chat's markdown and think loud settings. It handles parsing of content through Kramdown::ANSI when markdown is enabled, and applies annotation formatting to both content and thinking text according to the chat's configuration.

Returns:

  • (Array<String, String>) —

    an array containing the processed content and thinking text

  • (Array<String, nil>) —

    an array containing the processed content and nil if thinking is disabled



166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/ollama_chat/follow_chat.rb', line 166

def prepare_last_message
  content, thinking = @messages.last.content, @messages.last.thinking
  if chat.markdown.on?
    content = talk_annotate { chat.kramdown_ansi_parse(content) }
    if chat.think?
      thinking = think_annotate { chat.kramdown_ansi_parse(thinking) }
    end
  else
    content = talk_annotate { content }
    chat.think? and thinking = think_annotate { thinking }
  end
  return content&.chomp, thinking&.chomp
end

#stats_hash(response) ⇒ Hash (private)

Extracts performance statistics from an Ollama response and formats them into a hash of human-readable strings and metrics.

Parameters:

  • response (Object) —

    the response object containing evaluation metrics

Returns:

  • (Hash) —

    a hash of formatted statistics including durations, counts, and rates



244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/ollama_chat/follow_chat.rb', line 244

def stats_hash(response)
  eval_duration        = response.eval_duration.to_f / 1e9
  prompt_eval_duration = response.prompt_eval_duration.to_f / 1e9
  {
    eval_duration:        Tins::Duration.new(eval_duration).to_s,
    eval_count:           response.eval_count.to_i,
    eval_rate:            "%.2f t/s" % (response.eval_count.to_i / eval_duration),
    prompt_eval_duration: Tins::Duration.new(prompt_eval_duration).to_s,
    prompt_eval_count:    response.prompt_eval_count.to_i,
    prompt_eval_rate:     "%.2f t/s" % (response.prompt_eval_count.to_i / prompt_eval_duration),
    total_duration:       Tins::Duration.new(response.total_duration / 1e9).to_s,
    load_duration:        Tins::Duration.new(response.load_duration / 1e9).to_s,
  }
end

#truncate_for_terminal(text, max_lines: Tins::Terminal.lines) ⇒ String (private)

The truncate_for_terminal method processes text to fit within a specified number of lines.

This method takes a text string and trims it to ensure it doesn't exceed the maximum number of lines allowed for terminal display. If the text exceeds the limit, only the last N lines are retained where N equals the maximum lines parameter.

Parameters:

  • text (String) —

    the text content to be processed

  • max_lines (Integer) (defaults to: Tins::Terminal.lines) —

    the maximum number of lines allowed (defaults to terminal lines)

Returns:

  • (String) —

    the text truncated to fit within the specified line limit



111
112
113
114
115
116
# File 'lib/ollama_chat/follow_chat.rb', line 111

def truncate_for_terminal(text, max_lines: Tins::Terminal.lines)
  max_lines = max_lines.clamp(1..)
  lines = text.lines
  return text if lines.size <= max_lines
  lines[-max_lines..-1].join('')
end

#update_last_message(response) ⇒ Object (private)

The update_last_message method appends the content of a response to the last message in the conversation. It also appends thinking content to the last message if thinking is enabled and thinking content is present.

Parameters:

  • response (Object) —

    the response object containing message content and thinking



145
146
147
148
149
150
# File 'lib/ollama_chat/follow_chat.rb', line 145

def update_last_message(response)
  @messages.last.content << response.message&.content
  if chat.think? and response_thinking = response.message&.thinking.full?
    @messages.last.thinking << response_thinking
  end
end