Class: Leann::RubyLLM::Search

Inherits:
RubyLLM::Tool
  • Object
show all
Defined in:
lib/leann/ruby_llm/search.rb

Overview

A RubyLLM tool for searching LEANN indexes

Examples:

Basic usage

chat = ::RubyLLM.chat(model: "gpt-4o")
  .with_tool(Leann::RubyLLM::Search.new("my_index"))

chat.ask("What does LEANN do?")
# => LLM searches the index and generates an answer

Multiple indexes

docs_search = Leann::RubyLLM::Search.new("docs", name: "search_docs")
code_search = Leann::RubyLLM::Search.new("codebase", name: "search_code")

chat = ::RubyLLM.chat(model: "gpt-4o")
  .with_tools(docs_search, code_search)

Instance Method Summary collapse

Constructor Details

#initialize(index_name, name: "leann_search", limit: 5) ⇒ Search

Returns a new instance of Search.

Parameters:

  • index_name (String)

    Name of the LEANN index to search

  • name (String) (defaults to: "leann_search")

    Tool name (defaults to “leann_search”)

  • limit (Integer) (defaults to: 5)

    Default number of results (default: 5)



36
37
38
39
40
41
# File 'lib/leann/ruby_llm/search.rb', line 36

def initialize(index_name, name: "leann_search", limit: 5)
  @index_name = index_name
  @default_limit = limit
  @tool_name = name
  super()
end

Instance Method Details

#descriptionObject



47
48
49
50
# File 'lib/leann/ruby_llm/search.rb', line 47

def description
  "Searches the '#{@index_name}' knowledge base for relevant documents. " \
    "Use this to find information before answering questions."
end

#execute(query:, limit: nil) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/leann/ruby_llm/search.rb', line 63

def execute(query:, limit: nil)
  limit ||= @default_limit
  results = Leann.search(@index_name, query, limit: limit)

  if results.empty?
    { found: false, message: "No relevant documents found for: #{query}" }
  else
    {
      found: true,
      count: results.size,
      documents: results.map do |r|
        {
          text: r.text,
          score: r.score.round(3),
          metadata: r.
        }
      end
    }
  end
rescue Leann::IndexNotFoundError
  { error: "Index '#{@index_name}' not found" }
rescue StandardError => e
  { error: e.message }
end

#nameObject



43
44
45
# File 'lib/leann/ruby_llm/search.rb', line 43

def name
  @tool_name
end

#paramsObject



52
53
54
55
56
57
58
59
60
61
# File 'lib/leann/ruby_llm/search.rb', line 52

def params
  ::RubyLLM::Schema.new do
    string :query,
           description: "The search query to find relevant documents",
           required: true
    integer :limit,
            description: "Maximum number of results to return (default: #{@default_limit})",
            required: false
  end
end