Class: OllamaChat::Chat

Inherits:
Object
  • Object
show all
Includes:
Clipboard, Conversation, Dialog, DocumentCache, History, Information, KramdownANSI, MessageFormat, MessageOutput, ModelHandling, Parsing, ServerSocket, SourceFetching, Switches, WebSearching, Term::ANSIColor, Tins::GO
Defined in:
lib/ollama_chat/chat.rb

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

Class Attribute Summary collapse

Instance Attribute Summary collapse

Attributes included from ServerSocket

#server_socket_message

Attributes included from Dialog

#document_policy

Attributes included from Switches

#embedding, #embedding_enabled, #embedding_paused, #location, #markdown, #stream, #think, #voice

Instance Method Summary collapse

Methods included from Conversation

#load_conversation, #save_conversation

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

#chat_history_filename, #clear_history, #init_chat_history, #save_history

Methods included from MessageFormat

#message_type, #talk_annotate, #think_annotate

Methods included from Clipboard

#copy_to_clipboard, #paste_from_input

Methods included from MessageOutput

#output, #pipe, #write_file_unless_exist

Methods included from Information

#collection_stats, #display_chat_help, #display_chat_help_message, #info, #server_url, #server_version, #usage, #version

Methods included from Dialog

#ask?, #change_system_prompt, #change_voice, #choose_collection, #choose_document_policy, #choose_model, #choose_prompt, #connect_message, #message_list, #model_with_size

Methods included from WebSearching

#search_engine, #search_web, #search_web_with_duckduckgo, #search_web_with_searxng

Methods included from SourceFetching

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

Methods included from Parsing

#parse_atom, #parse_content, #parse_csv, #parse_rss, #parse_source, #pdf_read, #ps_read, #reverse_markdown

Methods included from ModelHandling

#model_present?, #pull_model_from_remote, #pull_model_unless_present

Methods included from Switches

#setup_switches

Methods included from DocumentCache

#configure_cache, #document_cache_class

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:

  • (ArgumentError)

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



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/ollama_chat/chat.rb', line 79

def initialize(argv: ARGV.dup)
  @opts               = go 'f:u:m:s:c:C:D:MESVh', 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
  setup_switches(config)
  base_url         = @opts[?u] || OllamaChat::EnvConfig::OLLAMA::URL
  @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 ArgumentError, 'require ollama API version 0.9.0 or higher'
  end
  @document_policy = config.document_policy
  @model           = choose_model(@opts[?m], config.model.name)
  @model_options   = Ollama::Options[config.model.options]
  model_system     = pull_model_unless_present(@model, @model_options)
  embedding_enabled.set(config.embedding.enabled && !@opts[?E])
  @messages        = OllamaChat::MessageList.new(self)
  if @opts[?c]
    messages.load_conversation(@opts[?c])
  else
    default = config.system_prompts.default? || model_system
    if @opts[?s] =~ /\A\?/
      change_system_prompt(default, system: @opts[?s])
    else
      system = OllamaChat::Utils::FileArgument.get_file_argument(@opts[?s], default:)
      system.present? and messages.set_system_prompt(system)
    end
  end
  @documents            = setup_documents
  @cache                = setup_cache
  @current_voice        = config.voice.default
  @images               = []
  @kramdown_ansi_styles = configure_kramdown_ansi_styles
  init_chat_history
  @opts[?S] and init_server_socket
rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e
  fix_config(e)
end

Class Attribute Details

.configObject

The config attribute accessor provides read and write access to the configuration object associated with this instance.



171
172
173
# File 'lib/ollama_chat/chat.rb', line 171

def config
  @config
end

Instance Attribute Details

#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

#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



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

def ollama
  @ollama
end

Instance Method Details

#add_documents_from_argv(document_list) ⇒ void (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

This method returns an undefined value.

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

See Also:



705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# File 'lib/ollama_chat/chat.rb', line 705

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

#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



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

def clean(what)
  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 'all'
    if ask?(prompt: 'Are you sure to clear messages and collection? (y/n) ') =~ /\Ay/i
      messages.clear
      @documents.clear
      links.clear
      clear_history
      STDOUT.puts "Cleared messages and collection #{bold{@documents.collection}}."
    else
      STDOUT.puts 'Cancelled.'
    end
  end
end

#configComplexConfig::Settings

The config method returns the configuration object associated with the class.

Returns:

  • (ComplexConfig::Settings)

    the configuration instance



185
186
187
# File 'lib/ollama_chat/chat.rb', line 185

def config
  self.class.config
end

#config=(config) ⇒ Object

The config= method assigns a new configuration object to the class.

Parameters:

  • config (ComplexConfig::Settings)

    the configuration object to be set



177
178
179
# File 'lib/ollama_chat/chat.rb', line 177

def config=(config)
  self.class.config = config
end

#debugTrueClass, FalseClass

The debug method accesses the debug configuration setting.

Returns:

  • (TrueClass, FalseClass)

    the current debug mode status



129
130
131
# File 'lib/ollama_chat/chat.rb', line 129

def debug
  OllamaChat::EnvConfig::OLLAMA::CHAT::DEBUG
end

#display_configObject (private)

The display_config method renders the configuration and displays it using a pager. It determines an appropriate pager command based on environment variables and available system commands, then uses Kramdown::ANSI::Pager to show the formatted configuration output.



510
511
512
513
514
515
516
517
518
519
# File 'lib/ollama_chat/chat.rb', line 510

def display_config
  command  = OllamaChat::EnvConfig::PAGER?
  rendered = config.to_s
  Kramdown::ANSI::Pager.pager(
    lines: rendered.count(?\n),
    command: my_pager
  ) do |output|
    output.puts rendered
  end
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

See Also:



786
787
788
789
790
791
792
793
794
795
# File 'lib/ollama_chat/chat.rb', line 786

def enable_command_completion(&block)
  old = Reline.completion_proc
  commands = display_chat_help_message.scan(/^\s*(\S+)/).inject(&:concat)
  Reline.completion_proc = -> input {
    commands.grep Regexp.new('\A' + Regexp.quote(input))
  }
  block.()
ensure
  Reline.completion_proc = old
end

#fix_config(exception) ⇒ Object (private)

The fix_config method handles configuration file errors by informing the user about the exception and prompting them to fix it. It then executes a diff tool to compare the current config file with the default one. This method exits the program after handling the configuration error

Parameters:

  • exception (Exception)

    the exception that occurred while reading the config file



756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
# File 'lib/ollama_chat/chat.rb', line 756

def fix_config(exception)
  save_conversation('backup.json')
  STDOUT.puts "When reading the config file, a #{exception.class} "\
    "exception was caught: #{exception.message.inspect}"
  unless diff_tool = OllamaChat::EnvConfig::DIFF_TOOL?
    exit 1
  end
  if ask?(prompt: 'Do you want to fix the config? (y/n) ') =~ /\Ay/i
    system Shellwords.join([
      diff_tool,
      @ollama_chat_config.filename,
      @ollama_chat_config.default_config_path,
    ])
    exit 0
  else
    exit 1
  end
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



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
# File 'lib/ollama_chat/chat.rb', line 209

def handle_input(content)
  case content
  when %r(^/copy$)
    copy_to_clipboard
    :next
  when %r(^/paste$)
    paste_from_input
  when %r(^/markdown$)
    markdown.toggle
    :next
  when %r(^/stream$)
    stream.toggle
    :next
  when %r(^/location$)
    location.toggle
    :next
  when %r(^/voice(?:\s+(change))?$)
    if $1 == 'change'
      change_voice
    else
      voice.toggle
    end
    :next
  when %r(^/list(?:\s+(\d*))?$)
    n = 2 * $1.to_i if $1
    messages.list_conversation(n)
    :next
  when %r(^/last(?:\s+(\d*))?$)
    n = $1.to_i if $1
    messages.show_last(n)
    :next
  when %r(^/clear(?:\s+(messages|links|history|tags|all))?$)
    clean($1)
    :next
  when %r(^/clobber$)
    clean('all')
    :next
  when %r(^/drop(?:\s+(\d*))?$)
    messages.drop($1)
    messages.show_last
    :next
  when %r(^/model$)
    @model = choose_model('', @model)
    :next
  when %r(^/system(?:\s+(show))?$)
    if $1 != 'show'
      change_system_prompt(@system)
    end
    @messages.show_system_prompt
    :next
  when %r(^/prompt)
    @prefill_prompt = choose_prompt
    :next
  when %r(^/regenerate$)
    if content = messages.second_last&.content
      content.gsub!(/\nConsider these chunks for your answer.*\z/, '')
      messages.drop(1)
    else
      STDOUT.puts "Not enough messages in this conversation."
      return :redo
    end
    @parse_content = false
    content
  when %r(^/collection(?:\s+(clear|change))?$)
    case $1 || 'change'
    when 'clear'
      loop do
        tags = @documents.tags.add('[EXIT]').add('[ALL]')
        tag = OllamaChat::Utils::Chooser.choose(tags, prompt: 'Clear? %s')
        case tag
        when nil, '[EXIT]'
          STDOUT.puts "Exiting chooser."
          break
        when '[ALL]'
          if ask?(prompt: 'Are you sure? (y/n) ') =~ /\Ay/i
            @documents.clear
            STDOUT.puts "Cleared collection #{bold{@documents.collection}}."
            break
          else
            STDOUT.puts 'Cancelled.'
            sleep 3
          end
        when /./
          @documents.clear(tags: [ tag ])
          STDOUT.puts "Cleared tag #{tag} from collection #{bold{@documents.collection}}."
          sleep 3
        end
      end
    when 'change'
      choose_collection(@documents.collection)
    end
    :next
  when %r(^/info$)
    info
    :next
  when %r(^/document_policy$)
    choose_document_policy
    :next
  when %r(^/think$)
    think.toggle
    :next
  when %r(^/import\s+(.+))
    @parse_content = false
    import($1) or :next
  when %r(^/summarize\s+(?:(\d+)\s+)?(.+))
    @parse_content = false
    summarize($2, words: $1) or :next
  when %r(^/embedding$)
    embedding_paused.toggle(show: false)
    embedding.show
    :next
  when %r(^/embed\s+(.+))
    @parse_content = false
    embed($1) or :next
  when %r(^/web\s+(?:(\d+)\s+)?(.+))
    @parse_content = false
    web($1, $2)
  when %r(^/save\s+(.+)$)
    save_conversation($1)
    :next
  when %r(^/links(?:\s+(clear))?$)
    manage_links($1)
    :next
  when %r(^/load\s+(.+)$)
    load_conversation($1)
    :next
  when %r(^/pipe\s+(.+)$)
    pipe($1)
    :next
  when %r(^/output\s+(.+)$)
    output($1)
    :next
  when %r(^/vim(?:\s+(.+))?$)
    if message = messages.last
      OllamaChat::Vim.new($1).insert message.content
    else
      STDERR.puts "Warning: No message found to insert into Vim"
    end
    :next
  when %r(^/config$)
    display_config
    :next
  when %r(^/quit$), nil
    STDOUT.puts "Goodbye."
    :return
  when %r(^/)
    display_chat_help
    :next
  when /\A\s*\z/
    STDOUT.puts "Type /quit to quit."
    :next
  end
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.



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
612
613
614
615
616
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
643
644
# File 'lib/ollama_chat/chat.rb', line 533

def interact_with_user
  loop do
    @parse_content = true
    type           = :terminal_input
    input_prompt   = bold { color(172) { message_type(@images) + " user" } } + bold { "> " }
    begin
      content = enable_command_completion do
        if prefill_prompt = @prefill_prompt.full?
          Reline.pre_input_hook = -> {
            Reline.insert_text prefill_prompt.gsub(/\n*\z/, '')
            @prefill_prompt = nil
          }
        else
          Reline.pre_input_hook = nil
        end
        Reline.readline(input_prompt, true)&.chomp
      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

    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

    content = content.encode(invalid: :replace)

    content, tags = if @parse_content
                      parse_content(content, @images)
                    else
                      [ content, Documentrix::Utils::Tags.new(valid_tag: /\A#*([\w\]\[]+)/) ]
                    end

    if embedding.on? && content
      records = @documents.find_where(
        content.downcase,
        tags:,
        prompt:     config.embedding.model.prompt?,
        text_size:  config.embedding.found_texts_size?,
        text_count: config.embedding.found_texts_count?,
      )
      unless records.empty?
        content += "\nConsider these chunks for your answer:\n\n"\
          "#{records.map { [ _1.text, _1.tags_set ] * ?\n }.join("\n\n---\n\n")}"
      end
    end

    messages << Ollama::Message.new(role: 'user', content:, images: @images.dup)
    @images.clear
    handler = OllamaChat::FollowChat.new(
      chat:     self,
      messages:,
      voice:    (@current_voice if voice.on?)
    )
    ollama.chat(
      model:    @model,
      messages: ,
      options:  @model_options,
      stream:   stream.on?,
      think:    think.on?,
      &handler
    )
    if embedding.on? && !records.empty?
      STDOUT.puts "", records.map { |record|
        link = if record.source =~ %r(\Ahttps?://)
                 record.source
               else
                 'file://%s' % File.expand_path(record.source)
               end
        [ link, ?# + record.tags.first ]
      }.uniq.map { |l, t| hyperlink(l, t) }.join(' ')
      debug and jj messages.to_ary
    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
    STDOUT.puts "#{bold('Error')}: Currently lost connection to ollama server and cannot send command."
  rescue Interrupt
    STDOUT.puts "Type /quit to quit."
  ensure
      self.server_socket_message = nil
  end
  0
rescue ComplexConfig::AttributeMissing, ComplexConfig::ConfigurationSyntaxError => e
  fix_config(e)
ensure
  save_history
end

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

The links set is memoized, meaning it will only be created once per object instance and subsequent calls will return the same Set instance.

Returns:

  • (Set)

    A Set object containing all links associated with this instance



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

def links
  @links ||= Set.new
end

The manage_links method handles operations on a collection of links, such as displaying them or clearing specific entries.

It supports two main commands: ‘clear’ and nil (default). When the command is ‘clear’, it presents an interactive menu to either clear all links or individual links. When the command is nil, it displays the current list of links with hyperlinks.

Parameters:

  • command (String, nil)

    the operation to perform on the links



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

def manage_links(command)
  case command
  when 'clear'
    loop do
      links_options = links.dup.add('[EXIT]').add('[ALL]')
      link = OllamaChat::Utils::Chooser.choose(links_options, prompt: 'Clear? %s')
      case link
      when nil, '[EXIT]'
        STDOUT.puts "Exiting chooser."
        break
      when '[ALL]'
        if ask?(prompt: 'Are you sure? (y/n) ') =~ /\Ay/i
          links.clear
          STDOUT.puts "Cleared all links in list."
          break
        else
          STDOUT.puts 'Cancelled.'
          sleep 3
        end
      when /./
        links.delete(link)
        STDOUT.puts "Cleared link from links in list."
        sleep 3
      end
    end
  when nil
    if links.empty?
      STDOUT.puts "List is empty."
    else
      Math.log10(links.size).ceil
      format  = "% #{}s. %s"
      connect = -> link { hyperlink(link) { link } }
      STDOUT.puts links.each_with_index.map { |x, i| format % [ i + 1, connect.(x) ] }
    end
  end
end

#setup_cacheDocumentrix::Documents::RedisCache? (private)

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

Returns:

  • (Documentrix::Documents::RedisCache, nil)

    the configured Redis cache instance or nil if no URL is set.



737
738
739
740
741
742
743
744
745
746
# File 'lib/ollama_chat/chat.rb', line 737

def setup_cache
  if url = config.redis.expiring.url?
    ex = config.redis.expiring.ex?.to_i
    Documentrix::Documents::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
676
677
678
679
# 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, @embedding_model_options)
    collection = @opts[?C] || config.embedding.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 and conversation history, then prompts the user for input to begin interacting with the chat.



192
193
194
195
196
197
198
199
200
# File 'lib/ollama_chat/chat.rb', line 192

def start
  info
  if messages.size > 1
    messages.list_conversation(2)
  end
  STDOUT.puts "\nType /help to display the chat help."

  interact_with_user
end

#web(count, query) ⇒ String, Symbol (private)

Performs a web search and processes the results based on document processing configuration.

Searches for the given query using the configured search engine and processes up to the specified number of URLs. The processing approach varies based on the current document policy and embedding status:

  • **Embedding mode**: When ‘@document_policy == ’embedding’‘ AND `@embedding.on?` is true, each result is embedded and the query is interpolated into the `web_embed` prompt.

  • **Summarizing mode**: When ‘@document_policy == ’summarizing’‘, each result is summarized and both query and results are interpolated into the `web_summarize` prompt.

  • **Importing mode**: For all other cases, each result is imported and both query and results are interpolated into the ‘web_import` prompt.

Examples:

Basic web search

web('3', 'ruby programming tutorials')

Web search with embedding policy

# With @document_policy == 'embedding' and @embedding.on?
# Processes results through embedding pipeline

Web search with summarizing policy

# With @document_policy == 'summarizing'
# Processes results through summarization pipeline

Parameters:

  • count (String)

    The maximum number of search results to process (defaults to 1)

  • query (String)

    The search query string

Returns:

  • (String, Symbol)

    The interpolated prompt content when successful, or :next if no URLs were found or processing failed

See Also:



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

def web(count, query)
  urls = search_web(query, count.to_i) or return :next
  if @document_policy == 'embedding' && @embedding.on?
    prompt = config.prompts.web_embed
    urls.each do |url|
      fetch_source(url) { |url_io| embed_source(url_io, url) }
    end
    prompt.named_placeholders_interpolate({query:})
  elsif @document_policy == 'summarizing'
    prompt = config.prompts.web_import
    results = urls.each_with_object('') do |url, content|
      summarize(url).full? do |c|
        content << c.ask_and_send_or_self(:read)
      end
    end
    prompt.named_placeholders_interpolate({query:, results:})
  else
    prompt = config.prompts.web_summarize
    results = urls.each_with_object('') do |url, content|
      import(url).full? do |c|
        content << c.ask_and_send_or_self(:read)
      end
    end
    prompt.named_placeholders_interpolate({query:, results:})
  end
end