Class: OllamaChat::Chat

Overview

A chat client for interacting with Ollama models through a terminal interface.

The Chat class provides a complete command-line interface for chatting with language models via the Ollama API. It handles configuration management, message history, document processing, web searching, and various interactive features including voice output, markdown rendering, and embedding capabilities.

Examples:

Initializing a chat session

chat = OllamaChat::Chat.new(argv: ['-m', 'llama3.1'])

Starting an interactive chat

chat.start

Constant Summary

Constants included from Parsing

Parsing::CONTENT_REGEXP, Parsing::DOCUMENT_POLICY_STATES, Parsing::HAS_AUDIO

Constants included from Feedback

Feedback::PREFIXES

Instance Attribute Summary collapse

Attributes included from Utils::Chooser

#current_search_state Stores the

Attributes included from SessionManagement

#session

Attributes included from PersonaeManagement

#default_persona_name

Attributes included from ServerSocket

#server_socket_message

Attributes included from StateSelectors

#context_format, #document_policy, #think_mode, #voices

Attributes included from Switches

#context_manifest, #embedding, #embedding_enabled, #embedding_paused, #location, #markdown, #memory_trigger, #runtime_info, #stream, #think_loud, #think_strip, #tools_support, #voice

Instance Method Summary collapse

Methods included from Utils::UTF8Converter

#convert_to_utf8

Methods included from Utils::ValueFormatter

#format_bytes, #format_tokens

Methods included from Utils::Chooser

#choose_entry, #choose_with_state

Methods included from Compaction

#assemble_summary, #build_tool_entries, #call_summarizer, #compact_min_tokens, #compact_ratio, #compact_ratio_tokens, #compact_with_retry, #extract_narrative, #extract_old_tool_calls, #format_summary_line, #report_compaction, #serialize_groups, #show_compaction_summary, #summarize_for_compaction, tool_summary_line

Methods included from PromptManagement

#add_new_prompt, #all_prompts, #choose_and_delete_prompt, #choose_and_edit_prompt, #choose_and_reset_count, #choose_prompt, #choose_prompt_context, #determine_valid_new_name_for_prompt, #duplicate_prompt, #export_prompt, #import_prompt, #info_prompt, #list_prompts, #prepare_conversation_history, #prompt_sync, #prompt_with_favourite, #rename_prompt, #reset_prompt_count, #reset_prompt_to_default, #show_prompt_diff, #suggest_prompts

Methods included from SystemPromptManagement

#all_system_prompts, #change_system_prompt, #current_system_prompt, #current_system_prompt_name, #model_default_system_prompt, #raw_system_prompt, #refresh_system_prompt, #set_current_system_prompt, #setup_system_prompt, #system_prompt_with_favourite

Methods included from PromptHandling

#delete_prompt, #each_prompt, #load_prompt_from_file, #prompt, #store_prompt, #write_prompt

Methods included from FavouritesManagement

#add_favourite, #all_favourited, #delete_favourite, #favourite_all_things, #prefix_favourite

Methods included from RAGHandling

#all_collections, #choose_collection, #clear_collection_sources, #clear_collection_tags, #clear_tag_records, #clear_whole_collection, #collection, #collection_descriptions, #create_collection, #create_memory_collection, #database_collection?, #delete_collection, #edit_collection, #extract_patterns, #list_collections, #memory_dump, #memory_restore, #query_collection, #rename_collection, #set_documents_collection, #switch_collection, #update_collection, #view_tag_records

Methods included from CollectionSearch

#find_document_records, #rerank_records, #trigger_inject

Methods included from SessionManagement

#change_session, #choose_session, #delete_session, #derive_session_name, #determine_valid_new_name_for_session, #duplicate_session, #edit_session_trigger, #generate_conversation_report, #list_sessions, #load_links_from_session, #new_random_session_name, #new_session, #preferred_session, #previous_session, #rename_session, #repair_group_uuids, #report_conversation, #session_apply, #session_close, #session_sync, #set_new_session, #set_previous_session_on_change, #setup_session, #show_session, #store_links_in_session, #store_messages_in_session, #summarize_conversation, #summarize_session

Methods included from PersonaeManagement

#add_persona, #ask_to_set_default_persona_name, #assistant, #available_personae, #available_personae_names, #backup_persona, #choose_persona, #convert_json_character_to_markdown, #default_persona, #default_persona_profile, #delete_persona, #determine_valid_new_name_for_persona, #duplicate_persona, #edit_persona, #export_persona, #import_persona, #import_persona_from_json, #info_persona, #initial_persona_name, #list_personae, #load_persona_file, #load_personae, #pathname_to_persona_name, #persona_backup_pathname, #persona_description, #persona_exist?, #persona_name_to_pathname, #persona_name_with_favourite, #personae_backup_directory, #personae_directory, #personae_result, #play_persona, #select_persona_path, #set_default_persona, #set_default_persona_name, #setup_persona_from_session, #setup_personae_directory, #substitute_variables, #sync_trigger

Methods included from ConfigHandling

#config, #config=, #diff_config, #display_config, #edit_config, #fix_config, #fix_session, #reload_config, #run_syntax_check, #syntax_checker_for

Methods included from ToolCalling

#configured_tools, #default_enabled_tools, #disable_tool, #enable_tool, #enabled_tools, #list_tools, #tool_configured?, #tool_enabled?, #tool_function, #tool_registered?, #tools

Methods included from LocationHandling

#location_data, #location_description, #location_description?

Methods included from MessageEditing

#change_response

Methods included from InputContent

#all_file_set, #choose_filename, #context_spook, #file_set_each, #input, #provide_file_set_content

Methods included from Conversation

#conversation_clean, #load_conversation, #save_conversation

Methods included from FileEditing

#determine_valid_output_filename, #edit_file, #edit_text, #edit_text_block, #perform_insert, #vim

Methods included from KramdownANSI

#configure_kramdown_ansi_styles, #kramdown_ansi_parse, #kramdown_markdown_remove, #table_column_budgets, #wrap_table_rows

Methods included from ServerSocket

create_socket_server, #init_server_socket, send_to_server_socket

Methods included from History

#clear_history, #current_history, #current_history=, #histories, #init_history, #save_history, #switch_history

Methods included from Pager

#determine_pager_command, #use_pager

Methods included from MessageFormat

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

Methods included from Clipboard

#copy_to_clipboard, #last_message_content, #paste_from_clipboard, #paste_from_stdin, #perform_copy_to_clipboard, #perform_paste_from_clipboard

Methods included from MessageOutput

#attempt_to_write_file, #output, #pipe

Methods included from Information

#client, #collection_stats, #context_filled, #context_usage, #context_usage_colored, #context_usage_plain, #conversation_length, #current_context_length, #display_chat_help, #dynamic_runtime_information, #dynamic_runtime_information_values, #info, #info_model, #info_rag, #info_runtime, #info_session, #infobar_message, #machine_profile, #print_welcome, #runtime_information_inject, #server_url, #server_version, #static_runtime_information, #static_runtime_information_values, #usage, #user, #user_name, #version

Methods included from Utils::Redact

#redact_password, redact_password

Methods included from ThinkControl

#normalize_think_state, #think, #think?, #think_loud?, #think_mode_states

Methods included from Dialog

#ask?, #ask_for_filename?, #change_voice, #choose_file_set, #confirm?, #connect_message, #connect_message_done, #go_command, #message_list, #should_overwrite?

Methods included from WebSearching

#manage_links, #search_engine, #search_web, #search_web_with_duckduckgo, #search_web_with_searxng, #web

Methods included from SourceFetching

#add_image, #bulk_embed_sources, #embed, #embed_source, #fetch_source, #fetch_source_as_filename, #import, #import_source, #summarize, #summarize_source

Methods included from Parsing

#epub_read, #parse_atom, #parse_audio, #parse_content, #parse_png, #parse_rss, #parse_source, #pdf_read, #personalize_character_profile, #process_document, #ps_read, #reverse_markdown

Methods included from Utils::AnalyzeDirectory

#generate_structure, #recurse_generate_structure, #structure_each_entry

Methods included from ModelHandling

#all_models, #choose_model, #choose_profile_for_model, #copy_model_options_from_session, #copy_model_options_profile, #copy_model_options_to_session, #delete_model_options_profile, #edit_model_options, #edit_session_model_options, #export_model_options, #fill_up_model_options, #get_default_model_options, #get_session_model_options, #get_stored_model_options, #import_model_options, #model_options, #model_present?, #model_with_size, #prepare_model, #pull_model_from_remote, #pull_model_unless_present, #reconfigure_model_options, #store_model_options, #stored_model_options_exist?, #use_model

Methods included from StateSelectors

#setup_state_selectors

Methods included from Switches

#setup_switches

Methods included from DocumentCache

#configure_cache, #document_cache_class

Methods included from Logging

#log, #logger

Methods included from HTTPHandling

#get_url, #http_options, #links, #request_url_response

Methods included from TokenEstimator

estimate

Methods included from Feedback

#feedback

Constructor Details

#initialize(argv: ARGV.dup) ⇒ Chat

Initializes a new OllamaChat::Chat instance with the given command-line arguments.

Sets up the chat environment including configuration parsing, Ollama client initialization, model selection, system prompt handling, document processing setup, and history management. This method handles all the bootstrapping necessary to create a functional chat session that can communicate with an Ollama server and process various input types including text, documents, web content, and images.

The initialization process includes parsing command-line options using Tins::GO for robust argument handling, setting up the Ollama client with configurable timeouts (connect, read, write), validating Ollama API version compatibility (requires >= 0.9.0 for features used), configuring model selection based on command-line or configuration defaults, initializing system prompts from files or inline content, setting up document processing pipeline with embedding capabilities through Documentrix::Documents, creating message history management through OllamaChat::MessageList, initializing cache systems for document embeddings, setting up voice support and image handling for multimodal interactions, enabling optional server socket functionality for remote input, and handling configuration errors with interactive recovery mechanisms.

Parameters:

  • argv (Array<String>) (defaults to: ARGV.dup) —

    Command-line arguments to parse (defaults to ARGV.dup)

Raises:

  • (RuntimeError) —

    If the Ollama API version is less than 0.9.0, indicating incompatibility with required API features



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/ollama_chat/chat.rb', line 107

def initialize(argv: ARGV.dup)
  @opts               = go 'f:u:m:l:nSVh', argv
  @opts[?h] and exit usage
  @opts[?V] and exit version
  @ollama_chat_config = OllamaChat::OllamaChatConfig.new(@opts[?f])
  self.config         = @ollama_chat_config.config
  truncate_logs
  @messages           = OllamaChat::MessageList.new(self)
  OllamaChat::Database.setup_models.each { _1.ask_and_send(:seed, self) }
  setup_switches
  setup_session
  setup_state_selectors(config)
  @model_cache = ModelCache.new
  connect_ollama
  connect_embedding_ollama
  @documents = setup_documents
  models::Collection.sync(self)
  @cache                = setup_cache
  @images               = []
  @kramdown_ansi_styles = configure_kramdown_ansi_styles
  @tool_call_processor  = OllamaChat::ToolCallProcessor.new(chat: self)
  setup_personae_directory
  @opts[?S] and init_server_socket
rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e
  fix_config(e)
end

Instance Attribute Details

#cache ⇒ OllamaChat::RedisCache? (readonly)

Provides read-only access to the cache instance used by the object.

Returns:



168
169
170
# File 'lib/ollama_chat/chat.rb', line 168

def cache
  @cache
end

#documents ⇒ Documentrix::Documents (readonly)

Returns the documents set for this object, initializing it lazily if needed.

The documents set is memoized, meaning it will only be created once per object instance and subsequent calls will return the same Documentrix::Documents instance.

Returns:

  • (Documentrix::Documents) —

    A Documentrix::Documents object containing all documents associated with this instance



148
149
150
# File 'lib/ollama_chat/chat.rb', line 148

def documents
  @documents
end

#images ⇒ Array (readonly)

Returns the list of images currently queued for the next message.

Returns:

  • (Array) —

    a list of images to be sent with the next prompt



163
164
165
# File 'lib/ollama_chat/chat.rb', line 163

def images
  @images
end

#messages ⇒ OllamaChat::MessageList (readonly)

Returns the messages set for this object, initializing it lazily if needed.

The messages set is memoized, meaning it will only be created once per object instance and subsequent calls will return the same OllamaChat::MessageList instance.

Returns:



158
159
160
# File 'lib/ollama_chat/chat.rb', line 158

def messages
  @messages
end

#model_cache ⇒ ModelCache (readonly)

The model_cache method provides read-only access to the model cache.

Returns:



173
174
175
# File 'lib/ollama_chat/chat.rb', line 173

def model_cache
  @model_cache
end

#ollama ⇒ Ollama::Client (readonly)

The ollama reader returns the Ollama API client instance.

Returns:

  • (Ollama::Client) —

    the configured Ollama API client



137
138
139
# File 'lib/ollama_chat/chat.rb', line 137

def ollama
  @ollama
end

#prefill_prompt ⇒ String, NilClass (private)

Returns the prefill prompt string if one exists and is not empty, or nil otherwise.

Returns:

  • (String, NilClass) —

    the prefill prompt string, or nil if not set or empty



424
425
426
# File 'lib/ollama_chat/chat.rb', line 424

def prefill_prompt
  @prefill_prompt.full?
end

#prefill_prompt==(value) ⇒ String, NilClass (writeonly, private)

Sets the content to be prefilled into the next user input prompt.

Returns:

  • (String, NilClass) —

    the prompt



431
# File 'lib/ollama_chat/chat.rb', line 431

attr_writer :prefill_prompt

#tool_call_processor ⇒ OllamaChat::ToolCallProcessor (readonly)

Returns the tool call processor instance.

Returns:



354
355
356
# File 'lib/ollama_chat/chat.rb', line 354

def tool_call_processor
  @tool_call_processor
end

Instance Method Details

#add_documents_from_argv(document_list) ⇒ Object (private)

Note:

Empty entries in the document list will trigger a collection clear operation

Note:

Documents are processed in batches of 25 to manage memory usage

Note:

Progress is reported to STDOUT during processing

Adds documents from command line arguments to the document collection.

Processes a list of document paths or URLs, handling both local files and remote resources.

Examples:

Adding local files

add_documents_from_argv(['/path/to/file1.txt', '/path/to/file2.pdf'])

Adding remote URLs

add_documents_from_argv(['https://example.com/page1', 'http://example.com/page2'])

Mixed local and remote

add_documents_from_argv(['/local/file.txt', 'https://remote.com/document'])

Parameters:

  • document_list (Array<String>) —

    List of document paths or URLs to process



725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# File 'lib/ollama_chat/chat.rb', line 725

def add_documents_from_argv(document_list)
  if document_list.any?(&:empty?)
    feedback("Clearing collection #{bold{collection}}.", type: :info)
    documents.clear
    document_list.reject!(&:empty?)
  end
  unless document_list.empty?
    document_list.map! do |doc|
      if doc =~ %r(\Ahttps?://)
        doc
      else
        File.expand_path(doc)
      end
    end
    feedback("Collection #{bold{collection}}: Adding #{document_list.size} documents…", type: :info)
    count = 1
    document_list.each_slice(25) do |docs|
      docs.each do |doc|
        fetch_source(doc) do |doc_io|
          embed_source(doc_io, doc, count:)
        end
        count += 1
      end
    end
  end
end

#base_url ⇒ String (private)

The base_url method returns the Ollama server URL from command-line options or environment configuration.

Returns:

  • (String) —

    the base URL used for connecting to the Ollama API



617
618
619
# File 'lib/ollama_chat/chat.rb', line 617

def base_url
  @opts[?u] || OC::OLLAMA::URL
end

#call_ollama_chat(**opts, &block) ⇒ Object (private)

Wrapper for ollama.chat to provide consistent logging of all arguments.

Parameters:

  • opts (Hash) —

    keyword arguments for the chat call

  • block (Proc) —

    optional handler block



362
363
364
365
366
367
368
369
370
371
# File 'lib/ollama_chat/chat.rb', line 362

def call_ollama_chat(**opts, &block)
  if debug
    log(:debug, "Ollama chat request sent", data: opts)
  else
    clean_opts = opts.dup
    clean_opts = clean_opts.slice!(:messages, :tools)
    log(:info, "Ollama chat request sent", data: clean_opts)
  end
  ollama.chat(**opts, &block)
end

#connect_embedding_ollama ⇒ Ollama::Client? (private)

Establishes a dedicated Ollama connection for embedding operations.

When OC::OLLAMA::EMBEDDING_URL is configured, creates a separate Ollama::Client targeting that host so the embedding model can run on a different machine (e.g. a GPU box running audio.cpp alongside the embedding model) while the chat model stays on the primary Ollama server.

Returns:

  • (Ollama::Client, nil) —

    the embedding client, or nil when no dedicated embedding URL is configured



689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
# File 'lib/ollama_chat/chat.rb', line 689

def connect_embedding_ollama
  if base_url = OC::OLLAMA::EMBEDDING_URL?
    connect_message(base_url:, prefix: 'embedding ')
    @embedding_ollama = Ollama::Client.new(
      connect_timeout: config.timeouts.connect_timeout?,
      read_timeout:    config.timeouts.read_timeout?,
      write_timeout:   config.timeouts.write_timeout?,
      base_url:        ,
      debug:           ,
      user_agent:
    )
    log(:info, "Embedding connection established", data: { base_url: })
    connect_message_done
    @embedding_ollama
  end
end

#connect_ollama ⇒ Ollama::Client (private)

The connect_ollama method establishes a connection to the Ollama API server.

This method initializes a new Ollama::Client instance with configured timeouts and connection parameters, then verifies that the connected server meets the minimum required API version (0.9.0). It sets the @ollama instance variable to the configured client and stores the version in @server_version.

Returns:

  • (Ollama::Client) —

    the configured Ollama client instance

Raises:

  • (RuntimeError) —

    if the connected Ollama server API version is less than 0.9.0



631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'lib/ollama_chat/chat.rb', line 631

def connect_ollama
  connect_message(base_url:)
  @server_version = nil
  @ollama = Ollama::Client.new(
    connect_timeout: config.timeouts.connect_timeout?,
    read_timeout:    config.timeouts.read_timeout?,
    write_timeout:   config.timeouts.write_timeout?,
    base_url:        ,
    debug:           ,
    user_agent:
  )
  if server_version.version < '0.9.0'.version
    raise 'require ollama API version 0.9.0 or higher'
  end
  log(:info, "Connection established", data: { base_url: })
  connect_message_done
  @ollama
end

#debug ⇒ TrueClass, FalseClass

The debug method accesses the debug configuration setting.

Returns:

  • (TrueClass, FalseClass) —

    the current debug mode status



224
225
226
# File 'lib/ollama_chat/chat.rb', line 224

def debug
  OC::OLLAMA::CHAT::DEBUG
end

#disable_content_parsing ⇒ self (private)

The disable_content_parsing method turns off content parsing by setting @parse_content to false.

This prevents automatic parsing of user input content during chat processing.

Returns:

  • (self) —

    returns the current instance to allow for method chaining



397
398
399
400
# File 'lib/ollama_chat/chat.rb', line 397

def disable_content_parsing
  @parse_content = false
  self
end

#embedding_ollama ⇒ Ollama::Client

Returns the Ollama client to use for embedding operations.

Falls back to the primary chat client when no dedicated embedding URL has been configured.

Returns:

  • (Ollama::Client) —

    the embedding or chat Ollama client



338
339
340
# File 'lib/ollama_chat/chat.rb', line 338

def embedding_ollama
  @embedding_ollama || ollama
end

#enable_command_completion(&block) ⇒ Object (private)

Enables tab completion for chat commands within the interactive session

Temporarily replaces the current Reline completion procedure with a custom one that provides command completion based on the chat help message.

Parameters:

  • block (Proc) —

    The block to execute with enhanced tab completion enabled

Returns:

  • (Object) —

    The return value of the executed block



777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
# File 'lib/ollama_chat/chat.rb', line 777

def enable_command_completion(&block)
  old = Reline.completion_proc
  Reline.autocompletion = true
  Reline.completion_proc = -> input, pre {
    before = [ pre, input ].join
    case before
    when %r(^/)
      start = [ pre, input ].join(' ').strip.gsub(/\s+/, ' ')
      command_completions.select { _1.start_with?(start) }
    when %r((./\S*))
      OllamaChat::Utils::PathCompleter.new(pre, input).complete
    end
  }
  block.()
ensure
  Reline.completion_proc = old
end

#enable_content_parsing ⇒ self (private)

The enable_content_parsing method enables content parsing for the chat session.

Returns:

  • (self) —

    returns the current instance to allow for method chaining



406
407
408
409
# File 'lib/ollama_chat/chat.rb', line 406

def enable_content_parsing
  @parse_content = true
  self
end

#generate(system: raw_system_prompt, prompt:, stream: false, think: false) ⇒ String

Sends a structured chat request to the Ollama model and returns the response content.

This method creates a minimal conversation consisting of a system message and a user message, executing it as a one-shot chat interaction.

Parameters:

  • system (String) (defaults to: raw_system_prompt) —

    the system prompt to guide the model's behavior (defaults to current raw_system_prompt)

  • prompt (String) —

    the user prompt to send to the model

  • stream (Boolean) (defaults to: false) —

    whether to stream the response (default: false)

  • think (Boolean) (defaults to: false) —

    enable thinking mode for hybrid-thinking models (default: false)

Returns:

  • (String) —

    the content of the resulting response message



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/ollama_chat/chat.rb', line 277

def generate(system: raw_system_prompt, prompt:, stream: false, think: false)
  messages = [
    OllamaChat::Message.new(
      role:        'system',
      content:     system,
    ),

    OllamaChat::Message.new(
      role: 'user',
      content: prompt
    ),
  ]

  content = call_ollama_chat(
    model:    @model,
    messages: ,
    options:  model_options,
    stream:   ,
    think:
  )&.message&.content.to_s

  if content.empty?
    log(:warn, "LLM generation returned empty content", data: { prompt: })
  else
    log(:info, "LLM generation successful", data: { prompt:, content: })
  end

  content
end

#handle_input(content) ⇒ Symbol, ... (private)

Handles user input commands and processes chat interactions.

Parameters:

  • content (String) —

    The input content to process

Returns:

  • (Symbol, String, nil) —

    Returns a symbol indicating next action, the content to be processed, or nil for no action needed



446
447
448
449
450
451
452
# File 'lib/ollama_chat/chat.rb', line 446

def handle_input(content)
  commands.each do |_name, command|
    action = command.execute_if_match?(content) {}
    action and return action
  end
  content
end

#initial_collection ⇒ Symbol

The initial_collection method determines the collection name to be used for embeddings in the RAG system.

Returns:

  • (Symbol) —

    the collection name symbol



244
245
246
247
248
249
250
251
252
253
# File 'lib/ollama_chat/chat.rb', line 244

def initial_collection
  c = session&.current_collection.full? ||
    config.embedding.collection.full? ||
    'default'
  if c =~ /\A#{OllamaChat::COLLECTION_NAME_REGEXP.source}\z/
    c
  else
    'default'
  end.to_sym
end

#initial_model ⇒ String

Returns the model name to be used for the chat session.

The resolution priority is:

  1. The current session's model (if present).
  2. The model specified via the command line option -m.
  3. The default model name defined in the configuration.

Returns:

  • (String) —

    the model name to be used for the chat session



236
237
238
# File 'lib/ollama_chat/chat.rb', line 236

def initial_model
  session&.current_model.full? || @opts[?m].full? || config.model.name
end

#initial_system_prompt ⇒ String

The initial_system_prompt method returns the system prompt for the initial message.

Returns:

  • (String) —

    the system prompt for the initial message



259
260
261
# File 'lib/ollama_chat/chat.rb', line 259

def initial_system_prompt
  @messages.system_name
end

#inspect ⇒ String

Returns a human-readable string representation of the Chat object, including the class name and the base URL.

Returns:

  • (String) —

    the inspected string



346
347
348
# File 'lib/ollama_chat/chat.rb', line 346

def inspect
  "#<#{self.class}: #{redact_password(base_url)}>"
end

#interact_with_user ⇒ Integer (private)

The interact_with_user method manages the interactive loop for user input and chat processing. It handles reading user input, processing commands, managing messages, and communicating with the Ollama server. The method supports command completion, prefilling prompts, socket input handling, and various chat features including embedding context and voice support. It processes user input through command handling, content parsing, and message formatting before sending requests to the Ollama server. The method also handles server socket messages, manages chat history, and ensures proper cleanup and configuration handling throughout the interaction.

Returns:

  • (Integer) —

    returns 0 on successful completion or raises an error



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
# File 'lib/ollama_chat/chat.rb', line 468

def interact_with_user
  loop do
    content           = nil
    group_uuid        = OllamaChat::UUIDV7.generate
    tools_were_called = false
    enable_content_parsing
    type         = :terminal_input
    input_prompt = bold { color(172) { message_type(@images) + " user" } } + bold { "> " }
    begin
      tools_were_called = tool_call_processor.drain { |index, tool_name, content|
        messages << OllamaChat::Message.new(
          role:        'user', # XXX this should be 'tool' but it doesn't currently seem to work in Ollama API
          sender_name: tool_name,
          tool_name:   ,
          content:     ,
          images:      @images.dup,
          group_uuid:
        )
      }
      tools_were_called and type = :tool_input
      unless tools_were_called
        content = enable_command_completion do
          if prefill_prompt
            Reline.pre_input_hook = -> {
              Reline.insert_text prefill_prompt.gsub(/\n*\z/, '')
              self.prefill_prompt = nil
            }
          else
            Reline.pre_input_hook = nil
          end
          Reline.readline(input_prompt, true)&.chomp
        end
      end
    rescue Interrupt
      if message = server_socket_message
        type           = message.type.full?(:to_sym) || :socket_input
        content        = message.content
        @parse_content = message.parse
        feedback color(112) { "Received a server socket message. Processing now…" }, type: :info
      else
        raise
      end
    end

    content = content.strip if content =~ %r(\A/[^/])

    if type == :terminal_input
      case next_action = handle_input(content)
      when :next
        next
      when :redo
        redo
      when String
        content = next_action
      end
    end

    unless type == :tool_input
      content = content.encode(invalid: :replace)

      content.present? or next

      parse_content? and content = parse_content(content, @images)

      messages << OllamaChat::Message.new(
        role:        'user',
        sender_name: user_name,
        content:     ,
        images:      @images.dup,
        group_uuid:
      )

      runtime_information_inject(group_uuid:)
      trigger_inject(content, group_uuid:)
    end
    @images.clear
    handler = OllamaChat::FollowChat.new(
      chat:     self,
      messages:,
      voice:    (voices.selected if voice.on?),
      group_uuid:
    )
    begin
      retried = false
      sent_messages = messages.compacted_messages
      sent_messages = sent_messages.map {
        _1.dup.tap { |message|
          message.sender_name = nil
          message.group_uuid  = nil
          message.tool_calls  = nil
          message.thinking    = nil if think_strip.on?
        }
      }
      prepare_model(@model)
      call_ollama_chat(
        model:    @model,
        messages: sent_messages,
        options:  model_options,
        stream:   stream.on?,
        think:    ,
        tools:    ,
        &handler
      )
      store_messages_in_session
    rescue Ollama::Errors::BadRequestError
      if (think? || tools_support.on?) && !retried
        msg = "Error in think mode/with tool support, switch both off and retry."
        log(:warn, msg, warn: true)
        sleep 1
        think_mode.selected  = 'disabled'
        tools_support.set false
        retried = true
        retry
      else
        raise
      end
    end

    case type
    when :socket_input
      server_socket_message&.disconnect
    when :socket_input_with_response
      if message = handler.messages.last
        server_socket_message.respond({ role: message.role, content: message.content })
      end
      server_socket_message&.disconnect
    end
  rescue Ollama::Errors::TimeoutError
    msg = "Currently lost connection to ollama server and cannot send command."
    log(:warn, msg, warn: true)
  rescue Interrupt
    feedback("Type /quit to quit.")
  ensure
    self.server_socket_message = nil
  end
  0
rescue OllamaChat::OllamaChatQuitError
  feedback("Goodbye.")
rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e
  log(:error, e)
  fix_config(e)
ensure
  session_close
end

#models ⇒ Module (private)

Returns The module containing the database models.

Returns:

  • (Module) —

    The module containing the database models.



386
387
388
# File 'lib/ollama_chat/chat.rb', line 386

def models
  OllamaChat::Database::Models
end

#parse_content? ⇒ TrueClass, FalseClass (private)

The parse_content? method returns the boolean value of the @parse_content instance variable.

Returns:

  • (TrueClass, FalseClass) —

    true if @parse_content is truthy, false otherwise



416
417
418
# File 'lib/ollama_chat/chat.rb', line 416

def parse_content?
  !!@parse_content
end

#quit_app ⇒ Object (private)

Signals a graceful shutdown of the application.

Raises OllamaChatQuitError which is caught by the main interaction loop to terminate the session cleanly.



437
438
439
# File 'lib/ollama_chat/chat.rb', line 437

def quit_app
  raise OllamaChat::OllamaChatQuitError
end

#setup_cache ⇒ OllamaChat::RedisCache? (private)

The setup_cache method initializes and returns a Redis cache instance with expiring keys if a Redis URL is configured.

Returns:



757
758
759
760
761
762
763
764
765
766
# File 'lib/ollama_chat/chat.rb', line 757

def setup_cache
  if url = config.redis.expiring.url?
    ex = config.redis.expiring.ex?.to_i
    OllamaChat::RedisCache.new(
      prefix: 'Expiring-',
      url:,
      ex:
    )
  end
end

#setup_documents ⇒ Documentrix::Documents, NULL (private)

The setup_documents method initializes the document processing pipeline by configuring the embedding model and database connection. It then loads specified documents into the system and returns the configured document collection.

Returns:

  • (Documentrix::Documents, NULL) —

    the initialized document collection if embedding is enabled, otherwise NULL



657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
# File 'lib/ollama_chat/chat.rb', line 657

def setup_documents
  if embedding.on?
    @embedding_model         = config.embedding.model.name
    @embedding_model_options = Ollama::Options[config.embedding.model.options]
    pull_model_unless_present(@embedding_model, ollama: embedding_ollama)
    collection = initial_collection
    @documents = Documentrix::Documents.new(
      ollama:            embedding_ollama,
      model:             @embedding_model,
      model_options:     config.embedding.model.options,
      embedding_length:  config.embedding.model.embedding_length,
      database_filename: config.embedding.database_filename || @ollama_chat_config.database_path,
      collection:        ,
      cache:             configure_cache,
      redis_url:         config.redis.documents.url?,
      debug:
    )
  else
    NULL
  end
end

#speak(text, background: true) ⇒ OllamaChat::TTS, ...

Synthesizes and plays a short voice notification using the session's current voice.

This is the chat-level facade for one-shot speech: it resolves the active voice, instantiates the configured voice handler, and delegates to its #speak method. It is a no-op when the voice switch is off, no voice is selected, or the handler lacks #speak.

Parameters:

  • text (String) —

    the text to speak

  • background (Boolean, Integer) (defaults to: true) —

    pass true for an immediate background thread, false for inline, or a numeric delay in seconds (e.g. 10) to spawn a background thread that sleeps before speaking

Returns:

  • (OllamaChat::TTS, OllamaChat::Say, nil) —

    the voice handler instance when a background thread was spawned (so callers can call cancel_speaking), or nil for inline playback or when voice is off



324
325
326
327
328
329
330
# File 'lib/ollama_chat/chat.rb', line 324

def speak(text, background: true)
  session or return
  voice.on? or return
  current_voice = session.current_voice.full? or return
  voice_handler.method_defined?(:speak) or return
  voice_handler.new(chat: self, voice: current_voice).speak(text, background:)
end

#start ⇒ Object

The start method initializes the chat session by displaying information, then prompts the user for input to begin interacting with the chat.



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/ollama_chat/chat.rb', line 193

def start
  log(:info, 'Starting chat client', data: {
    client:, server: { version: server_version, url: server_url }, user:,
    config: @ollama_chat_config.filename,
  })
  begin
    if model = session.current_model.full?
      use_model(model, keep_options: true)
    else
      use_model(initial_model)
    end
  rescue OllamaChat::UnknownModelError => e
    abort "Failed to use to model: #{e}"
  end

  feedback ?\n

  setup_persona_from_session
  setup_system_prompt

  print_welcome
  info_session

  feedback("\nType /help to display the chat help.")

  interact_with_user
end

#truncate_logs ⇒ Object (private)

Truncates chat.log and database.log to the configured tail line count before any new logging begins for this session.



375
376
377
378
379
380
381
382
383
# File 'lib/ollama_chat/chat.rb', line 375

def truncate_logs
  keep = OC::OLLAMA::CHAT::LOG::TAIL_LINES
  OllamaChat::Utils::LogRotation.truncate_tail(
    OC::OLLAMA::CHAT::LOG::CHAT, keep_lines: keep
  )
  OllamaChat::Utils::LogRotation.truncate_tail(
    OC::OLLAMA::CHAT::LOG::DATABASE, keep_lines: keep
  )
end

#voice_handler ⇒ Class, NilClass

Returns the voice handler class based on the configuration.

This method resolves the voice handler class specified in the config. If running within RSpec, it returns nil to avoid side effects.

Returns:

  • (Class, NilClass) —

    the voice handler class or nil if in test mode



181
182
183
184
185
186
187
188
189
# File 'lib/ollama_chat/chat.rb', line 181

def voice_handler
  defined?(RSpec) and return nil
  case config.voice.handler
  when 'OllamaChat::TTS'
    OllamaChat::TTS
  when 'OllamaChat::Say'
    OllamaChat::Say
  end
end