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 PromptManagement

#add_new_prompt, #all_prompts, #choose_and_delete_prompt, #choose_and_edit_prompt, #choose_prompt, #determine_valid_new_name_for_prompt, #duplicate_prompt, #export_prompt, #import_prompt, #info_prompt, #list_prompts, #prepare_conversation_history, #prompt_with_favourite, #reset_prompt_to_default, #suggest_prompts

Methods included from SystemPromptManagement

#add_new_system_prompt, #all_system_prompts, #ask_to_set_current_system_prompt, #change_system_prompt, #choose_and_delete_system_prompt, #choose_and_edit_system_prompt, #choose_system_prompt, #current_system_prompt, #current_system_prompt_name, #determine_valid_new_name_for_system_prompt, #duplicate_system_prompt, #export_system_prompt, #import_system_prompt, #info_system_prompt, #list_system_prompts, #model_default_system_prompt, #raw_system_prompt, #reset_system_prompt_to_default, #set_current_system_prompt, #setup_system_prompt, #system_prompt_with_favourite

Methods included from PromptHandling

#delete_prompt, #delete_system_prompt, #each_prompt, #each_system_prompt, #load_prompt_from_file, #prompt, #store_prompt, #store_system_prompt, #system_prompt, #write_prompt

Methods included from FavouritesManagement

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

Methods included from RAGHandling

#choose_collection, #clear_collection, #collection, #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, #session_apply, #session_close, #set_new_session, #setup_session, #show_session, #store_links_in_session, #store_messages_in_session, #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=, #display_config, #edit_config, #fix_config, #fix_session, #reload_config

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

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, #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, #display_chat_help, #dynamic_runtime_information, #dynamic_runtime_information_values, #info, #info_model, #info_rag, #info_runtime, #info_session, #infobar_message, #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?, #change_voice, #choose_file_set, #confirm?, #connect_message, #go_command, #message_list

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, #embed, #embed_source, #fetch_source, #fetch_source_as_filename, #import, #import_source, #summarize, #summarize_source

Methods included from Parsing

#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_to_session, #edit_model_options, #edit_session_model_options, #fill_up_model_options, #get_default_model_options, #get_session_model_options, #get_stored_model_options, #model_options, #model_present?, #model_with_size, #prepare_model, #pull_model_from_remote, #pull_model_unless_present, #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 Commands

#collection, #compose, #config, #copy, #list, #pipe, #reconnect, #session

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



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
127
128
129
130
# File 'lib/ollama_chat/chat.rb', line 102

def initialize(argv: ARGV.dup)
  @opts               = go 'f:u:m:c:C:D:l:nMESVh', 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
  @messages           = OllamaChat::MessageList.new(self)
  OllamaChat::Database.setup_models.each { _1.ask_and_send(:seed, self) }
  setup_session
  setup_switches
  setup_state_selectors(config)
  connect_ollama
  if conversation_file = @opts[?c]
    messages.load_conversation(conversation_file)
  else
    messages.read_conversation_jsonl(session.messages.to_s)
  end
  embedding_enabled.set(config.embedding.enabled && !@opts[?E])
  @documents            = setup_documents
  @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
  info_session
rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e
  fix_config(e)
end

Instance Attribute Details

#cacheObject (readonly)

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



166
167
168
# File 'lib/ollama_chat/chat.rb', line 166

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



146
147
148
# File 'lib/ollama_chat/chat.rb', line 146

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



161
162
163
# File 'lib/ollama_chat/chat.rb', line 161

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:



156
157
158
# File 'lib/ollama_chat/chat.rb', line 156

def messages
  @messages
end

#ollamaOllama::Client (readonly)

The ollama reader returns the Ollama API client instance.

Returns:

  • (Ollama::Client)

    the configured Ollama API client



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

def ollama
  @ollama
end

#prefill_promptBoolean (private)

Returns whether there is a prompt waiting to be prefilled into the input buffer.

Returns:

  • (Boolean)

    true if a prefill prompt exists and is not empty, false otherwise



308
309
310
# File 'lib/ollama_chat/chat.rb', line 308

def prefill_prompt
  @prefill_prompt.full?
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



617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
# File 'lib/ollama_chat/chat.rb', line 617

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



534
535
536
# File 'lib/ollama_chat/chat.rb', line 534

def base_url
  @opts[?u] || OC::OLLAMA::URL
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



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/ollama_chat/chat.rb', line 335

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



548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/ollama_chat/chat.rb', line 548

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 to #{base_url} established.")
  @ollama
end

#debugTrueClass, FalseClass

The debug method accesses the debug configuration setting.

Returns:

  • (TrueClass, FalseClass)

    the current debug mode status



196
197
198
# File 'lib/ollama_chat/chat.rb', line 196

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



282
283
284
285
# File 'lib/ollama_chat/chat.rb', line 282

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



669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
# File 'lib/ollama_chat/chat.rb', line 669

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



291
292
293
294
# File 'lib/ollama_chat/chat.rb', line 291

def enable_content_parsing
  @parse_content = true
  self
end

#generate(system: raw_system_prompt, prompt:) ⇒ 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.

(defaults to current raw_system_prompt)

Parameters:

  • system (String) (defaults to: raw_system_prompt)

    the system prompt to guide the model's behavior

  • prompt (String)

    the user prompt to send to the model

Returns:

  • (String)

    the content of the resulting response message



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/ollama_chat/chat.rb', line 245

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

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

  ollama.chat(
    model:    @model,
    messages: ,
    options:  model_options,
    stream:   false,
    think:    false,
    tools:
  )&.message&.content.to_s
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



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

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



216
217
218
219
220
221
222
223
# File 'lib/ollama_chat/chat.rb', line 216

def initial_collection
  (
    @opts[?C] ||
    session&.current_collection.full? ||
    config.embedding.collection.full? ||
    :default
  ).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



208
209
210
# File 'lib/ollama_chat/chat.rb', line 208

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



229
230
231
# File 'lib/ollama_chat/chat.rb', line 229

def initial_system_prompt
  @messages.system_name
end

#interact_with_userObject (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.



383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
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
# File 'lib/ollama_chat/chat.rb', line 383

def interact_with_user
  loop do
    content           = nil
    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
        )
      }
      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 :return
        return
      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)

      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
        )
      end

      messages << OllamaChat::Message.new(
        role:        'user',
        sender_name: user_name,
        content:     ,
        images:      @images.dup
      )
    end
    @images.clear
    handler = OllamaChat::FollowChat.new(
      chat:     self,
      messages:,
      voice:    (voices.selected if voice.on?)
    )
    begin
      retried = false
      sent_messages = messages.to_ary
      if think_strip.on?
        sent_messages = sent_messages.map {
          _1.dup.tap { |message|
            message.thinking = nil
          }
        }
      end
      prepare_model(@model)
      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
        STDOUT.puts "#{bold('Error')}: in think mode/with tool support, switch both off and retry."
        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 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.



271
272
273
# File 'lib/ollama_chat/chat.rb', line 271

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



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

def parse_content?
  !!@parse_content
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:



649
650
651
652
653
654
655
656
657
658
# File 'lib/ollama_chat/chat.rb', line 649

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



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

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

    document_list = @opts[?D].to_a
    add_documents_from_argv(document_list)
    @documents
  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.



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/ollama_chat/chat.rb', line 170

def start
  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

  info_session

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

  interact_with_user
end