Class: Phronomy::Agent::Context::Knowledge::Source::RAGKnowledge

Inherits:
Base
  • Object
show all
Defined in:
lib/phronomy/agent/context/knowledge/source/rag_knowledge.rb

Overview

A KnowledgeSource that retrieves semantically relevant chunks from a VectorStore.

On each #fetch call, the query is embedded and the k nearest documents are returned as knowledge chunks.

Examples:

store = Phronomy::Agent::Context::Knowledge::VectorStore::InMemory.new
embeddings = Phronomy::Agent::Context::Knowledge::Embeddings::RubyLLMEmbeddings.new(model: "text-embedding-3-small")
ks = Phronomy::Agent::Context::Knowledge::Source::RAGKnowledge.new(
  store: store,
  embeddings: embeddings,
  k: 5
)

Instance Method Summary collapse

Methods inherited from Base

#fetch_async, #static?

Constructor Details

#initialize(store:, embeddings:, k: 5, type: :rag, source: nil) ⇒ RAGKnowledge

Returns a new instance of RAGKnowledge.

Parameters:



29
30
31
32
33
34
35
# File 'lib/phronomy/agent/context/knowledge/source/rag_knowledge.rb', line 29

def initialize(store:, embeddings:, k: 5, type: :rag, source: nil)
  @store = store
  @embeddings = embeddings
  @k = k
  @type = type
  @source = source
end

Instance Method Details

#fetch(query: nil, cancellation_token: nil) ⇒ Array<Hash>

Embed the query and retrieve the k nearest chunks from the vector store.

Returns an empty array when query is nil or blank.

Parameters:

Returns:

  • (Array<Hash>)


45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/phronomy/agent/context/knowledge/source/rag_knowledge.rb', line 45

def fetch(query: nil, cancellation_token: nil)
  cancellation_token&.raise_if_cancelled!
  return [] if query.nil? || query.strip.empty?

  vector = @embeddings.embed(query, cancellation_token)
  results = @store.search(query_embedding: vector, k: @k, cancellation_token: cancellation_token)
  results.map do |doc|
    chunk = {content: doc[:metadata][:content], type: @type}
    src = @source || doc[:metadata][:source]
    chunk[:source] = src if src
    chunk
  end
end