queryclerk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Queryclerk
6
+ # Builds strict prompts so the AI emits only the expected JSON DSL.
7
+ class PromptBuilder
8
+ ALLOWED_OPERATORS = %w[eq gt lt gte lte between in like].freeze
9
+
10
+ def initialize(schema:, max_limit:)
11
+ @schema = schema
12
+ @max_limit = max_limit
13
+ end
14
+
15
+ def system_prompt
16
+ <<~PROMPT
17
+ You convert user requests into a strict query JSON DSL for ActiveRecord.
18
+ Output rules:
19
+ - Return ONLY JSON. No markdown, no code fences, no commentary.
20
+ - Never output SQL, pseudo-SQL, or Ruby code.
21
+ - Do not include keys not listed below.
22
+ - Use only the provided schema fields.
23
+ - Limit must be an integer between 1 and #{@max_limit}.
24
+ - Operators allowed: #{ALLOWED_OPERATORS.join(', ')}
25
+
26
+ JSON format:
27
+ {
28
+ "filters": [
29
+ { "field": "status", "operator": "eq", "value": "unpaid" }
30
+ ],
31
+ "limit": 50,
32
+ "sort": { "field": "created_at", "direction": "desc" }
33
+ }
34
+
35
+ Field constraints:
36
+ - Allowed base fields are these columns: #{@schema[:columns].keys.sort.join(', ')}
37
+ - Associated fields must use "association.column" (example: "user.email")
38
+ - Allowed sort directions: asc, desc
39
+ - For operator "between", value must be an array of two values
40
+ - For operator "in", value must be an array
41
+
42
+ Schema summary:
43
+ #{JSON.pretty_generate(@schema)}
44
+ PROMPT
45
+ end
46
+
47
+ def user_prompt(natural_language_prompt)
48
+ natural_language_prompt.to_s.strip
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base"
4
+
5
+ module Queryclerk
6
+ module Providers
7
+ # Anthropic native Messages API (https://api.anthropic.com/v1/messages).
8
+ #
9
+ # Differs from OpenAI: x-api-key auth + anthropic-version header, a
10
+ # top-level `system` prompt, a required `max_tokens`, and a response whose
11
+ # text lives in a `content` array of typed blocks rather than `choices`.
12
+ class Anthropic < Base
13
+ ENDPOINT_PATH = "messages"
14
+
15
+ private
16
+
17
+ def endpoint_path
18
+ ENDPOINT_PATH
19
+ end
20
+
21
+ def request_headers
22
+ {
23
+ "x-api-key" => configuration.api_key,
24
+ "anthropic-version" => configuration.anthropic_version,
25
+ "Content-Type" => "application/json"
26
+ }
27
+ end
28
+
29
+ def request_payload(system_prompt, user_prompt)
30
+ {
31
+ model: configuration.model_name,
32
+ max_tokens: configuration.max_tokens,
33
+ temperature: configuration.temperature,
34
+ system: system_prompt,
35
+ messages: [
36
+ { role: "user", content: user_prompt }
37
+ ]
38
+ }
39
+ end
40
+
41
+ def extract_content(parsed)
42
+ blocks = parsed["content"]
43
+ if blocks.is_a?(Array)
44
+ text_block = blocks.find { |block| block.is_a?(Hash) && block["type"] == "text" }
45
+ return text_block["text"] if text_block && !text_block["text"].nil?
46
+ end
47
+
48
+ raise AIResponseError, "AI response missing content text block"
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "faraday"
4
+ require "json"
5
+
6
+ module Queryclerk
7
+ module Providers
8
+ # Shared HTTP transport for chat-style LLM providers.
9
+ #
10
+ # Subclasses implement the provider-specific contract:
11
+ # #endpoint_path, #request_headers, #request_payload, #extract_content
12
+ #
13
+ # Endpoint paths MUST be relative (no leading slash) so they append to the
14
+ # configured base URL's path (e.g. ".../v1") instead of replacing it.
15
+ class Base
16
+ def initialize(configuration:, connection: nil)
17
+ @configuration = configuration
18
+ @connection = connection
19
+ validate_configuration!
20
+ end
21
+
22
+ def chat_completion(system_prompt:, user_prompt:)
23
+ response = post_request(system_prompt, user_prompt)
24
+ ensure_success!(response)
25
+ extract_content(parse_body(response))
26
+ rescue Faraday::Error => e
27
+ raise AIResponseError, "AI request failed: #{e.message}"
28
+ end
29
+
30
+ private
31
+
32
+ attr_reader :configuration
33
+
34
+ def post_request(system_prompt, user_prompt)
35
+ connection.post(endpoint_path) do |req|
36
+ request_headers.each { |name, value| req.headers[name] = value }
37
+ req.body = JSON.generate(request_payload(system_prompt, user_prompt))
38
+ end
39
+ end
40
+
41
+ def connection
42
+ @connection ||= Faraday.new(url: configuration.api_base_url) do |f|
43
+ f.options.timeout = configuration.request_timeout
44
+ f.options.open_timeout = configuration.request_timeout
45
+ f.adapter Faraday.default_adapter
46
+ end
47
+ end
48
+
49
+ def parse_body(response)
50
+ JSON.parse(response.body.to_s)
51
+ rescue JSON::ParserError
52
+ raise AIResponseError, "AI response body is not valid JSON"
53
+ end
54
+
55
+ # Faraday does not raise on non-2xx, so check the status explicitly. Error
56
+ # bodies are not guaranteed to be JSON (a gateway may return HTML/plain
57
+ # text), so this must surface a useful detail without depending on a
58
+ # successful parse — hence it runs before parse_body.
59
+ def ensure_success!(response)
60
+ return if response.success?
61
+
62
+ raise AIResponseError, "AI request failed: #{error_detail(response)}"
63
+ end
64
+
65
+ # Both OpenAI and Anthropic nest the human-readable error under
66
+ # error.message; fall back to the HTTP status for non-JSON error bodies.
67
+ def error_detail(response)
68
+ parsed = JSON.parse(response.body.to_s)
69
+ (parsed.is_a?(Hash) && parsed.dig("error", "message")) || "HTTP #{response.status}"
70
+ rescue JSON::ParserError
71
+ "HTTP #{response.status}"
72
+ end
73
+
74
+ def validate_configuration!
75
+ return unless configuration.api_key.to_s.strip.empty?
76
+
77
+ raise ConfigurationError, "Missing API key. Set Queryclerk.configure { |c| c.api_key = ... }"
78
+ end
79
+
80
+ # --- Provider contract (subclasses must override) ---
81
+
82
+ def endpoint_path
83
+ raise NotImplementedError, "#{self.class} must implement #endpoint_path"
84
+ end
85
+
86
+ def request_headers
87
+ raise NotImplementedError, "#{self.class} must implement #request_headers"
88
+ end
89
+
90
+ def request_payload(_system_prompt, _user_prompt)
91
+ raise NotImplementedError, "#{self.class} must implement #request_payload"
92
+ end
93
+
94
+ def extract_content(_parsed)
95
+ raise NotImplementedError, "#{self.class} must implement #extract_content"
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base"
4
+
5
+ module Queryclerk
6
+ module Providers
7
+ # OpenAI (and OpenAI-compatible) Chat Completions API.
8
+ class OpenAI < Base
9
+ ENDPOINT_PATH = "chat/completions"
10
+
11
+ private
12
+
13
+ def endpoint_path
14
+ ENDPOINT_PATH
15
+ end
16
+
17
+ def request_headers
18
+ {
19
+ "Authorization" => "Bearer #{configuration.api_key}",
20
+ "Content-Type" => "application/json"
21
+ }
22
+ end
23
+
24
+ def request_payload(system_prompt, user_prompt)
25
+ {
26
+ model: configuration.model_name,
27
+ temperature: configuration.temperature,
28
+ messages: [
29
+ { role: "system", content: system_prompt },
30
+ { role: "user", content: user_prompt }
31
+ ]
32
+ }
33
+ end
34
+
35
+ def extract_content(parsed)
36
+ choices = parsed["choices"]
37
+ if choices.is_a?(Array) && choices.first
38
+ # content is null when the model replies with tool_calls only.
39
+ content = choices.first.dig("message", "content")
40
+ return content unless content.nil?
41
+ end
42
+
43
+ raise AIResponseError, "AI response missing choices[0].message.content"
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "providers/base"
4
+ require_relative "providers/openai"
5
+ require_relative "providers/anthropic"
6
+
7
+ module Queryclerk
8
+ # Provider strategy registry. Maps a configured provider symbol to the
9
+ # concrete transport that speaks that vendor's chat API.
10
+ module Providers
11
+ REGISTRY = {
12
+ openai: OpenAI,
13
+ anthropic: Anthropic
14
+ }.freeze
15
+
16
+ # @param configuration [Queryclerk::Configuration]
17
+ # @param connection [Faraday::Connection, nil] injectable transport (tests)
18
+ # @return [Queryclerk::Providers::Base]
19
+ def self.build(configuration:, connection: nil)
20
+ provider_class = REGISTRY[configuration.provider]
21
+ unless provider_class
22
+ raise ConfigurationError,
23
+ "Unknown provider #{configuration.provider.inspect}. " \
24
+ "Supported providers: #{REGISTRY.keys.join(", ")}"
25
+ end
26
+
27
+ provider_class.new(configuration: configuration, connection: connection)
28
+ end
29
+
30
+ def self.supported
31
+ REGISTRY.keys
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Queryclerk
4
+ # Builds an ActiveRecord::Relation from validated DSL.
5
+ class QueryBuilder
6
+ def initialize(model:, dsl:, configuration:)
7
+ @model = model
8
+ @dsl = dsl
9
+ @configuration = configuration
10
+ @arel_table = model.arel_table
11
+ end
12
+
13
+ def call
14
+ @joins = requested_joins
15
+ SafetyGuard.validate_joins!(model: @model, joins: @joins, configuration: @configuration)
16
+
17
+ relation = @model.all
18
+ relation = SafetyGuard.apply_tenant_scope(model: @model, relation: relation)
19
+ relation = apply_joins(relation)
20
+ relation = apply_filters(relation)
21
+ relation = apply_sort(relation)
22
+ relation.limit(@dsl["limit"])
23
+ end
24
+
25
+ private
26
+
27
+ def apply_joins(relation)
28
+ @joins.reduce(relation) do |current_relation, association_name|
29
+ current_relation.left_joins(association_name.to_sym)
30
+ end
31
+ end
32
+
33
+ def apply_filters(relation)
34
+ @dsl.fetch("filters", []).reduce(relation) do |current_relation, filter|
35
+ field = filter.fetch("field")
36
+ operator = filter.fetch("operator")
37
+ value = filter["value"]
38
+
39
+ apply_filter(current_relation, field, operator, value)
40
+ end
41
+ end
42
+
43
+ def apply_filter(relation, field, operator, value)
44
+ attribute = resolve_attribute(field)
45
+
46
+ case operator
47
+ when "eq"
48
+ relation.where(attribute.eq(value))
49
+ when "gt"
50
+ relation.where(attribute.gt(value))
51
+ when "lt"
52
+ relation.where(attribute.lt(value))
53
+ when "gte"
54
+ relation.where(attribute.gteq(value))
55
+ when "lte"
56
+ relation.where(attribute.lteq(value))
57
+ when "between"
58
+ relation.where(attribute.between(value[0]..value[1]))
59
+ when "in"
60
+ relation.where(attribute.in(value))
61
+ when "like"
62
+ pattern = "%#{ActiveRecord::Base.sanitize_sql_like(value.to_s)}%"
63
+ relation.where(attribute.matches(pattern))
64
+ else
65
+ raise InvalidDSL, "Unsupported operator: #{operator}"
66
+ end
67
+ end
68
+
69
+ def apply_sort(relation)
70
+ sort = @dsl["sort"]
71
+ return relation unless sort
72
+
73
+ field = sort.fetch("field")
74
+ direction = sort.fetch("direction")
75
+ attribute = resolve_attribute(field)
76
+ relation.reorder(direction == "asc" ? attribute.asc : attribute.desc)
77
+ end
78
+
79
+ def requested_joins
80
+ explicit = Array(@dsl["joins"]).map(&:to_s)
81
+ from_filters = @dsl.fetch("filters", []).map { |filter| association_for_field(filter.fetch("field")) }.compact
82
+ from_sort = [association_for_field(@dsl.dig("sort", "field"))].compact
83
+
84
+ (explicit + from_filters + from_sort).uniq
85
+ end
86
+
87
+ def association_for_field(field)
88
+ return nil unless field.to_s.include?(".")
89
+
90
+ field.to_s.split(".", 2).first
91
+ end
92
+
93
+ def resolve_attribute(field)
94
+ field_name = field.to_s
95
+ return @arel_table[field_name] unless field_name.include?(".")
96
+
97
+ association_name, column_name = field_name.split(".", 2)
98
+ reflection = @model.reflect_on_association(association_name.to_sym)
99
+ raise InvalidDSL, "Unknown association join: #{association_name}" unless reflection
100
+
101
+ reflection.klass.arel_table[column_name]
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/railtie"
4
+
5
+ module Queryclerk
6
+ # Rails integration hook.
7
+ class Railtie < Rails::Railtie
8
+ initializer "queryclerk.configure" do
9
+ Queryclerk.configuration
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Queryclerk
4
+ # Centralized policy checks that enforce fail-closed query safety.
5
+ class SafetyGuard
6
+ class << self
7
+ def validate_model!(model:, configuration:)
8
+ unless defined?(ActiveRecord::Base) && model.is_a?(Class) && model < ActiveRecord::Base
9
+ raise InvalidModelError, "Model must inherit from ActiveRecord::Base"
10
+ end
11
+
12
+ allowed_models = Array(configuration.allowed_models)
13
+ return if allowed_models.include?(model)
14
+
15
+ raise UnauthorizedModel, "Model #{model.name} is not in allowed_models"
16
+ end
17
+
18
+ def validate_joins!(model:, joins:, configuration:)
19
+ joins = Array(joins)
20
+ return if joins.empty?
21
+
22
+ allowed = Array(configuration.allowed_associations[model.name] || configuration.allowed_associations[model])
23
+ reflection_names = model.reflect_on_all_associations.map { |association| association.name.to_s }
24
+
25
+ joins.each do |join_name|
26
+ join_name = join_name.to_s
27
+ unless reflection_names.include?(join_name)
28
+ raise InvalidDSL, "Unknown association join: #{join_name}"
29
+ end
30
+
31
+ unless allowed.include?(join_name)
32
+ raise InvalidDSL, "Join not allowed by policy: #{join_name}"
33
+ end
34
+ end
35
+ end
36
+
37
+ def apply_tenant_scope(model:, relation:)
38
+ return relation unless model.respond_to?(:current_tenant_scope)
39
+
40
+ scope = model.current_tenant_scope
41
+ return relation unless scope
42
+ raise InvalidDSL, "current_tenant_scope must return an ActiveRecord::Relation" unless scope.is_a?(ActiveRecord::Relation)
43
+
44
+ relation.merge(scope)
45
+ end
46
+
47
+ def enforce_limit!(limit:, max_limit:)
48
+ return if limit.is_a?(Integer) && limit.positive? && limit <= max_limit
49
+
50
+ raise InvalidDSL, "limit must be between 1 and #{max_limit}"
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Queryclerk
4
+ # Extracts a safe summary of model schema that can be sent to the AI.
5
+ class SchemaIntrospector
6
+ def initialize(model)
7
+ @model = model
8
+ end
9
+
10
+ def call
11
+ {
12
+ model: @model.name,
13
+ table: @model.table_name,
14
+ columns: columns_summary,
15
+ associations: associations_summary,
16
+ association_columns: association_columns_summary,
17
+ enums: enums_summary
18
+ }
19
+ end
20
+
21
+ private
22
+
23
+ def columns_summary
24
+ @model.columns.each_with_object({}) do |column, memo|
25
+ memo[column.name] = {
26
+ type: column.type,
27
+ null: column.null,
28
+ default: column.default
29
+ }
30
+ end
31
+ end
32
+
33
+ def associations_summary
34
+ @model.reflect_on_all_associations.each_with_object({}) do |association, memo|
35
+ memo[association.name.to_s] = {
36
+ macro: association.macro,
37
+ class_name: association.class_name
38
+ }
39
+ end
40
+ end
41
+
42
+ def enums_summary
43
+ return {} unless @model.respond_to?(:defined_enums)
44
+
45
+ @model.defined_enums.transform_values(&:keys)
46
+ end
47
+
48
+ def association_columns_summary
49
+ @model.reflect_on_all_associations.each_with_object({}) do |association, memo|
50
+ next if association.polymorphic?
51
+
52
+ columns = association.klass.columns.each_with_object({}) do |column, column_memo|
53
+ column_memo[column.name] = { type: column.type }
54
+ end
55
+
56
+ memo[association.name.to_s] = {
57
+ table: association.klass.table_name,
58
+ columns: columns
59
+ }
60
+ rescue StandardError
61
+ # Skip associations that cannot be safely introspected.
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Queryclerk
4
+ VERSION = "0.1.0"
5
+ end
data/lib/queryclerk.rb ADDED
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "queryclerk/version"
4
+ require_relative "queryclerk/errors"
5
+ require_relative "queryclerk/configuration"
6
+ require_relative "queryclerk/providers"
7
+ require_relative "queryclerk/client"
8
+ require_relative "queryclerk/schema_introspector"
9
+ require_relative "queryclerk/prompt_builder"
10
+ require_relative "queryclerk/ai_adapter"
11
+ require_relative "queryclerk/dsl_parser"
12
+ require_relative "queryclerk/query_builder"
13
+ require_relative "queryclerk/safety_guard"
14
+
15
+ begin
16
+ require_relative "queryclerk/railtie"
17
+ rescue LoadError
18
+ # Rails is optional outside Rails applications.
19
+ end
20
+
21
+ # Main entry point for natural-language to ActiveRecord query translation.
22
+ module Queryclerk
23
+ class << self
24
+ # @return [Queryclerk::Configuration]
25
+ def configuration
26
+ @configuration ||= Configuration.new
27
+ end
28
+
29
+ # @yieldparam config [Queryclerk::Configuration]
30
+ def configure
31
+ yield(configuration)
32
+ end
33
+
34
+ # Converts a natural-language prompt into an ActiveRecord::Relation.
35
+ #
36
+ # @param prompt [String]
37
+ # @param model [Class]
38
+ # @param ai_adapter [#call, nil] Optional injectable adapter for tests.
39
+ # @return [ActiveRecord::Relation]
40
+ def query(prompt:, model:, ai_adapter: nil)
41
+ SafetyGuard.validate_model!(model: model, configuration: configuration)
42
+
43
+ schema = SchemaIntrospector.new(model).call
44
+ prompt_builder = PromptBuilder.new(schema: schema, max_limit: configuration.max_limit)
45
+ adapter = ai_adapter || AIAdapter.new(client: Client.new(configuration: configuration))
46
+
47
+ raw_dsl = adapter.call(
48
+ system_prompt: prompt_builder.system_prompt,
49
+ user_prompt: prompt_builder.user_prompt(prompt)
50
+ )
51
+
52
+ dsl = DSLParser.new(
53
+ model: model,
54
+ schema: schema,
55
+ dsl: raw_dsl,
56
+ max_limit: configuration.max_limit
57
+ ).call
58
+
59
+ QueryBuilder.new(model: model, dsl: dsl, configuration: configuration).call
60
+ end
61
+
62
+ # Resets runtime configuration. Intended for tests.
63
+ def reset_configuration!
64
+ @configuration = Configuration.new
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,3 @@
1
+ module Queryclerk
2
+ VERSION: String
3
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+
5
+ RSpec.describe Queryclerk::AIAdapter do
6
+ it "strips markdown code fences and parses JSON" do
7
+ client = instance_double("Client")
8
+ allow(client).to receive(:chat_completion).and_return(
9
+ <<~TEXT
10
+ ```json
11
+ {"filters":[],"limit":10}
12
+ ```
13
+ TEXT
14
+ )
15
+
16
+ result = described_class.new(client: client).call(system_prompt: "x", user_prompt: "y")
17
+ expect(result).to eq("filters" => [], "limit" => 10)
18
+ end
19
+
20
+ it "raises AIResponseError for invalid JSON" do
21
+ client = instance_double("Client")
22
+ allow(client).to receive(:chat_completion).and_return("not-json")
23
+
24
+ expect do
25
+ described_class.new(client: client).call(system_prompt: "x", user_prompt: "y")
26
+ end.to raise_error(Queryclerk::AIResponseError)
27
+ end
28
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "json"
5
+
6
+ RSpec.describe Queryclerk::Client do
7
+ def stub_connection(base_url, expected_path, response)
8
+ stubs = Faraday::Adapter::Test::Stubs.new
9
+ stubs.post(expected_path) do |_env|
10
+ [200, { "Content-Type" => "application/json" }, JSON.generate(response)]
11
+ end
12
+ Faraday.new(url: base_url) { |f| f.adapter :test, stubs }
13
+ end
14
+
15
+ it "delegates to the OpenAI provider by default" do
16
+ cfg = Queryclerk::Configuration.new.tap { |c| c.api_key = "k" }
17
+ conn = stub_connection(
18
+ cfg.api_base_url, "/v1/chat/completions",
19
+ { "choices" => [{ "message" => { "content" => "openai-out" } }] }
20
+ )
21
+
22
+ client = described_class.new(configuration: cfg, connection: conn)
23
+
24
+ expect(client.chat_completion(system_prompt: "s", user_prompt: "u")).to eq("openai-out")
25
+ end
26
+
27
+ it "delegates to the Anthropic provider when configured" do
28
+ cfg = Queryclerk::Configuration.new.tap do |c|
29
+ c.api_key = "k"
30
+ c.provider = :anthropic
31
+ end
32
+ conn = stub_connection(
33
+ cfg.api_base_url, "/v1/messages",
34
+ { "content" => [{ "type" => "text", "text" => "anthropic-out" }] }
35
+ )
36
+
37
+ client = described_class.new(configuration: cfg, connection: conn)
38
+
39
+ expect(client.chat_completion(system_prompt: "s", user_prompt: "u")).to eq("anthropic-out")
40
+ end
41
+
42
+ it "raises ConfigurationError when the API key is missing" do
43
+ cfg = Queryclerk::Configuration.new
44
+
45
+ expect { described_class.new(configuration: cfg) }
46
+ .to raise_error(Queryclerk::ConfigurationError, /Missing API key/)
47
+ end
48
+ end