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 ThinkControl

ThinkControl::THINK_MODE_STATES

Constants included from Parsing

Parsing::CONTENT_REGEXP, Parsing::DOCUMENT_POLICY_STATES

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 ToolCalling

#tool_call_results

Attributes included from ServerSocket

#server_socket_message

Attributes included from StateSelectors

#context_format, #document_policy, #think_mode, #voices

Attributes included from Switches

#embedding, #embedding_enabled, #embedding_paused, #location, #markdown, #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, #summarize_for_compaction, tool_summary_line

Methods included from PromptManagement

#add_new_prompt, #all_prompts, #choose_and_delete_prompt, #choose_and_edit_prompt, #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_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, #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, #collection, #create_collection, #database_collection?, #delete_collection, #edit_collection, #extract_patterns, #list_collections, #rename_collection, #set_current_collection, #switch_collection, #update_collection

Methods included from SessionManagement

#change_session, #choose_session, #delete_session, #derive_session_name, #determine_valid_new_name_for_session, #duplicate_session, #list_sessions, #load_links_from_session, #new_session, #preferred_session, #previous_session, #rename_session, #repair_group_uuids, #report_conversation, #report_session, #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_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

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, #handle_tool_call_results?, #list_tools, #tool_configured?, #tool_enabled?, #tool_function, #tool_paths_allowed, #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

#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

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_descriptions, #collection_stats, #context_filled, #context_gauge, #context_usage, #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, #print_welcome, #server_url, #server_version, #static_runtime_information, #static_runtime_information_values, #usage, #user, #user_name, #version

Methods included from ThinkControl

#think, #think?, #think_loud?

Methods included from Dialog

#ask?, #ask_for_filename?, #change_voice, #choose_file_set, #confirm?, #connect_message, #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_content, #parse_png, #parse_rss, #parse_source, #pdf_read, #personalize_character_profile, #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

Methods included from TokenEstimator

estimate

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



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

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)
  connect_ollama
  @documents = setup_documents
  models::Collection.sync(self)
  @cache                = setup_cache
  @images               = []
  @kramdown_ansi_styles = configure_kramdown_ansi_styles
  @tool_call_results    = Hash.new { |h, name| h[name] = [] }
  setup_personae_directory
  @opts[?S] and init_server_socket
rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e
  fix_config(e)
end

Instance Attribute Details

#cacheOllamaChat::RedisCache? (readonly)

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

Returns:



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

def cache
  @cache
end

#documentsDocumentrix::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



143
144
145
# File 'lib/ollama_chat/chat.rb', line 143

def documents
  @documents
end

#imagesArray (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



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

def images
  @images
end

#messagesOllamaChat::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:



153
154
155
# File 'lib/ollama_chat/chat.rb', line 153

def messages
  @messages
end

#ollamaOllama::Client (readonly)

The ollama reader returns the Ollama API client instance.

Returns:

  • (Ollama::Client)

    the configured Ollama API client



132
133
134
# File 'lib/ollama_chat/chat.rb', line 132

def ollama
  @ollama
end

#prefill_promptString, 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



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

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



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

attr_writer :prefill_prompt

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



696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/ollama_chat/chat.rb', line 696

def add_documents_from_argv(document_list)
  if document_list.any?(&:empty?)
    STDOUT.puts "Clearing collection #{bold{documents.collection}}."
    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
    STDOUT.puts "Collection #{bold{documents.collection}}: Adding #{document_list.size} documents…"
    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_urlString (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



312
313
314
315
316
317
318
319
320
321
# File 'lib/ollama_chat/chat.rb', line 312

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

#clean(what) ⇒ Object (private)

The clean method clears various parts of the chat session based on the specified parameter.

Parameters:

  • what (String, nil)

    the type of data to clear, defaults to 'messages' if nil



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/ollama_chat/chat.rb', line 409

def clean(what)
  persona_profile = nil
  case what
  when 'messages', nil
    messages.clear
    STDOUT.puts "Cleared messages."
  when 'links'
    links.clear
    STDOUT.puts "Cleared links."
  when 'history'
    clear_history
    STDOUT.puts "Cleared history."
  when 'tags'
    @documents.clear
    STDOUT.puts "Cleared all tags."
  when 'images'
    messages.clear_images
    STDOUT.puts "Cleared all images."
  when 'all'
    if confirm?(
        prompt: '🔔 Are you sure to clear messages and collection? (y/n) ',
        yes: /\Ay/i
      )
    then
      messages.clear
      @documents.clear
      links.clear
      clear_history
      STDOUT.puts "Cleared messages and collection #{bold{collection}}."
    else
      STDOUT.puts 'Cancelled.'
    end
  end
  persona_profile
end

#connect_ollamaOllama::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
# File 'lib/ollama_chat/chat.rb', line 631

def connect_ollama
  @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:        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: })
  @ollama
end

#debugTrueClass, FalseClass

The debug method accesses the debug configuration setting.

Returns:

  • (TrueClass, FalseClass)

    the current debug mode status



215
216
217
# File 'lib/ollama_chat/chat.rb', line 215

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

#disable_content_parsingself (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



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

def disable_content_parsing
  @parse_content = false
  self
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



748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
# File 'lib/ollama_chat/chat.rb', line 748

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_parsingself (private)

The enable_content_parsing method enables content parsing for the chat session.

Returns:

  • (self)

    returns the current instance to allow for method chaining



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

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



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/ollama_chat/chat.rb', line 268

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



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

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

#initial_collectionSymbol

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

Returns:

  • (Symbol)

    the collection name symbol



235
236
237
238
239
240
241
242
243
244
# File 'lib/ollama_chat/chat.rb', line 235

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_modelString

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



227
228
229
# File 'lib/ollama_chat/chat.rb', line 227

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

#initial_system_promptString

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

Returns:

  • (String)

    the system prompt for the initial message



250
251
252
# File 'lib/ollama_chat/chat.rb', line 250

def initial_system_prompt
  @messages.system_name
end

#inspectString

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

Returns:

  • (String)

    the inspected string



302
303
304
# File 'lib/ollama_chat/chat.rb', line 302

def inspect
  "#<#{self.class}: #{base_url.to_s}>"
end

#interact_with_userInteger (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



459
460
461
462
463
464
465
466
467
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 459

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 = handle_tool_call_results? { |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
        STDOUT.puts color(112) { "Received a server socket message. Processing now…" }
      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:
      )

      if runtime_info.on?
        tool_name = 'runtime_information'
        messages << OllamaChat::Message.new(
          role:        'user',
          tool_name:   ,
          sender_name: tool_name,
          content:     dynamic_runtime_information,
          images:      @images.dup,
          group_uuid:
        )
      end
    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
    STDOUT.puts "Type /quit to quit."
  ensure
    self.server_socket_message = nil
  end
  0
rescue OllamaChat::OllamaChatQuitError
  STDOUT.puts "Goodbye."
rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e
  log(:error, e)
  fix_config(e)
ensure
  session_close
end

#modelsModule (private)

Returns The module containing the database models.

Returns:

  • (Module)

    The module containing the database models.



336
337
338
# File 'lib/ollama_chat/chat.rb', line 336

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



366
367
368
# File 'lib/ollama_chat/chat.rb', line 366

def parse_content?
  !!@parse_content
end

#quit_appObject (private)

Signals a graceful shutdown of the application.

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



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

def quit_app
  raise OllamaChat::OllamaChatQuitError
end

#setup_cacheOllamaChat::RedisCache? (private)

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

Returns:



728
729
730
731
732
733
734
735
736
737
# File 'lib/ollama_chat/chat.rb', line 728

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_documentsDocumentrix::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



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

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)
    collection = initial_collection
    @documents = Documentrix::Documents.new(
      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

#startObject

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



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/ollama_chat/chat.rb', line 184

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

  STDOUT.puts

  setup_persona_from_session
  setup_system_prompt

  print_welcome
  info_session

  STDOUT.puts "\nType /help to display the chat help."

  interact_with_user
end

#truncate_logsObject (private)

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



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

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_handlerClass, Array

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 an empty array to avoid side effects.

Returns:

  • (Class, Array)

    the voice handler class or an empty array if in test mode



172
173
174
175
176
177
178
179
180
# File 'lib/ollama_chat/chat.rb', line 172

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