Module: RubyLLM::Mongoid::GridFsAttachment

Extended by:
ActiveSupport::Concern
Defined in:
lib/ruby_llm/mongoid/grid_fs_attachment.rb

Overview

Optional concern for message models that want GridFS-backed file attachments instead of Active Storage.

Usage:

class Message
  include Mongoid::Document
  include RubyLLM::Mongoid::GridFsAttachment
  acts_as_message
end

Each uploaded file is stored in a MongoDB GridFS bucket (default: “attachments”). Metadata is tracked in the gridfs_file_ids array field on the document.

To use a different bucket name:

class Message
  include RubyLLM::Mongoid::GridFsAttachment
  use_gridfs_bucket :llm_files
end

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#cleanup_gridfs_tempfilesObject

Cleanup tempfiles created during download



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/ruby_llm/mongoid/grid_fs_attachment.rb', line 39

def cleanup_gridfs_tempfiles
  return unless defined?(@_gridfs_tempfiles) && @_gridfs_tempfiles

  @_gridfs_tempfiles.each do |f|
    f.close
    f.unlink
  rescue StandardError => e
    RubyLLM.logger.warn "RubyLLM: Failed to cleanup GridFS tempfile #{f.path}: #{e.message}"
  end
  @_gridfs_tempfiles = []
end

#gridfs_content(text) ⇒ Object

Builds a RubyLLM::Content that streams each stored file back from GridFS. Called by message_methods#extract_content when gridfs_file_ids is non-empty.



53
54
55
56
57
58
59
60
61
62
# File 'lib/ruby_llm/mongoid/grid_fs_attachment.rb', line 53

def gridfs_content(text)
  sources = gridfs_file_ids.filter_map { |meta| download_gridfs_file(meta) }
  return text if sources.empty?

  if text.present?
    RubyLLM::Content.new(text).tap { |c| sources.each { |f, name| c.add_attachment(f, filename: name) } }
  else
    RubyLLM::Content.new(nil, sources.map(&:first))
  end
end