Class: AIRecordFinder::PromptBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/ai_record_finder/prompt_builder.rb

Overview

Builds strict prompts so the AI emits only the expected JSON DSL.

Constant Summary collapse

ALLOWED_OPERATORS =
%w[eq gt lt gte lte between in like].freeze

Instance Method Summary collapse

Constructor Details

#initialize(schema:, max_limit:) ⇒ PromptBuilder

Returns a new instance of PromptBuilder.



10
11
12
13
# File 'lib/ai_record_finder/prompt_builder.rb', line 10

def initialize(schema:, max_limit:)
  @schema = schema
  @max_limit = max_limit
end

Instance Method Details

#system_promptObject



15
16
17
18
19
20
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
# File 'lib/ai_record_finder/prompt_builder.rb', line 15

def system_prompt
  <<~PROMPT
    You convert user requests into a strict query JSON DSL for ActiveRecord.
    Output rules:
    - Return ONLY JSON. No markdown, no code fences, no commentary.
    - Never output SQL, pseudo-SQL, or Ruby code.
    - Do not include keys not listed below.
    - Use only the provided schema fields.
    - Limit must be an integer between 1 and #{@max_limit}.
    - Operators allowed: #{ALLOWED_OPERATORS.join(', ')}

    JSON format:
    {
      "filters": [
        { "field": "status", "operator": "eq", "value": "unpaid" }
      ],
      "limit": 50,
      "sort": { "field": "created_at", "direction": "desc" }
    }

    Field constraints:
    - Allowed base fields are these columns: #{@schema[:columns].keys.sort.join(', ')}
    - Associated fields must use "association.column" (example: "user.email")
    - Allowed sort directions: asc, desc
    - For operator "between", value must be an array of two values
    - For operator "in", value must be an array

    Schema summary:
    #{JSON.pretty_generate(@schema)}
  PROMPT
end

#user_prompt(natural_language_prompt) ⇒ Object



47
48
49
# File 'lib/ai_record_finder/prompt_builder.rb', line 47

def user_prompt(natural_language_prompt)
  natural_language_prompt.to_s.strip
end