Class: OpenaiEmbeddingCreator
- Inherits:
-
Object
- Object
- OpenaiEmbeddingCreator
- Defined in:
- lib/embedding_engines/openai_embeddings.rb
Instance Method Summary collapse
- #call(text, pages_mode = true) ⇒ Object
-
#initialize(api_key = nil, chunker = BasicTextChunker.new, model = "text-embedding-ada-002") ⇒ OpenaiEmbeddingCreator
constructor
A new instance of OpenaiEmbeddingCreator.
Constructor Details
#initialize(api_key = nil, chunker = BasicTextChunker.new, model = "text-embedding-ada-002") ⇒ OpenaiEmbeddingCreator
Returns a new instance of OpenaiEmbeddingCreator.
8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/embedding_engines/openai_embeddings.rb', line 8 def initialize(api_key = nil, chunker = BasicTextChunker.new, model = "text-embedding-ada-002") @chunker = chunker @model = model @api_key = api_key || ENV['OPENAI_API_KEY'] raise 'API key not found. Please set the OPENAI_API_KEY environment variable.' if api_key.nil? || api_key.empty? if @api_key @llm = OpenAI::Client.new(access_token: @api_key) else Rails.logger.error "OpenAI API key not provided. Set the OPENAI_API_KEY in the ENV variables or pass it as an argument." end end |
Instance Method Details
#call(text, pages_mode = true) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/embedding_engines/openai_embeddings.rb', line 21 def call(text, pages_mode=true) if pages_mode vectors = [] return [] unless @llm # Return empty if the API client isn't set up # Divide the text into chunks for each page text.each_with_index do |page_content, page_index| chunks = @chunker.split_into_chunks(page_content) # Create embeddings for each chunk chunks.each_with_index do |chunk, index| response = @llm.( parameters: { model: @model, input: chunk } ) # Extract the embeddings from the response = response['data'][0]['embedding'] # Create vector data for the chunk and keep page numbers for reference vector_data = { id: "vec #{index + 1}", values: , metadata: { text: chunk, page: page_index + 1, } } # storing each chunk vector data in an array vectors << vector_data end end vectors else response = @llm.( parameters: { model: @model, input: chunk } ) # Extract the embeddings from the response response['data'][0]['embedding'] end end |