Class: Vectorsearch::Qdrant

Inherits:
Base
  • Object
show all
Defined in:
lib/vectorsearch/qdrant.rb

Constant Summary

Constants inherited from Base

Base::DEFAULT_COHERE_DIMENSION, Base::DEFAULT_METRIC, Base::DEFAULT_OPENAI_DIMENSION, Base::LLMS

Instance Attribute Summary

Attributes inherited from Base

#client, #index_name, #llm, #llm_api_key

Instance Method Summary collapse

Methods inherited from Base

#generate_completion, #generate_embedding, #generate_prompt

Constructor Details

#initialize(url:, api_key:, index_name:, llm:, llm_api_key:) ⇒ Qdrant

Returns a new instance of Qdrant.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/vectorsearch/qdrant.rb', line 7

def initialize(
  url:,
  api_key:,
  index_name:,
  llm:,
  llm_api_key:
)
  @client = ::Qdrant::Client.new(
    url: url,
    api_key: api_key
  )
  @index_name = index_name

  super(llm: llm, llm_api_key: llm_api_key)
end

Instance Method Details

#add_texts(texts:) ⇒ Hash

Add a list of texts to the index

Parameters:

  • texts (Array)

    The list of texts to add

Returns:

  • (Hash)

    The response from the server



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/vectorsearch/qdrant.rb', line 26

def add_texts(
  texts:
)
  batch = { ids: [], vectors: [], payloads: [] }

  texts.each do |text|
    batch[:ids].push(SecureRandom.uuid)
    batch[:vectors].push(generate_embedding(text: text))
    batch[:payloads].push({ content: text })
  end

  client.points.upsert(
    collection_name: index_name,
    batch: batch
  )
end

#ask(question:) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/vectorsearch/qdrant.rb', line 79

def ask(question:)
  search_results = similarity_search(query: question)

  context = search_results.dig("result").map do |result|
    result.dig("payload").to_s
  end
  context = context.join("\n---\n")

  prompt = generate_prompt(question: question, context: context)

  generate_completion(prompt: prompt)
end

#create_default_schemaHash

Create the index with the default schema

Returns:

  • (Hash)

    The response from the server



45
46
47
48
49
50
51
52
53
# File 'lib/vectorsearch/qdrant.rb', line 45

def create_default_schema
  client.collections.create(
    collection_name: index_name,
    vectors: {
      distance: DEFAULT_METRIC.capitalize,
      size: default_dimension
    }
  )
end

#similarity_search(query:, k: 4) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/vectorsearch/qdrant.rb', line 55

def similarity_search(
  query:,
  k: 4
)
  embedding = generate_embedding(text: query)

  similarity_search_by_vector(
    embedding: embedding,
    k: k
  )
end

#similarity_search_by_vector(embedding:, k: 4) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/vectorsearch/qdrant.rb', line 67

def similarity_search_by_vector(
  embedding:,
  k: 4
)
  client.points.search(
    collection_name: index_name,
    limit: k,
    vector: embedding,
    with_payload: true
  )
end