Class: GuardrailsRuby::Guard
- Inherits:
-
Object
- Object
- GuardrailsRuby::Guard
- Defined in:
- lib/guardrails_ruby/guard.rb
Instance Method Summary collapse
-
#call(user_input, context: {}) ⇒ Object
Wrap an LLM call with input + output guards.
-
#check(name, **options) ⇒ Object
DSL: register a check by name with options.
-
#check_input(text) ⇒ Object
Run all input checks in order, return merged Result.
-
#check_output(input: nil, output:, context: {}) ⇒ Object
Run all output checks in order, return merged Result.
-
#initialize(&block) ⇒ Guard
constructor
A new instance of Guard.
-
#input(&block) ⇒ Object
DSL: define input checks.
-
#output(&block) ⇒ Object
DSL: define output checks.
Constructor Details
#initialize(&block) ⇒ Guard
Returns a new instance of Guard.
7 8 9 10 11 |
# File 'lib/guardrails_ruby/guard.rb', line 7 def initialize(&block) @input_checks = [] @output_checks = [] instance_eval(&block) if block end |
Instance Method Details
#call(user_input, context: {}) ⇒ Object
Wrap an LLM call with input + output guards
50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/guardrails_ruby/guard.rb', line 50 def call(user_input, context: {}) user_input = user_input.to_s if user_input.nil? input_result = check_input(user_input) handle_violations(input_result) sanitized_input = input_result.sanitized || user_input raw_output = yield(sanitized_input) output_result = check_output(input: sanitized_input, output: raw_output, context: context) handle_violations(output_result) output_result.sanitized || raw_output end |
#check(name, **options) ⇒ Object
DSL: register a check by name with options
28 29 30 31 32 33 34 35 36 |
# File 'lib/guardrails_ruby/guard.rb', line 28 def check(name, **) check_class = Check.lookup(name) raise ArgumentError, "Unknown check: #{name.inspect}" unless check_class target = @current_checks raise ArgumentError, "check must be called inside an input or output block" unless target target << check_class.new(**) end |
#check_input(text) ⇒ Object
Run all input checks in order, return merged Result
39 40 41 |
# File 'lib/guardrails_ruby/guard.rb', line 39 def check_input(text) run_checks(@input_checks, text) end |
#check_output(input: nil, output:, context: {}) ⇒ Object
Run all output checks in order, return merged Result
44 45 46 47 |
# File 'lib/guardrails_ruby/guard.rb', line 44 def check_output(input: nil, output:, context: {}) ctx = context.merge(input: input) run_checks(@output_checks, output, context: ctx) end |
#input(&block) ⇒ Object
DSL: define input checks
14 15 16 17 18 |
# File 'lib/guardrails_ruby/guard.rb', line 14 def input(&block) @current_checks = @input_checks instance_eval(&block) @current_checks = nil end |
#output(&block) ⇒ Object
DSL: define output checks
21 22 23 24 25 |
# File 'lib/guardrails_ruby/guard.rb', line 21 def output(&block) @current_checks = @output_checks instance_eval(&block) @current_checks = nil end |