Skip to content

Commit

Permalink
Add sentiment attribute and calculation to SurveyResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
CoralineAda committed Aug 20, 2024
1 parent 09612ec commit c9e7471
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 1 deletion.
14 changes: 14 additions & 0 deletions app/jobs/sentiment_analysis_job.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# This background job hydrates the graph from a SurveyResponse.
class SentimentAnalysisJob

include Sidekiq::Job

queue_as :default

def perform(id)
return unless record = SurveyResponse.find(id)
Rails.logger.info("SentimentAnalysisJob running with survey response ID #{id}")
record.classify_sentiment
end

end
25 changes: 25 additions & 0 deletions app/models/survey_response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ class SurveyResponse < ApplicationRecord

REQUIRED_FIELDS = [:age_given]

# This is the prompt passed to the AI agent to serve as instructions for sentiment analysis.
SENTIMENT_PROMPT = %{
You are a social researcher doing textual analysis. Perform sentiment analysis against the provided text, classifying it as "positive", "negative", or "neutral". Return the classification encoded as JSON in the following format:
{
"sentiment" : "positive"
}
The text to perform sentiment analysis on is as follows:
}


# Given a file handle to a data file, parse the filel contents as CSV and hydrate SurveyResponse records in serial.
def self.import(file_handle)
CSV.read(file_handle, headers: true).each do |record|
Expand Down Expand Up @@ -104,6 +117,18 @@ def persona
)
end

# Calculates and sets the sentiment based on a the "identity reflection / notes" field.
# This method uses the Clients::OpenAi client passing the text of the reflection as an
# argument to the prompt. The agent returns a classification, which is written to the
# SurveyResponse record.
def classify_sentiment
response = Clients::OpenAi.request("#{SENTIMENT_PROMPT} #{self.notes}")
return unless response['sentiment'].present?
classification = response['sentiment'].strip.downcase
update_attribute(:sentiment, classification)
return classification
end

def populate_experience_codes
{
"age" => age_exp_codes,
Expand Down
5 changes: 5 additions & 0 deletions db/migrate/20240820223410_add_sentiment_to_survey_response.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class AddSentimentToSurveyResponse < ActiveRecord::Migration[7.1]
def change
add_column :survey_responses, :sentiment, :string
end
end
3 changes: 2 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit c9e7471

Please sign in to comment.