Module: OllamaChat::RAGHandling

Included in:
Chat
Defined in:
lib/ollama_chat/rag_handling.rb

Overview

A module that handles Retrieval-Augmented Generation (RAG) operations for the OllamaChat application.

This module provides functionality for managing collections, clearing and changing collections, listing collections, and renaming collections within the RAG system.

Instance Method Summary collapse

Instance Method Details

#all_collections ⇒ Sequel::Dataset (private)

Retrieves all document collections registered in the database.

Returns:

  • (Sequel::Dataset) —

    a dataset of all collections ordered by name.



508
509
510
# File 'lib/ollama_chat/rag_handling.rb', line 508

def all_collections
  models::Collection.order(:name)
end

#choose_collection(current_collection) ⇒ Object (private)

The choose_collection method presents a menu to select or create a document collection. It displays existing collections along with options to create a new one or exit. The method prompts the user for input and updates the document collection accordingly.

Parameters:

  • current_collection (String, nil) —

    the name of the currently active collection



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

def choose_collection(current_collection)
  collections = [ current_collection ] + all_collections.pluck(:name)
  collections = collections.filter_map(&:to_s).uniq.sort
  collections.unshift('[EXIT]').unshift('[NEW]')
  collection = choose_entry(
    collections,
    prompt: 'Which archive of knowledge shall we delve into? %s'
  ) || current_collection
  case collection = collection&.to_s
  when '[NEW]'
    if name = create_collection
      set_documents_collection(name)
    end
  when nil, '[EXIT]'
    feedback("Exiting chooser.")
  when /./
    set_documents_collection(collection)
  end
ensure
  if collection
    @session.update(current_collection: collection)
    log(:info, "Collection switched", data: { collection: })
    feedback("Using collection #{bold{collection}}.", type: :info)
  end
  info
end

#clear_collection_sources ⇒ Object (private)

Removes source documents from the collection through an interactive user interface.

Each source is displayed with its associated tags for context. Users can preview a source's records in a pager before confirming removal.



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

def clear_collection_sources
  choose_with_state do
    loop do
      sources     = Set.new
      source_tags = Hash.new { |h, k| h[k] = Set.new }
      @documents.records.each do |record|
        source = record.source.full? or next
        sources << source
        source_tags[source].merge(record.tags)
      end
      display_map = {}
      sources.each do |s|
        tags = source_tags[s].map(&:to_s)
        line = tags.any? ? "#{s}  [#{tags.join(', ')}]" : s
        display_map[line] = s
      end
      display = display_map.keys
      display.unshift('[EXIT]')
      chosen = choose_entry(
        display,
        prompt: 'Which source to remove from the collection? %s'
      )
      case chosen
      when nil, '[EXIT]'
        feedback("Exiting chooser.")
        break
      else
        source = display_map[chosen]
        action = confirm?(prompt: "  🔍[v]iew / 🧹[c]lear / 🔙other to go back: ")
        case action
        when /\Av/i
          records = @documents.records(sources: [ source ])
          use_pager(force: true) do |output|
            output.puts "#{bold{source}} (#{records.size} records)"
            output.puts
            records.each do |record|
              output.puts kramdown_ansi_parse(<<~EOT)
                **[#{record.tags.join(', ')}]**
                ```
                #{wrap(record.text.sub(/\n+\z/, ''), percentage: 90)}
                ```
                ---
              EOT
            end
          end
        when /\Ac/i
          @documents.source_remove(source)
          log(:info, "Source removed from collection",
              data: { collection:, source: })
          feedback(
            "Removed source #{source} from collection #{bold{collection}}.",
            type:    :info,
            timeout: 3,
          )
        end
      end
    end
  end
end

#clear_collection_tags ⇒ Object (private)

Clears documents from the collection through an interactive two-level tag browser.

Level 1: choose a tag from the collection. Level 2: inspect records grouped by source, with preview (v) and surgical clear (c) options.



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

def clear_collection_tags
  choose_with_state do
    loop do
      display = @documents.tags.map(&:to_s).sort.unshift('[EXIT]')
      tag = choose_entry(
        display,
        prompt: 'Which tag to inspect? %s'
      )
      case tag
      when nil, '[EXIT]'
        feedback('Exiting chooser.')
        break
      else
        records = @documents.records(tags: tag)
        groups  = records.group_by { |r| r.source.full? || '(nil)' }

        if groups.size == 1 && groups.values.first.size == 1
          record  = groups.values.first.first
          source  = record.source
          snippet = record.text.strip[0, 72].inspect
          label   = source ? "#{source} #{snippet}" : snippet
          feedback(label, type: :info)
          view_tag_records(tag, [record])
          confirm?(prompt: "  🧹[c]lear / 🔙other to go back: ") =~ /\Ac/i or next
          clear_tag_records(tag, source)
        else
          group_lines = []
          group_map   = {}
          groups.sort_by { |src, _| src }.each do |src, recs|
            if recs.size == 1
              snippet = recs.first.text.strip[0, 72].inspect
              line = src == '(nil)' ? snippet : "#{src} #{snippet}"
            else
              line = "#{src} (#{recs.size} records)"
            end
            group_lines << line
            group_map[line] = [src, recs]
          end
          group_lines.unshift('[back]')
          chosen = choose_entry(
            group_lines,
            prompt: "Tag #{tag.to_s.gsub(?%, '%%')} — which source group? %s"
          )
          next if chosen.nil? || chosen == '[back]'
          src, recs = group_map[chosen]
          action = confirm?(prompt: "  🔍[v]iew / 🧹[c]lear / 🔙other to go back: ")
          case action
          when /\Av/i
            view_tag_records(tag, recs)
          when /\Ac/i
            clear_tag_records(tag, src == '(nil)' ? nil : src)
          end
        end
      end
    end
  end
end

#clear_tag_records(tag, source) ⇒ Object (private)

Clears records for a tag, using source_remove when a source is present, or clear(tags:) for memory entries (no source).



361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/ollama_chat/rag_handling.rb', line 361

def clear_tag_records(tag, source)
  if source
    @documents.source_remove(source)
  else
    @documents.clear(tags: [ tag ])
  end
  log(:info, 'Tag cleared from collection',
      data: { collection:, tag:, source: })
  feedback(
    "Cleared tag #{tag} from collection #{bold{collection}}.",
    type:    :info,
    timeout: 3,
  )
end

#clear_whole_collection ⇒ nil, OllamaChat::Chat (private)

The clear_whole_collection method confirms user intent to delete the entire collection, then clears all documents and logs the action, returning self on success.

Returns:

  • (nil, OllamaChat::Chat) —

    when the user declines the confirmation prompt, self otherwise.



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/ollama_chat/rag_handling.rb', line 260

def clear_whole_collection
  target = collection
  prompt = "🔥 This will incinerate every record in #{target.inspect}. " \
    "Type the name to confirm (C-c ⇒ cancel): "
  typed = switch_history(:collection_name) do
    ask?(prompt:, prefill: target).full?(:strip)
  end
  if typed == target
    @documents.clear
    log(:info, "Collection #{target.inspect} cleared", data: { collection: })
    feedback("Cleared collection #{bold{collection}}.", type: :info)
    self
  else
    feedback('Denied.', type: :denied)
    nil
  end
end

#collection ⇒ String

Returns the name of the currently active document collection.

Returns:

  • (String) —

    the name of the current collection



67
68
69
# File 'lib/ollama_chat/rag_handling.rb', line 67

def collection
  @documents.collection.to_s
end

#collection_descriptions ⇒ Hash{String => String}

Retrieves a hash of collection names and their descriptions from the database.

This is used to provide context to the AI model about available RAG collections.

Returns:

  • (Hash{String => String}) —

    a hash mapping collection names to their descriptions



87
88
89
90
91
92
93
# File 'lib/ollama_chat/rag_handling.rb', line 87

def collection_descriptions
  cols = models::Collection.where(enabled: true)
    .select(:name, :description).order(:name)
  cols.each_with_object({}) do |c, hash|
    hash[c.name] = c.description
  end
end

#create_collection ⇒ Object (private)

Interactively create a new collection record.



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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# File 'lib/ollama_chat/rag_handling.rb', line 655

def create_collection
  name = switch_history(:collection_name) do
    ask?(prompt: "📚 Name of the new collection: ")
  end
  unless name.full?
    feedback("Cancelled creation of collection.", type: :cancel)
    return
  end

  if database_collection?(name)
    feedback("Collection #{name.inspect} already exists.", type: :warn)
    return
  end

  description = switch_history(:collection_description) do
    ask?(prompt: "📝 Description: ")
  end
  unless description.full?
    feedback("Cancelled creation of collection #{name.inspect}.", type: :cancel)
    return
  end
  patterns_str = switch_history(:patterns) do
    ask?(prompt: "🔍 Patterns (space-separated globs, e.g., lib/**/*.rb): ")
  end
  patterns = extract_patterns(patterns_str)

  begin
    models::Collection.create(
      name: name.to_s,
      description: description.to_s,
      patterns:
    )
    if patterns.full?
      update_collection(name.to_s)
    end
    feedback("Created collection '#{name}'.", type: :success)
    log(:info, "Collection created", data: { name:, description:, patterns: })
  rescue Sequel::UniqueConstraintViolation
    feedback("Collection #{name.inspect} already exists.", type: :warn)
  rescue Sequel::Error => e
    feedback("Database error: #{e.message}", type: :warn)
  end
  name.to_s
end

#create_memory_collection(persona_name) ⇒ String

Creates (or reuses) the persistent memory collection for a persona.

The collection name is derived from the argument: a bare stem gets the memory- prefix; a full memory-* name is used as-is. The collection is registered with an empty pattern list. If it already exists, it is returned without modification.

This is the single canonical entry point for ensuring a persona's memory collection exists before it is referenced by the trigger mechanism, the memorize/forget tools, or any other consumer.

Parameters:

  • persona_name (String) —

    the persona stem (e.g. "personal_assistant") or the full collection name (e.g. "memory-personal_assistant").

Returns:

  • (String) —

    the collection name (e.g. "memory-personal_assistant").



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ollama_chat/rag_handling.rb', line 49

def create_memory_collection(persona_name)
  collection = persona_name.to_s
  collection = "memory-#{collection}" unless collection.start_with?('memory-')

  unless chat.database_collection?(collection)
    models::Collection.create(
      name:        collection,
      description: "Memory for persona #{persona_name}",
      patterns:    [],
    )
  end

  collection
end

#database_collection?(collection) ⇒ OllamaChat::Database::Models::Collection?

Looks up a collection in the database by name.

Parameters:

  • collection (String, Symbol, #to_s) —

    the collection name to look up

Returns:



31
32
33
# File 'lib/ollama_chat/rag_handling.rb', line 31

def database_collection?(collection)
  models::Collection[name: collection.to_s]
end

#delete_collection ⇒ Object (private)

Permanently remove a collection from DB and purge from Documentrix.



756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
# File 'lib/ollama_chat/rag_handling.rb', line 756

def delete_collection
  choose_with_state do
    loop do
      collections = models::Collection.order(:name).pluck(:name)
      collections.unshift('[CANCEL]')
      target_name = choose_entry(
        collections,
        prompt: '🗑️ Which collection to delete? %s'
      )
      break if target_name.nil? || target_name == '[CANCEL]'

      col = database_collection?(target_name)
      unless col
        feedback("Collection #{target_name.inspect} not found in database.", type: :warn)
        next
      end

      if target_name.to_s == 'default'
        feedback(
          "Cannot delete #{target_name.inspect}: it is the default collection. " \
            'Switch to another collection first.',
          type: :warn
        )
        next
      end

      destroyed = false
      if confirm?(prompt: "⚠️ Are you sure you want to permanently delete #{target_name.inspect}? (y/n) ", yes: /\Ay/i)
        begin
          col.chat = self
          col.destroy
          destroyed = true
          feedback("Deleted collection #{target_name.inspect}.", type: :success)
          log(:info, "Collection deleted", data: { name: target_name })
        rescue Sequel::Error => e
          feedback("Database error: #{e.message}", type: :warn)
        rescue => e
          feedback("Error removing from Documentrix: #{e.message}", type: :warn)
        ensure
          if destroyed && session.current_collection == target_name
            session.update(current_collection: 'default')
          end
        end
      else
        feedback("Deletion denied.", type: :denied)
      end
    end
  end
end

#edit_collection ⇒ Object (private)

Interactively update attributes of an existing collection.



701
702
703
704
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'lib/ollama_chat/rag_handling.rb', line 701

def edit_collection
  collections = models::Collection.order(:name).pluck(:name)
  collections.unshift('[CANCEL]')
  target_name = choose_entry(
    collections,
    prompt: '📚 Which collection to edit? %s'
  )
  return if target_name.nil? || target_name == '[CANCEL]'

  col = database_collection?(target_name)
  unless col
    feedback("Collection #{target_name.inspect} not found in database.", type: :warn)
    return
  end

  new_description = switch_history :collection_description do
    ask?(
      prompt: "📝 New description (leave blank to keep): ",
      prefill: col.description
    )
  end
  patterns = switch_history :patterns do
    patterns_str = ask?(
      prompt: "🔍 New patterns (space-separated, leave blank to keep): ",
      prefill: col.patterns.full?(:join, ' ')
    )
    extract_patterns(patterns_str)
  end

  enabled_prompt = col.enabled ?
    "🚫 Disable this collection? (hidden from the model) (y/n) " :
    "✅ Enable this collection? (visible to the model) (y/n) "
  toggle = case confirm?(prompt: enabled_prompt)
           when /\Ay/i then true
           when /\An/i then false
           end

  col.description = new_description.full? ? new_description.to_s : col.description
  col.patterns    = patterns
  col.enabled     = toggle ^ col.enabled unless toggle.nil?

  begin
    col.save
    if toggle
      status = col.enabled ? 'enabled' : 'disabled'
      feedback("Collection '#{col.name}' is now #{status}.", type: :info)
    end
    feedback("Updated collection '#{col.name}'.", type: :success)
    log(:info, "Collection updated", data: { name: col.name, enabled: col.enabled })
  rescue Sequel::Error => e
    feedback("Database error: #{e.message}", type: :warn)
  end
end

#extract_patterns(patterns_str) ⇒ Array<String> (private)

Extracts and normalizes file patterns from a shell-style string.

Splits the input string using shell semantics, correctly handling spaces enclosed in single/double quotes or escaped with backslashes. Each resulting pattern is expanded to an absolute path.

Parameters:

  • patterns_str (String, nil) —

    the shell-style glob patterns

Returns:

  • (Array<String>) —

    an array of expanded absolute path patterns



649
650
651
652
# File 'lib/ollama_chat/rag_handling.rb', line 649

def extract_patterns(patterns_str)
  patterns = Shellwords.split(patterns_str.to_s)
  patterns.map { File.expand_path(_1) }
end

#list_collections ⇒ Object (private)

Displays the list of available collections in the terminal.

This method retrieves the current collection and the full list of available collections and their descriptions from the internal document handler, highlighting the active one.



517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/ollama_chat/rag_handling.rb', line 517

def list_collections
  current_collection = collection.to_s
  collections = all_collections.select(:name, :description, :enabled)
  use_pager do |output|
    collections.each { |c|
      enabled                = c.enabled ? '✅' : '⛔'
      collection_name        = current_collection == c.name ? bold { c.name } : c.name
      collection_description = c.description

      output.puts '%s %s: %s' % [ enabled, collection_name, collection_description ]
    }
  end
end

#memory_dump(filename) ⇒ Object

Dumps one or more memory-<persona> collections to a JSONL file for portable backup or migration.

Presents an accumulating chooser of all memory-* collections: pick individual collections (they drop out of the list once selected), [ALL] to grab everything remaining, or [DONE] to commit the write. Each line carries a collection field so one file can hold multiple personas.

Parameters:

  • filename (String, nil) —

    the output path (must end in .json/.jsonl); prompts interactively if nil



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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/ollama_chat/rag_handling.rb', line 106

def memory_dump(filename)
  collections = all_collections
    .where(Sequel.lit('name LIKE "memory-%"'))
    .pluck(:name)
  return feedback('No memory-* collections found.', type: :warn) unless collections

  selected = Set.new
  choose_with_state do
    loop do
      remaining = collections - selected.to_a
      entries   = (remaining.empty? ? [] : ['[ALL]'] + remaining) + ['[DONE]']
      choice    = choose_entry(entries, prompt: 'Which memory collections to dump? %s')
      case choice
      when nil, '[DONE]'
        break
      when '[ALL]'
        selected.merge(remaining)
        break
      else
        selected << choice
      end
    end
  end

  return feedback('Cancelled, no collections selected.', type: :cancel) if selected.empty?

  filename.present? or filename = ask_for_filename?(action: 'to dump into')
  unless filename
    feedback("Dumping memory cancelled.", type: :cancel)
    return
  end
  filename = Pathname.new(filename).expand_path
  should_overwrite?(filename) or return

  feedback("Dumping #{selected.size} collection(s): #{selected.sort.join(', ')}")

  records = []
  selected.sort.each do |col|
    switch_collection(col) do
      @documents.each_record do |r|
        records << {
          collection: col,
          text:       r.text,
          tags:       r.tags.to_a.map { _1.to_s(link: false) },
          source:     r.source.full?,
        }.compact
      end
    end
  end

  OllamaChat::Utils::JSONJSONLIO.new(filename).write(collection: records)
  log(:info, 'Memory dumped',
      data: { collections: selected.sort, records: records.size, file: filename.to_s })
  feedback(
    "Dumped #{records.size} record(s) across #{selected.size} collection(s) to #{filename.to_s.inspect}.",
    type: :success
  )
end

#memory_restore(filename) ⇒ Object

Restores memory-<persona> collections from a JSONL dump file.

Presents an accumulating chooser of all collections found in the file: pick individual collections (they drop out of the list once selected), [ALL] to grab everything remaining, or [DONE] to commit the restore. Records are added with their original tag and source so timestamps and file associations survive.

Parameters:

  • filename (String, nil) —

    the input path (must end in .json/.jsonl); prompts interactively if nil



175
176
177
178
179
180
181
182
183
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
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
# File 'lib/ollama_chat/rag_handling.rb', line 175

def memory_restore(filename)
  unless filename.present?
    filename = ask_for_filename?(action: 'to restore from')
  end
  unless filename
    feedback("Restoring memory cancelled.", type: :cancel)
    return
  end
  filename = Pathname.new(filename).expand_path
  filename.exist? or return feedback("File #{filename.to_s.inspect} not found.", type: :warn)

  entries = OllamaChat::Utils::JSONJSONLIO.new(filename).read.to_a
  return feedback("No records found in #{filename.to_s.inspect}.", type: :warn) if entries.empty?

  collections = entries.group_by { |e| e['collection'] }.reject { _1.nil? }
  return feedback('No collection field found in entries.', type: :warn) if collections.empty?

  selected = Set.new
  choose_with_state do
    loop do
      remaining = collections.keys - selected.to_a
      choices   = (remaining.empty? ? [] : ['[ALL]'] + remaining) + ['[DONE]']
      choice    = choose_entry(choices, prompt: 'Which memory collections to restore? %s')
      case choice
      when nil, '[DONE]'
        break
      when '[ALL]'
        selected.merge(remaining)
        break
      else
        selected << choice
      end
    end
  end

  return feedback('Cancelled, no collections selected.', type: :cancel) if selected.empty?

  selected = selected.sort

  feedback("Restoring #{selected.size} collection(s): #{selected.join(', ')}")

  total   = 0
  skipped = 0
  collections.slice(*selected).sort.each do |col, group|
    create_memory_collection(col)
    switch_collection(col) do
      existing_tags = Set.new
      @documents.each_record do |r|
        r.tags.each { |t| existing_tags << t.to_s(link: false) }
      end

      group.each do |entry|
        tags = Array(entry['tags'])
        if tags.any? { |t| existing_tags.include?(t) }
          skipped += 1
          next
        end
        @documents.add(
          [entry['text']],
          tags:,
          batch_size: 1,
          source: entry['source']
        )
        total += 1
      end
    end
  end

  log(:info, 'Memory restored',
      data: { file: filename.to_s, collections: selected, records: total, skipped: })
  feedback(
    "Restored #{total} record(s) across #{selected.size} collection(s) from #{filename.to_s.inspect}." +
      (skipped.zero? ? '' : " (#{skipped} duplicate(s) skipped)."),
    type: :success
  )
end

#query_collection(edit: false, rerank: false) ⇒ Object (private)

Queries the active collection for matching records and prints a scored result table for debugging and inspection.

Parameters:

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

    use edit_text for query input (default: false)

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

    apply LLM rerank to results (default: false)



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

def query_collection(edit: false, rerank: false)
  unless embedding.on?
    feedback("Embedding is disabled.", type: :warn)
    return
  end
  query =
    if edit
      edit_text.full?(:strip)
    else
      switch_history(:query) { ask?(prompt: "🔍 Query: ").full?(:strip) }
    end
  query.blank? and return

  records = find_document_records(query)
  if rerank && records.any?
    records = rerank_records(query, records)
  end

  use_pager do |output|
    suffix = records.size == 1 ? '' : 's'
    output.puts "📚 Collection: #{collection.to_s} (#{records.size} record#{suffix})"
    output.puts
    if records.empty?
      output.puts '  No records found.'
    else
      max_num_width = Math.log10(1 + records.size).ceil
      records.each_with_index do |record, i|
        score = format('%.1f%%', record.similarity * 100)
        text  = wrap(
          truncate(record.text.strip, length: 5 * Tins::Terminal.rows),
          percentage: 90
        )
        link = if record.source =~ %r(\Ahttps?://)
                 record.source
               elsif record.source.present?
                 'file://%s' % File.expand_path(record.source)
               end
        tag = ?# + record.tags.first
        if tag && link
          tag = hyperlink(link, tag)
        end
        num = bold { "%#{max_num_width}u." % (i + 1) }
        feedback(format("%s %s %s", num, score, tag), output:)
        feedback(kramdown_ansi_parse("```\n%s\n```" % text), output:)
        feedback(kramdown_ansi_parse(?- * 3), output:)
      end
    end
  end
  log(:info, "Collection queried", data: {
    collection: collection.to_s, query:, hits: records.size, rerank:
  })
end

#rename_collection(current_collection) ⇒ Object (private)

Rename an existing collection to a new, user‑supplied name.

This helper prompts the user to provide a new name for the collection identified by current_collection. It then renames the current collection to have the new_name and switches to it.

Parameters:

  • current_collection (Symbol) —

    the current collection name



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/rag_handling.rb', line 483

def rename_collection(current_collection)
  prompt = 'Rename collection %s to: ' % current_collection
  new_collection = switch_history :collection_name do
    ask?(prompt:, prefill: current_collection).full?(:to_sym)
  end
  if new_collection
    begin
      @documents.rename_collection(new_collection)
      col = database_collection?(current_collection)
      col&.update(name: new_collection.to_s)
      log(:info, "Collection renamed", data: { old_name: current_collection, new_name: new_collection })
      feedback("Renamed current collection #{current_collection} to #{new_collection}.", type: :info)
    rescue Sequel::UniqueConstraintViolation
      feedback("Renaming to #{new_collection} failed, it already exists in database.", type: :warn)
    rescue => e
      feedback("Renaming to #{new_collection} failed: #{e.message}", type: :warn)
    end
  else
    feedback("Renaming cancelled.", type: :cancel)
  end
end

#set_documents_collection(collection) ⇒ String, Symbol

Sets the documents collection to collection.

Parameters:

  • collection (String, Symbol) —

    the name of the collection to set

Returns:

  • (String, Symbol) —

    the newly set collection name



75
76
77
# File 'lib/ollama_chat/rag_handling.rb', line 75

def set_documents_collection(collection)
  @documents.collection = collection
end

#switch_collection(other_collection = nil) { ... } ⇒ Object

Temporarily switches the RAG collection to the specified collection.

The current collection is stored and restored after the block is executed, ensuring the state remains consistent regardless of whether the block completes successfully or raises an error.

Parameters:

  • other_collection (String, nil) (defaults to: nil) —

    the collection to switch to. If nil, the current collection is used.

Yields:

  • The code to execute within the context of the switched collection.

Returns:

  • (Object) —

    the result of the block.



18
19
20
21
22
23
24
# File 'lib/ollama_chat/rag_handling.rb', line 18

def switch_collection(other_collection = nil)
  other_collection ||= collection
  old_collection, @documents.collection = collection, other_collection
  yield other_collection
ensure
  @documents.collection = old_collection
end

#update_collection(collection) ⇒ String (private)

Updates the documents in the current collection by re-embedding any sources that have been modified since they were first added, and embedding any new files matching the collection's patterns.

This method iterates through all records in the active collection and identifies unique sources. For each modified source, it preserves the existing tags, removes the stale records, and re-embeds the current version of the source. It then scans for new files matching the collection's patterns and embeds them.

Returns:

  • (String) —

    a newline-separated string of embedding result messages.



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

def update_collection(collection)
  results = []
  switch_collection(collection) do
    unless col = database_collection?(collection)
      feedback("Collection #{collection.inspect} not found in database.", type: :warn)
      return ''
    end

    matched_sources = nil
    if patterns = col.patterns.full?
      matched_sources = all_file_set(patterns).map(&:to_s).to_set
    end

    sources = {}
    seen    = Set.new
    @documents.each_record do |record|
      source = @documents.normalize_source(record.source) or next
      if matched_sources.nil? || matched_sources.member?(source)
        seen.member?(source) and next
        seen << source
        unless @documents.source_modified?(source)
          infobar.puts "Source #{source.to_s.inspect} is unmodified. => Skipping."
          next
        end
        sources[source] = record.tags_set
      end
      @documents.source_remove(source)
    end

    if patterns = col.patterns.full?
      new_sources = all_file_set(patterns).map(&:to_s).reject { seen.member?(_1) }.to_set
      new_sources.each { seen << _1 }
      new_sources.each { sources[_1] = [] }
    end

    results.concat(bulk_embed_sources(sources))
    log(:info, "Collection updated", data: { collection:, sources_updated: results.size })
  end
  results * ?\n
end

#view_tag_records(tag, records) ⇒ Object (private)

Renders tag-filtered records in the pager.



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/ollama_chat/rag_handling.rb', line 343

def view_tag_records(tag, records)
  use_pager(force: true) do |output|
    output.puts "#{bold{tag}} (#{records.size} records)"
    output.puts
    records.each do |record|
      output.puts kramdown_ansi_parse(<<~EOT)
        **#{record.source}**
        ```
        #{wrap(record.text.sub(/\n+\z/, ''), percentage: 90)}
        ```
        ---
      EOT
    end
  end
end