Class: Journeybook::Ai::OpenaiClient
- Inherits:
-
Object
- Object
- Journeybook::Ai::OpenaiClient
- Defined in:
- app/services/journeybook/ai/openai_client.rb
Defined Under Namespace
Classes: Error
Constant Summary collapse
- ENDPOINT =
URI("https://api.openai.com/v1/responses")
Instance Method Summary collapse
- #complete(prompt) ⇒ Object
-
#initialize(api_key: Journeybook.configuration.openai_api_key.presence || ENV["OPENAI_API_KEY"], model: Journeybook.configuration.openai_model) ⇒ OpenaiClient
constructor
A new instance of OpenaiClient.
Constructor Details
#initialize(api_key: Journeybook.configuration.openai_api_key.presence || ENV["OPENAI_API_KEY"], model: Journeybook.configuration.openai_model) ⇒ OpenaiClient
Returns a new instance of OpenaiClient.
11 12 13 14 |
# File 'app/services/journeybook/ai/openai_client.rb', line 11 def initialize(api_key: Journeybook.configuration.openai_api_key.presence || ENV["OPENAI_API_KEY"], model: Journeybook.configuration.openai_model) @api_key = api_key @model = model end |
Instance Method Details
#complete(prompt) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'app/services/journeybook/ai/openai_client.rb', line 16 def complete(prompt) raise Error, "OpenAI API key is missing. Set config.openai_api_key or OPENAI_API_KEY." if @api_key.blank? response = Net::HTTP.start(ENDPOINT.host, ENDPOINT.port, use_ssl: true) do |http| http.request(build_request(prompt)) end body = JSON.parse(response.body) raise Error, openai_error(body, response) unless response.is_a?(Net::HTTPSuccess) extract_text(body) rescue JSON::ParserError raise Error, "OpenAI returned an invalid JSON response." end |