Class: SentimentInsights::Clients::Sentiment::OpenAIClient
- Inherits:
-
Object
- Object
- SentimentInsights::Clients::Sentiment::OpenAIClient
- Defined in:
- lib/sentiment_insights/clients/sentiment/open_ai_client.rb
Constant Summary collapse
- DEFAULT_MODEL =
"gpt-3.5-turbo"- DEFAULT_RETRIES =
3
Instance Method Summary collapse
- #analyze_entries(entries, question: nil, prompt: nil, batch_size: 50) ⇒ Object
-
#initialize(api_key: ENV['OPENAI_API_KEY'], model: DEFAULT_MODEL, max_retries: DEFAULT_RETRIES, return_scores: true) ⇒ OpenAIClient
constructor
A new instance of OpenAIClient.
Constructor Details
#initialize(api_key: ENV['OPENAI_API_KEY'], model: DEFAULT_MODEL, max_retries: DEFAULT_RETRIES, return_scores: true) ⇒ OpenAIClient
Returns a new instance of OpenAIClient.
13 14 15 16 17 18 19 |
# File 'lib/sentiment_insights/clients/sentiment/open_ai_client.rb', line 13 def initialize(api_key: ENV['OPENAI_API_KEY'], model: DEFAULT_MODEL, max_retries: DEFAULT_RETRIES, return_scores: true) @api_key = api_key or raise ArgumentError, "OpenAI API key is required" @model = model @max_retries = max_retries @return_scores = return_scores @logger = Logger.new($stdout) end |
Instance Method Details
#analyze_entries(entries, question: nil, prompt: nil, batch_size: 50) ⇒ Object
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 67 68 69 70 71 72 73 74 75 |
# File 'lib/sentiment_insights/clients/sentiment/open_ai_client.rb', line 21 def analyze_entries(entries, question: nil, prompt: nil, batch_size: 50) all_sentiments = [] entries.each_slice(batch_size) do |batch| prompt_content = build_prompt_content(batch, question: question, prompt: prompt) request_body = { model: @model, messages: [ { role: "user", content: prompt_content } ], temperature: 0.0 } uri = URI("https://api.openai.com/v1/chat/completions") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true response_content = nil attempt = 0 while attempt < @max_retries attempt += 1 request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["Authorization"] = "Bearer #{@api_key}" request.body = JSON.generate(request_body) begin response = http.request(request) rescue StandardError => e @logger.error "OpenAI API request error: #{e.class} - #{e.}" raise end status = response.code.to_i if status == 429 @logger.warn "Rate limit (HTTP 429) on attempt #{attempt}. Retrying..." sleep(2 ** (attempt - 1)) next elsif status != 200 @logger.error "Request failed (#{status}): #{response.body}" raise "OpenAI API Error: #{status}" else data = JSON.parse(response.body) response_content = data.dig("choices", 0, "message", "content") break end end sentiments = parse_sentiments(response_content, batch.size) all_sentiments.concat(sentiments) end all_sentiments end |