Class: JekyllAiRelatedPosts::ApiEmbeddings
- Inherits:
-
Object
- Object
- JekyllAiRelatedPosts::ApiEmbeddings
- 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
- #dimensions ⇒ Object
- #embedding_for(text) ⇒ Object
-
#initialize(api_key, api_url: nil, model: nil, connection: nil) ⇒ ApiEmbeddings
constructor
A new instance of ApiEmbeddings.
- #model ⇒ Object
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
#dimensions ⇒ Object
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 (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 = data["data"][0]["embedding"] @dimensions ||= .length 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 |
#model ⇒ Object
32 33 34 |
# File 'lib/jekyll_ai_related_posts/api_embeddings.rb', line 32 def model @model end |