Module: OllamaChat::Information

Extended by:
Tins::Concern
Includes:
Utils::Redact
Included in:
Chat
Defined in:
lib/ollama_chat/information.rb

Overview

A module that provides information and user agent functionality for OllamaChat

The Information module encapsulates methods for managing application identification, displaying version and configuration details, and providing a modular information dashboard for chat sessions. It includes user agent capabilities for HTTP requests and provides focused information views.

Examples:

Displaying application information

chat.info

Showing version details

chat.version

Displaying usage help

chat.usage

Defined Under Namespace

Modules: UserAgent

Instance Method Summary collapse

Methods included from Utils::Redact

#redact_password, redact_password

Instance Method Details

#client ⇒ String

The client method returns the application name and its current version as a single string

Returns:

  • (String) —

    the progname followed by the OllamaChat version separated by a space



63
64
65
# File 'lib/ollama_chat/information.rb', line 63

def client
  [ progname, OllamaChat::VERSION ] * ' '
end

#collection_stats(output: STDOUT) ⇒ Object

The collection_stats method displays statistics about the current document collection.

This method outputs information regarding the active document collection, including the collection name, total number of embeddings, and a list of tags.

Parameters:

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

    the output stream to write the message to



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

def collection_stats(output: STDOUT)
  col          = database_collection?(collection)
  length       = (Tins::Terminal.cols - 10).clamp(0..)
  wrapped_tags =
    wrap(@documents.tags.to_a.join(', '), length:).
    gsub(/(?<!\A)^/, ' ' * 4)
  output.puts <<~EOT
    Current Collection
      Name: #{bold{collection}}
      Status: #{col&.enabled ? '✅' : '⛔'}
      Patterns: #{italic{col&.patterns.full?(:join, ' ') || '∅' }}
      #Embeddings: #{@documents.size}
      #Tags: #{@documents.tags.size}
      Tags:
        #{wrapped_tags}
  EOT
  nil
end

#context_filled ⇒ Float

Computes the fraction of the context window currently in use.

Delegates to ContextUsage#filled; clamped to 0.0–1.0.

Returns:

  • (Float) —

    the ratio of used context (e.g. 0.73 for 73%)



461
462
463
# File 'lib/ollama_chat/information.rb', line 461

def context_filled
  context_usage.filled
end

#context_usage ⇒ ContextUsage (private)

Lazily builds and caches the ContextUsage bound to this chat, which owns the ANSI/emoji presentation logic for context usage.

Returns:



540
541
542
# File 'lib/ollama_chat/information.rb', line 540

def context_usage
  @context_usage ||= OllamaChat::ContextUsage.new(self)
end

#context_usage_colored ⇒ String

The context_usage_colored method returns a summary string of the current context window's token usage, with the used, maximum, and percentage values all ANSI-colored according to the compaction thresholds.

Delegates the presentation (emoji + color) to ContextUsage.

Returns:

  • (String) —

    the formatted, colored string representing context usage



135
136
137
# File 'lib/ollama_chat/information.rb', line 135

def context_usage_colored
  context_usage.colored
end

#context_usage_plain ⇒ String?

Formats the current context usage as a human-readable string.

Returns a string like "167.7 KT of 262.1 KT (64.0%)" combining the estimated tokens in use, the effective context length, and the percentage. Delegates to ContextUsage#plain.

Returns:

  • (String, nil) —

    the formatted usage string, or nil if the context length cannot be determined.



473
474
475
# File 'lib/ollama_chat/information.rb', line 473

def context_usage_plain
  context_usage.plain
end

#conversation_length ⇒ String

Returns a formatted string representing the estimated text length of the full stored conversation, excluding images and JSON scaffolding.

Delegates to MessageList#full_estimate_tokens, which sums per-message token_estimate (content + optional thinking) across all messages, respecting the think_strip toggle. This differs from Session#estimate_tokens, which measures raw JSONL bytes including base64 images and metadata — the latter is the storage footprint, this is the model-facing text volume.

Returns:

  • (String) —

    formatted as "340.5 KT (1.2 MiB)"



373
374
375
376
# File 'lib/ollama_chat/information.rb', line 373

def conversation_length
  es = messages.full_estimate_tokens
  "%s (%s)" % [ es.tokens_formatted, es.bytes_formatted ]
end

#current_context_length ⇒ Integer, NilClass

Resolves the effective context window size for the current model.

Prefers the session-level num_ctx override (set via /model_options or the stored model options profile). Falls back to the model's native context_length in the default profile or as reported by the Ollama server if possible.

Returns:

  • (Integer, NilClass) —

    the context length in tokens or nil



450
451
452
453
454
# File 'lib/ollama_chat/information.rb', line 450

def current_context_length
  get_session_model_options[:num_ctx] ||
  get_stored_model_options(@model)[:num_ctx] ||
    ollama.ps&.models&.find { _1.name == @model }&.context_length
end

#display_chat_help(pattern = nil) ⇒ Object

The display_chat_help method outputs the chat help message to standard output, eventually using the configured pager.

Parameters:

  • pattern (String, Regexp, nil) (defaults to: nil) —

    An optional pattern to filter the commands displayed in the help message.



255
256
257
258
259
260
# File 'lib/ollama_chat/information.rb', line 255

def display_chat_help(pattern = nil)
  use_pager do |output|
    output.puts help_message(pattern)
  end
  nil
end

#dynamic_runtime_information ⇒ String

The dynamic_runtime_information method generates a formatted string containing real-time environment details (the "heartbeat").

It returns the result of interpolating the dynamic values into the configured dynamic_runtime_info prompt template.

Returns:

  • (String) —

    the formatted dynamic runtime information string.



412
413
414
415
416
# File 'lib/ollama_chat/information.rb', line 412

def dynamic_runtime_information
  prompt(:dynamic_runtime_info).to_s.named_placeholders_interpolate(
    dynamic_runtime_information_values
  )
end

#dynamic_runtime_information_values ⇒ Hash

The dynamic_runtime_information_values method compiles a set of volatile runtime details that change frequently.

These include the current timestamp, weekday, session name, git branch and origin, terminal dimensions, and feature switch statuses.

Returns:

  • (Hash) —

    a hash containing dynamic runtime values.



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/ollama_chat/information.rb', line 385

def dynamic_runtime_information_values
  now = Time.now
  {
    git_current_branch:   `git rev-parse --abbrev-ref HEAD 2>/dev/null`.chomp.full? || 'n/a',
    git_remote_origin:    `git remote get-url origin 2>/dev/null`.chomp.full? || 'n/a',
    git_sha:              `git rev-parse HEAD 2>/dev/null`.chomp.full? || 'n/a',
    git_sha_short:        `git rev-parse --short HEAD 2>/dev/null`.chomp.full? || 'n/a',
    markdown:             markdown.on? ? 'enabled' : 'disabled',
    session_name:         session.name,
    terminal_cols:        Tins::Terminal.cols,
    terminal_rows:        Tins::Terminal.rows,
    time:                 now.iso8601,
    tools_support:        tools_support.on? ? 'enabled' : 'disabled',
    voice:                voice.on? ? 'enabled' : 'disabled',
    weekday:              now.strftime('%A'),
    context_usage:        context_usage_plain,
    conversation_length:  ,
  }
end

#info(output: STDOUT) ⇒ Object

Displays a high-level summary dashboard of the current state of the ollama_chat instance.

Parameters:

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

    the output stream to write the information to, defaults to STDOUT



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/ollama_chat/information.rb', line 233

def info(output: STDOUT)
  print_welcome(output:)
  output.puts "📜 Documents database cache is #{@documents.nil? ? 'n/a' : bold{@documents.cache.class}}"
  output.puts "🔎 Currently selected search engine is #{bold{search_engine}}."
  output.puts "🧠 Current chat model is #{bold{@model}}."
  output.puts "🗣️ Session: #{bold{@session.name}} (#{italic{@session.id}})"
  output.puts "  Current System Prompt: #{bold{current_system_prompt_name}}"
  if name = default_persona_name
    output.puts "  💃 Persona: #{bold{name}}"
  else
    output.puts "  No persona selected."
  end
  output.print '  🛠️ '; tools_support.show(output:)
  output.print '  🏃 '; runtime_info.show(output:)
  nil
end

#info_model(output: STDOUT) ⇒ Object

Displays detailed information about the current chat model, including capabilities, families, and configuration options.

Parameters:

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

    the output stream to print the model information to (defaults to STDOUT).



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/ollama_chat/information.rb', line 99

def info_model(output: STDOUT)
  output.puts "🧠 Current chat model is #{bold{@model}}."
  output.puts   "  Families: #{Array(@model_metadata&.families) * ', '}"
  output.puts   "  Capabilities: #{Array(@model_metadata&.capabilities) * ', '}"
  if @model_metadata&.thinking
    thinking = @model_metadata.thinking
    levels   = Array(thinking.values).map { normalize_think_state(_1) }
    default  = normalize_think_state(thinking.default)
    output.puts "  Thinking: #{levels * ', '} (default: #{bold{default}})"
  end

  profiles = models::ModelOptions.where(model_name: @model).order(:profile).all
  if profiles.full?
    output.puts "  Stored Profile Options:"
    profiles.each do |p|
      output.puts <<~EOT.gsub(/^/, '      ')
        #{bold{p.profile}}:
          #{JSON.pretty_generate(p.options)}
      EOT
    end
  elsif config.model.options.full?
    output.puts "  Default Options: #{JSON.pretty_generate(mo).gsub(/(?<!\A)^/, '  ')}"
  end

  if model_options.present?
    output.puts "  Session Options: #{JSON.pretty_generate(model_options).gsub(/(?<!\A)^/, '  ')}"
  end
end

#info_rag(output: STDOUT) ⇒ Object

Displays information regarding the Retrieval Augmented Generation (RAG) configuration, including the embedding model and collection statistics.

Parameters:

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

    the output stream to write the information to, defaults to STDOUT



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/ollama_chat/information.rb', line 191

def info_rag(output: STDOUT)
  if embedding.on?
    if base_url = OC::OLLAMA::EMBEDDING_URL?
      output.puts "🔌 Connected to embedding ollama server on: #{redact_password(base_url)}"
    end
    output.puts "🗄️ Current RAG model is #{bold{@embedding_model}}"
    if @embedding_model_options.present?
      output.puts "  Options: #{JSON.pretty_generate(@embedding_model_options).gsub(/(?<!\A)^/, '  ')}"
    end
    output.puts "Text splitter is #{bold{config.embedding.splitter.name}}."
    collection_stats(output:)
    if session.trigger.full?
      session.trigger.each do |col, cfg|
        state = cfg['enabled'] ? '✅' : '⛔'
        output.puts "\u26A1 Trigger: #{state} #{bold{col}}"
        output.puts "     Prompt: #{bold{cfg['prompt_name']}}"
        output.puts "     Text count: #{cfg['text_count'] || 'unlimited'}"
      end
    end
  end
  embedding.show(output:)
  output.puts "📜 Document policy for parsing in user text: #{bold{document_policy}}"
end

#info_runtime(output: STDOUT) ⇒ Object

Displays the current runtime environment details, split into static (session-level) and dynamic (real-time) information.

Parameters:

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

    the output stream to write the information to, defaults to STDOUT



176
177
178
179
180
181
182
183
184
185
# File 'lib/ollama_chat/information.rb', line 176

def info_runtime(output: STDOUT)
  output.puts "🏃 Runtime Information:"
  output.print '  '; runtime_info.show(output:)
  output.puts 'Static:'
  output.puts static_runtime_information_values.stringify_keys_recursive.to_yaml.
    sub(/\A---\s*\n/, '').gsub(/^/, '  ')
  output.puts 'Dynamic:'
  output.puts dynamic_runtime_information_values.stringify_keys_recursive.to_yaml.
    sub(/\A---\s*\n/, '').gsub(/^/, '  ')
end

#info_session(output: STDOUT) ⇒ Object

Displays a detailed view of the current chat session state, including the system prompt, persona, active model, thinking modes, tools, and audio settings.

Parameters:

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

    the output stream to write the information to, defaults to STDOUT



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/ollama_chat/information.rb', line 144

def info_session(output: STDOUT)
  output.print "🗣️ Current session: "; show_session(output:)
  output.puts "  Current Session Working Directory: \"#{bold{session.working_directory}}\""
  output.puts "  Current System Prompt: #{bold{current_system_prompt_name}}"
  if name = default_persona_name
    output.puts "  💃 Persona: #{bold{name}}"
  else
    output.puts "  No persona selected."
  end
  output.puts "🧠 Current chat model is #{bold{@model}}."
  output.puts  "  Context Usage: #{context_usage_colored}"
  output.puts  "  Conversation Length: #{conversation_length}"
  output.print '  '; think_mode.show(output:)
  output.print '  '; think_loud.show(output:)
  output.print '  '; think_strip.show(output:)
  output.print '  🛠️ '; tools_support.show(output:)
  output.print "\u2699 Chat Settings"
  output.print '  '; markdown.show(output:)
  output.print '  '; stream.show(output:)
  output.print '  🎙️ '; voice.show(output:)
  if voice.on?
    output.print '  '; voices.show(output:)
  end
  output.print '  '; location.show(output:)
  output.print '  '; context_format.show(output:)
  output.print '  '; context_manifest.show(output:)
end

#infobar_message ⇒ Hash

Returns the infobar message configuration as a hash.

This configuration is used by the infobar gem to define the progress bar's format and spinner settings.

Returns:

  • (Hash) —

    the infobar message configuration



328
329
330
# File 'lib/ollama_chat/information.rb', line 328

def infobar_message
  config.infobar.message.to_h
end

#machine_profile ⇒ String (private)

Builds and caches a compact, single-line description of the host machine, derived from a fastfetch run against the bundled profile (+OC::FASTFETCH+). The profile requests a focused set of modules (os, kernel, cpu, gpu, de, wm, terminal, memory, editor, packages, chassis, board, bios) so the result stays small enough to inject into the system prompt at zero per-turn cost.

Gracefully degrades to 'n/a' when fastfetch is not installed or the config is missing, so a missing optional dependency never breaks session startup.

Returns:

  • (String) —

    e.g. C64 1541 (c64) · 6502@1MHz m64 · MOS Technology 6502 · NVIDIA GeForce RTX 5090 (32GB) · VIC-II (no DE) · Home Computer · PET2001N-Board · MOS 3.0 UEFI 4000 · 64 KiB · vim 1.0 · 1 pkgs



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'lib/ollama_chat/information.rb', line 494

def machine_profile
  return @machine_profile if defined?(@machine_profile)
  @machine_profile = nil
  unless fastfetch = OC::FASTFETCH?
    log(:warn, 'Fastfetch executable not found, skipping machine profile!')
    return
  end
  config = Shellwords.escape(File.join(__dir__, 'ollama_chat_config', 'fastfetch-profile.jsonc'))
  out = `#{fastfetch} -c #{config} --format json 2>/dev/null`.full? or return
  mods = JSON.parse(out, object_class: JSON::GenericObject)
  @machine_profile =
    mods.map do |m|
      r = m.result or next
      case m.type
      when 'OS'
        "%s %s (%s)" % [ r.name, r.versionID, r.idLike ]
      when 'Kernel'
        "%s %s" % [ r.release, r.architecture ]
      when 'CPU'
        r.cpu
      when 'GPU'
        (r.find { _1.type == 'Discrete' } || r.first)&.name
      when 'WM'
        suffix = mods.any? { _1.type == 'DE' && _1.result } ? '' : ' (no DE)'
        "%s/%s%s" % [ r.processName, r.protocolName, suffix ]
      when 'Memory'
        format_bytes(r.total)
      when 'Editor'
        "%s %s" % [ r.exe, r.version ]
      when 'Packages'
        "%s pkgs" % r.all
      when 'Chassis'
        r.type
      when 'Board'
        r.name
      when 'BIOS'
        "%s %s" % [ r.type, r.version ]
      end
    end.compact * ' · '
rescue JSON::ParserError
end

The print_welcome method prints a welcome message containing the application version, the connected ollama server version, and the server URL.

Parameters:

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

    the output stream where the welcome messages are printed (default: STDOUT)



221
222
223
224
225
226
# File 'lib/ollama_chat/information.rb', line 221

def print_welcome(output: STDOUT)
  feedback(<<~EOT, output:)
    💎 Running ollama_chat version: #{bold{OllamaChat::VERSION}}
    🔌 Connected to ollama server version: #{bold{server_version}} on: #{bold{redact_password(server_url)}}
  EOT
end

#runtime_information_inject(group_uuid:) ⇒ Object

Injects the current dynamic runtime information (the "heartbeat") as a user-role tool message into the active message list.

The injected message shares the caller's group_uuid so it is grouped with the surrounding conversation exchange. The content is generated by dynamic_runtime_information, which interpolates live values (timestamp, git state, terminal size, context usage) into the configured prompt template.

No-op when the runtime_info switch is off.

Parameters:

  • group_uuid (String) —

    the UUID of the current message group



430
431
432
433
434
435
436
437
438
439
440
# File 'lib/ollama_chat/information.rb', line 430

def runtime_information_inject(group_uuid:)
  runtime_info.on? or return
  tool_name = 'runtime_information'
  messages << OllamaChat::Message.new(
    role:        'user',
    tool_name:   ,
    sender_name: tool_name,
    content:     dynamic_runtime_information,
    group_uuid:
  )
end

#server_url ⇒ String

The server_url method returns the base URL of the Ollama server connection.

Returns:

  • (String) —

    the base URL used for communicating with the Ollama API



304
305
306
# File 'lib/ollama_chat/information.rb', line 304

def server_url
  @server_url ||= ollama.base_url
end

#server_version ⇒ String

The server_version method retrieves the version of the Ollama server.

Returns:

  • (String) —

    the version string of the connected Ollama server



297
298
299
# File 'lib/ollama_chat/information.rb', line 297

def server_version
  @server_version ||= ollama.version.version
end

#static_runtime_information ⇒ String

Generates a formatted string of static runtime information.

This method interpolates the static runtime values into the configured static_runtime_info prompt template.

Returns:

  • (String) —

    a formatted static runtime information string.



356
357
358
359
360
# File 'lib/ollama_chat/information.rb', line 356

def static_runtime_information
  prompt(:static_runtime_info).to_s.named_placeholders_interpolate(
    static_runtime_information_values
  )
end

#static_runtime_information_values ⇒ Hash

Generates a hash containing static runtime information.

This method collects session-level constants including the user, language preferences, location, client version, working directory, allowed tool paths, and available RAG collections.

Returns:

  • (Hash) —

    a hash containing static runtime data.



339
340
341
342
343
344
345
346
347
348
# File 'lib/ollama_chat/information.rb', line 339

def static_runtime_information_values
  {
    client:               ,
    current_directory:    Pathname.pwd.expand_path.to_path,
    languages:            config.languages * ', ',
    location:             location.on?.full? { location_description } || 'n/a',
    machine:              machine_profile || 'n/a',
    user:                 ,
  }
end

#usage ⇒ Integer

The usage method displays the command-line idea help text and returns an exit code of 0.

Returns:

  • (Integer) —

    always returns 0 indicating successful help display



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/ollama_chat/information.rb', line 266

def usage
  feedback(<<~EOT)
    Usage: #{progname} [OPTIONS]

      -f CONFIG      config file to read
      -l SESSION     load session with name/id SESSION
      -n             create a new session
      -u URL         the ollama base url, OLLAMA_URL
      -m MODEL       the ollama chat model, OLLAMA_CHAT_MODEL, ?selector
      -S             open a socket to receive input from ollama_chat_send
      -V             display the current version number and quit
      -h             this help

      Use `?selector` with `-m` or `-l` to filter options. Multiple matches
      will open a chooser dialog.
  EOT
  0
end

#user ⇒ String

Retrieves the name of the chat user.

Returns:

  • (String) —

    the chat user's name or 'n/a' if not set



311
312
313
# File 'lib/ollama_chat/information.rb', line 311

def user
  user_name || 'n/a'
end

#user_name ⇒ String

Retrieves the name of the chat user.

Returns:

  • (String) —

    the chat user's name or nil if not set



318
319
320
# File 'lib/ollama_chat/information.rb', line 318

def user_name
  OC::OLLAMA::CHAT::USER
end

#version ⇒ Integer

The version method outputs the program name and its version number to standard output.

Returns:

  • (Integer) —

    returns 0 indicating successful execution



289
290
291
292
# File 'lib/ollama_chat/information.rb', line 289

def version
  feedback("%s %s" % [ progname, OllamaChat::VERSION ])
  0
end