Class: AISpec::Core::Providers::OpenAI

Inherits:
Base
  • Object
show all
Defined in:
lib/aispec/core/providers/openai.rb

Constant Summary collapse

BASE_URI =
"https://api.openai.com/v1/chat/completions"

Instance Attribute Summary

Attributes inherited from Base

#model, #options

Instance Method Summary collapse

Methods inherited from Base

get, register

Constructor Details

#initialize(model: "gpt-4o", api_key: nil, **options) ⇒ OpenAI

Returns a new instance of OpenAI.



13
14
15
16
# File 'lib/aispec/core/providers/openai.rb', line 13

def initialize(model: "gpt-4o", api_key: nil, **options)
  super(model: model, **options)
  @api_key = api_key || ENV["OPENAI_API_KEY"]
end

Instance Method Details

#generate(prompt, system_prompt: nil, temperature: 0.7, **_params) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
63
64
65
66
# File 'lib/aispec/core/providers/openai.rb', line 18

def generate(prompt, system_prompt: nil, temperature: 0.7, **_params)
  return fallback_mock_if_no_key(prompt) unless @api_key && !@api_key.empty?

  messages = []
  messages << { role: "system", content: system_prompt } if system_prompt
  messages << { role: "user", content: prompt }

  payload = {
    model: @model || "gpt-4o",
    messages: messages,
    temperature: temperature
  }

  uri = URI.parse(BASE_URI)
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  req = Net::HTTP::Post.new(uri.path, {
    "Content-Type" => "application/json",
    "Authorization" => "Bearer #{@api_key}"
  })
  req.body = JSON.generate(payload)

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.read_timeout = AISpec.configuration.timeout

  res = http.request(req)
  elapsed_ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000.0

  if res.is_a?(Net::HTTPSuccess)
    data = JSON.parse(res.body)
    output = data.dig("choices", 0, "message", "content") || ""
    prompt_tokens = data.dig("usage", "prompt_tokens") || 0
    comp_tokens = data.dig("usage", "completion_tokens") || 0
    total_tokens = data.dig("usage", "total_tokens") || (prompt_tokens + comp_tokens)

    cost = estimate_cost(@model, prompt_tokens, comp_tokens)

    build_response(
      output: output,
      latency_ms: elapsed_ms,
      tokens: total_tokens,
      cost: cost,
      raw: data
    )
  else
    raise "OpenAI API Error (#{res.code}): #{res.body}"
  end
end