Class: Zwischen::AI::OpenAIClient

Inherits:
BaseClient show all
Defined in:
lib/zwischen/ai/openai_client.rb

Constant Summary collapse

API_BASE_URL =
"https://api.openai.com/v1/"

Instance Attribute Summary

Attributes inherited from BaseClient

#api_key, #config

Instance Method Summary collapse

Constructor Details

#initialize(api_key: nil, config: {}) ⇒ OpenAIClient

Returns a new instance of OpenAIClient.

Raises:



12
13
14
15
16
17
18
19
20
21
# File 'lib/zwischen/ai/openai_client.rb', line 12

def initialize(api_key: nil, config: {})
  super
  raise Error, "OpenAI API key not found." unless @api_key

  @client = Faraday.new(url: API_BASE_URL) do |conn|
    conn.request :json
    conn.response :json, content_type: /\bjson$/
    conn.adapter Faraday.default_adapter
  end
end

Instance Method Details

#analyze(prompt) ⇒ Object



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
# File 'lib/zwischen/ai/openai_client.rb', line 23

def analyze(prompt)
  model = @config["model"] || "gpt-4"

  # Relative path: a leading slash would discard the /v1 prefix of the base URL
  response = @client.post("chat/completions") do |req|
    req.headers["Authorization"] = "Bearer #{@api_key}"
    req.body = {
      model: model,
      messages: [
        {
          role: "user",
          content: prompt
        }
      ]
    }
  end

  body = response.body
  body = JSON.parse(body) if body.is_a?(String)

  if response.success?
    body.dig("choices", 0, "message", "content")
  else
    error_message = body.dig("error", "message") rescue body
    raise Error, "OpenAI API error: #{error_message}"
  end
rescue Faraday::Error => e
  raise Error, "Network error: #{e.message}"
rescue JSON::ParserError => e
  raise Error, "Invalid JSON response: #{e.message}"
end