Class: Zwischen::AI::OpenAIClient
- Inherits:
-
BaseClient
- Object
- BaseClient
- Zwischen::AI::OpenAIClient
- 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
Instance Method Summary collapse
- #analyze(prompt) ⇒ Object
-
#initialize(api_key: nil, config: {}) ⇒ OpenAIClient
constructor
A new instance of OpenAIClient.
Constructor Details
#initialize(api_key: nil, config: {}) ⇒ OpenAIClient
Returns a new instance of OpenAIClient.
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 = body.dig("error", "message") rescue body raise Error, "OpenAI API error: #{}" end rescue Faraday::Error => e raise Error, "Network error: #{e.}" rescue JSON::ParserError => e raise Error, "Invalid JSON response: #{e.}" end |