Class: AsktiveRecord::Adapters::OpenAI

Inherits:
Base
  • Object
show all
Defined in:
lib/asktive_record/adapters/openai.rb

Overview

OpenAI adapter for AsktiveRecord. Wraps the ruby-openai gem to provide LLM communication capabilities.

Examples:

adapter = AsktiveRecord::Adapters::OpenAI.new(
  api_key: ENV["OPENAI_API_KEY"],
  model_name: "gpt-4o"
)
response = adapter.chat("Generate a SQL query...")

Constant Summary collapse

DEFAULT_MODEL =
"gpt-4o-mini"
DEFAULT_TEMPERATURE =
0.2
DEFAULT_MAX_TOKENS =
250

Instance Attribute Summary

Attributes inherited from Base

#api_key, #model_name

Instance Method Summary collapse

Methods inherited from Base

#resolved_model_name

Constructor Details

#initialize(api_key:, model_name: nil) ⇒ OpenAI

Returns a new instance of OpenAI.



22
23
24
25
# File 'lib/asktive_record/adapters/openai.rb', line 22

def initialize(api_key:, model_name: nil)
  super
  @client = nil
end

Instance Method Details

#chat(prompt, options = {}) ⇒ String?

Send a prompt to OpenAI and return the text response.

Parameters:

  • prompt (String)

    the prompt to send

  • options (Hash) (defaults to: {})

    additional options

Options Hash (options):

  • :temperature (Float) — default: 0.2

    the temperature for response generation

  • :max_tokens (Integer) — default: 250

    the maximum tokens in the response

Returns:

  • (String, nil)

    the text response from the LLM



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/asktive_record/adapters/openai.rb', line 34

def chat(prompt, options = {})
  response = client.chat(
    parameters: {
      model: resolved_model_name,
      messages: [{ role: "user", content: prompt }],
      temperature: options.fetch(:temperature, DEFAULT_TEMPERATURE),
      max_tokens: options.fetch(:max_tokens, DEFAULT_MAX_TOKENS)
    }
  )
  response.dig("choices", 0, "message", "content")&.strip
rescue ::OpenAI::Error => e
  raise ApiError, "OpenAI API error: #{e.message}"
end

#default_model_nameString

Returns the default model name for OpenAI.

Returns:

  • (String)


51
52
53
# File 'lib/asktive_record/adapters/openai.rb', line 51

def default_model_name
  DEFAULT_MODEL
end