Module: RubyLLM::Text::Sentiment

Defined in:
lib/ruby_llm/text/sentiment.rb

Constant Summary collapse

DEFAULT_CATEGORIES =
[ "positive", "negative", "neutral" ].freeze

Class Method Summary collapse

Class Method Details

.build_prompt(text, categories:, simple:) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/ruby_llm/text/sentiment.rb', line 40

def self.build_prompt(text, categories:, simple:)
  categories_list = categories.join(", ")

  if simple
    output_instruction = "Return only the sentiment category name, nothing else."
  else
    output_instruction = "      Return a JSON object with:\n      - \"label\": the sentiment category\n      - \"confidence\": a confidence score between 0 and 1 (where 1 is completely confident)\n    OUTPUT\n  end\n\n  <<~PROMPT\n    Analyze the sentiment of the following text.\n\n    Categories: \#{categories_list}\n\n    \#{output_instruction}\n\n    Text:\n    \#{text}\n  PROMPT\nend\n"

.call(text, categories: DEFAULT_CATEGORIES, simple: false, model: nil, **options) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ruby_llm/text/sentiment.rb', line 6

def self.call(text, categories: DEFAULT_CATEGORIES, simple: false, model: nil, **options)
  model ||= RubyLLM::Text.config.model_for(:sentiment)

  prompt = build_prompt(text, categories: categories, simple: simple)

  if simple
    Base.call_llm(prompt, model: model, **options)
  else
    # For structured output with confidence score
    schema = {
      type: "object",
      properties: {
        label: { type: "string", enum: categories },
        confidence: { type: "number", minimum: 0, maximum: 1 }
      },
      required: [ "label", "confidence" ]
    }
    response = Base.call_llm(prompt, model: model, schema: schema, **options)

    begin
      result = JSON.parse(Base.clean_json_response(response))
      # Ensure confidence is a float
      result["confidence"] = result["confidence"].to_f
      result
    rescue JSON::ParserError
      # If JSON parsing fails, fall back to simple mode (no schema), as documented.
      simple_prompt = build_prompt(text, categories: categories, simple: true)
      Base.call_llm(simple_prompt, model: model, **options)
    end
  end
end