Class: Webshaker::Ai

Inherits:
Object
  • Object
show all
Defined in:
lib/webshaker/ai.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(html_content, status_update: ->(status) {}) ⇒ Ai

Returns a new instance of Ai.



5
6
7
8
# File 'lib/webshaker/ai.rb', line 5

def initialize(html_content, status_update: ->(status) {})
  @html_content = html_content
  @status_update = status_update
end

Instance Attribute Details

#html_contentObject (readonly)

Returns the value of attribute html_content.



3
4
5
# File 'lib/webshaker/ai.rb', line 3

def html_content
  @html_content
end

#status_updateObject (readonly)

Returns the value of attribute status_update.



3
4
5
# File 'lib/webshaker/ai.rb', line 3

def status_update
  @status_update
end

Instance Method Details

#analyze(with_prompt:, model: Webshaker.config.model, respond_with: :text, temperature: 0.8, full_response: false) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/webshaker/ai.rb', line 10

def analyze(with_prompt:, model: Webshaker.config.model, respond_with: :text, temperature: 0.8, full_response: false)
  status_update.call(:ai_start)

  response = ai_client.chat(
    parameters: {
      model:,
      messages: messages(with_prompt).concat((respond_with.to_sym == :json) ? [{role: "user", content: "respond with json"}] : []),
      temperature:
    }.merge(
      (respond_with.to_sym == :json) ? {response_format: {type: "json_object"}} : {}
    )
  )

  # Return full response from the ai client if the respond_with is set to :full
  if full_response
    status_update.call(:ai_done)
    return response
  end

  response = response["choices"][0]["message"]["content"]
  response = JSON.parse(response) if respond_with.to_sym === :json

  status_update.call(:ai_done)
  response
end