Class: JekyllAiRelatedPosts::ApiEmbeddings

Inherits:
Object
  • Object
show all
Defined in:
lib/jekyll_ai_related_posts/api_embeddings.rb

Constant Summary collapse

DEFAULT_API_URL =
"https://api.openai.com"
DEFAULT_MODEL =
"text-embedding-3-small"
DEFAULT_DIMENSIONS =
1536

Instance Method Summary collapse

Constructor Details

#initialize(api_key, api_url: nil, model: nil, connection: nil) ⇒ ApiEmbeddings

Returns a new instance of ApiEmbeddings.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/jekyll_ai_related_posts/api_embeddings.rb', line 11

def initialize(api_key, api_url: nil, model: nil, connection: nil)
  @api_url = api_url || DEFAULT_API_URL
  @model = model || DEFAULT_MODEL
  @dimensions = nil

  @connection = if connection.nil?
    Faraday.new(url: @api_url) do |builder|
      builder.request :authorization, "Bearer", api_key
      builder.request :json
      builder.response :json
      builder.response :raise_error
    end
  else
    connection
  end
end

Instance Method Details

#dimensionsObject



28
29
30
# File 'lib/jekyll_ai_related_posts/api_embeddings.rb', line 28

def dimensions
  @dimensions ||= discover_dimensions
end

#embedding_for(text) ⇒ Object



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
# File 'lib/jekyll_ai_related_posts/api_embeddings.rb', line 36

def embedding_for(text)
  res = @connection.post("v1/embeddings") do |req|
    req.body = {
      input: text,
      model: @model
    }
  end

  data = res.body
  unless data.is_a?(Hash) &&
         data["data"].is_a?(Array) &&
         data["data"][0].is_a?(Hash) &&
         data["data"][0]["embedding"].is_a?(Array)
    Jekyll.logger.error "AI Related Posts:", "Unexpected API response structure!"
    Jekyll.logger.error "AI Related Posts:", "Response body: #{data.inspect}"
    raise Error, "Unexpected API response: embedding data not found"
  end

  embedding = data["data"][0]["embedding"]
  @dimensions ||= embedding.length
  embedding
rescue Faraday::Error => e
  Jekyll.logger.error "AI Related Posts:", "Error response from embeddings API!"
  Jekyll.logger.error "AI Related Posts:", e.inspect

  raise
end

#modelObject



32
33
34
# File 'lib/jekyll_ai_related_posts/api_embeddings.rb', line 32

def model
  @model
end