Class: SentimentInsights::Clients::KeyPhrases::OpenAIClient
- Inherits:
-
Object
- Object
- SentimentInsights::Clients::KeyPhrases::OpenAIClient
- Defined in:
- lib/sentiment_insights/clients/key_phrases/open_ai_client.rb
Constant Summary collapse
- DEFAULT_MODEL =
"gpt-3.5-turbo"- DEFAULT_RETRIES =
3
Instance Method Summary collapse
-
#extract_batch(entries, question: nil, key_phrase_prompt: nil, sentiment_prompt: nil) ⇒ Object
Extract key phrases from entries and enrich with sentiment.
-
#initialize(api_key: ENV['OPENAI_API_KEY'], model: DEFAULT_MODEL, max_retries: DEFAULT_RETRIES) ⇒ OpenAIClient
constructor
A new instance of OpenAIClient.
Constructor Details
#initialize(api_key: ENV['OPENAI_API_KEY'], model: DEFAULT_MODEL, max_retries: DEFAULT_RETRIES) ⇒ OpenAIClient
Returns a new instance of OpenAIClient.
14 15 16 17 18 19 20 |
# File 'lib/sentiment_insights/clients/key_phrases/open_ai_client.rb', line 14 def initialize(api_key: ENV['OPENAI_API_KEY'], model: DEFAULT_MODEL, max_retries: DEFAULT_RETRIES) @api_key = api_key or raise ArgumentError, "OpenAI API key is required" @model = model @max_retries = max_retries @logger = Logger.new($stdout) @sentiment_client = SentimentInsights::Clients::Sentiment::OpenAIClient.new(api_key: @api_key, model: @model) end |
Instance Method Details
#extract_batch(entries, question: nil, key_phrase_prompt: nil, sentiment_prompt: nil) ⇒ Object
Extract key phrases from entries and enrich with sentiment
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 |
# File 'lib/sentiment_insights/clients/key_phrases/open_ai_client.rb', line 23 def extract_batch(entries, question: nil, key_phrase_prompt: nil, sentiment_prompt: nil) responses = [] phrase_map = Hash.new { |h, k| h[k] = [] } # Fetch sentiments in batch from sentiment client sentiments = @sentiment_client.analyze_entries(entries, question: question, prompt: sentiment_prompt) entries.each_with_index do |entry, index| sentence = entry[:answer].to_s.strip next if sentence.empty? response_id = "r_#{index + 1}" phrases = extract_phrases_from_sentence(sentence, question: question, prompt: key_phrase_prompt) sentiment = sentiments[index] || { label: :neutral } responses << { id: response_id, sentence: sentence, sentiment: sentiment[:label], segment: entry[:segment] || {} } phrases.each do |phrase| phrase_map[phrase.downcase] << response_id end end phrases = phrase_map.map do |phrase, ref_ids| { phrase: phrase, mentions: ref_ids.uniq, summary: nil } end { phrases: phrases, responses: responses } end |