Class: RubyLLM::SearchResults

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_llm/search_results.rb

Overview

A SearchResults wraps documents a Tool returns so the model can cite each source. RubyLLM renders them in the selected provider's citation format; cited passages appear on Message#citations.

def execute(query:)
docs = MyVectorStore.search(query)

RubyLLM::SearchResults.new(
  *docs.map { |doc| { title: doc.name, url: doc.link, text: doc.body } }
)
end

Cited passages come back on the response as Message#citations.

Constant Summary collapse

KEY =

:nodoc:

'search_results'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*results, **result) ⇒ SearchResults

Returns a new SearchResults built from one or more result hashes, or from a single result given as keywords.

RubyLLM::SearchResults.new(title: 'Q4 Report', url: report_url, text: report_text)
RubyLLM::SearchResults.new({ title: 'A', text: '...' }, { title: 'B', text: '...' })

Each result is reduced to its :title, :url, and :text entries. Raises ArgumentError if no results are given or a result is missing :title or :text.

Raises:



33
34
35
36
37
# File 'lib/ruby_llm/search_results.rb', line 33

def initialize(*results, **result)
  results << result if result.any?
  @results = results.map { |entry| normalize(entry) }
  raise ArgumentError, 'SearchResults requires at least one result' if @results.empty?
end

Instance Attribute Details

#resultsObject (readonly)

The normalized results, as an array of hashes with :title, :text, and optional :url keys.



22
23
24
# File 'lib/ruby_llm/search_results.rb', line 22

def results
  @results
end

Class Method Details

.from_content(content) ⇒ Object

:nodoc:



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

def self.from_content(content) # :nodoc:
  return unless content.is_a?(String) && content.lstrip.start_with?('{')

  parsed = JSON.parse(content)
  entries = parsed[KEY]
  return unless entries.is_a?(Array) && entries.any? && entries.all?(Hash)

  new(*entries)
rescue JSON::ParserError, ArgumentError
  nil
end

Instance Method Details

#to_hObject

:nodoc:



51
52
53
# File 'lib/ruby_llm/search_results.rb', line 51

def to_h # :nodoc:
  { KEY => results }
end

#to_json(*args) ⇒ Object

:nodoc:



55
56
57
# File 'lib/ruby_llm/search_results.rb', line 55

def to_json(*args) # :nodoc:
  JSON.generate(to_h, *args)
end