Module: RubyLLM::Text::Grammar

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

Class Method Summary collapse

Class Method Details

.build_prompt(text, explain:, preserve_style:) ⇒ Object



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
# File 'lib/ruby_llm/text/grammar.rb', line 41

def self.build_prompt(text, explain:, preserve_style:)
  style_instruction = preserve_style ?
    "Preserve the original tone, style, and level of formality." :
    ""

  if explain
    output_instruction = <<~OUTPUT
      Return a JSON object with:
      - "corrected": the corrected text
      - "changes": an array of changes made (e.g., "their → they're", "tommorow → tomorrow")
    OUTPUT
  else
    output_instruction = "Return only the corrected text with no explanation or additional commentary."
  end

  <<~PROMPT
    Fix grammar, spelling, punctuation, and word choice errors in the following text.
    #{style_instruction}

    #{output_instruction}

    Text:
    #{text}
  PROMPT
end

.call(text, explain: false, preserve_style: false, model: nil, **options) ⇒ Object



4
5
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
37
# File 'lib/ruby_llm/text/grammar.rb', line 4

def self.call(text, explain: false, preserve_style: false, model: nil, **options)
  model ||= RubyLLM::Text.config.model_for(:grammar)

  prompt = build_prompt(text, explain: explain, preserve_style: preserve_style)

  if explain
    # For structured output with explanations
    schema = {
      type: "object",
      properties: {
        corrected: { type: "string" },
        changes: {
          type: "array",
          items: { type: "string" }
        }
      },
      required: [ "corrected", "changes" ]
    }
    response = Base.call_llm(prompt, model: model, schema: schema, **options)

    begin
      JSON.parse(Base.clean_json_response(response))
    rescue JSON::ParserError
      # Fallback: if JSON parsing fails, return best-effort structured response
      cleaned_response = Base.clean_json_response(response)
      {
        "corrected" => cleaned_response,
        "changes" => []
      }
    end
  else
    Base.call_llm(prompt, model: model, **options)
  end
end