Sha256: eb68ddbdcad4aaec62476ca7a8d05cc07e44b53b4fddc62200852817586ab5b8

Contents?: true

Size: 1.3 KB

Versions: 1

Compression:

Stored size: 1.3 KB

Contents

module Webshaker
  class Ai
    attr_reader :html_content

    def initialize(html_content)
      @html_content = html_content
    end

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

      # Return full response from the ai client if the respond_with is set to :full
      return response if full_response

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

    private

    def ai_client
      @client ||= OpenAI::Client.new(access_token: Webshaker.config.open_ai_key)
    end

    def messages(user_prompt)
      [
        {role: "system", content: "You are an HTML interpreter. The user will give you the contents of an HTML and ask you something about it. Please comply with what the user asks."},
        {role: "user", content: html_content},
        {role: "user", content: user_prompt}
      ]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
webshaker-0.0.4 lib/webshaker/ai.rb