Class: Riffer::Guardrails::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/riffer/guardrails/runner.rb

Overview

Executes guardrails sequentially, passing each one’s output to the next; if any blocks, execution stops and a tripwire is returned.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(guardrail_configs, phase:, context: nil) ⇒ Runner

– : (Array[Hash[Symbol, untyped]], phase: Symbol, ?context: untyped) -> void



18
19
20
21
22
# File 'lib/riffer/guardrails/runner.rb', line 18

def initialize(guardrail_configs, phase:, context: nil)
  @guardrail_configs = guardrail_configs
  @phase = phase
  @context = context
end

Instance Attribute Details

#contextObject (readonly)

The context passed to guardrails.



14
15
16
# File 'lib/riffer/guardrails/runner.rb', line 14

def context
  @context
end

#guardrail_configsObject (readonly)

The guardrail configs to execute.



8
9
10
# File 'lib/riffer/guardrails/runner.rb', line 8

def guardrail_configs
  @guardrail_configs
end

#phaseObject (readonly)

The execution phase (:before or :after).



11
12
13
# File 'lib/riffer/guardrails/runner.rb', line 11

def phase
  @phase
end

Instance Method Details

#run(data, messages: nil) ⇒ Object

Runs the guardrails sequentially. For the :before phase data is the messages array; for :after it’s the response (and messages must be provided). – : (untyped, ?messages: Array?) -> [untyped, Riffer::Guardrails::Tripwire?, Array]



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/riffer/guardrails/runner.rb', line 29

def run(data, messages: nil)
  current_data = data
  modifications = [] #: Array[Riffer::Guardrails::Modification]

  guardrail_configs.each do |config|
    guardrail = instantiate_guardrail(config)
    result = execute_guardrail(guardrail, current_data, messages: messages)

    if result.block?
      tripwire = Riffer::Guardrails::Tripwire.new(
        reason: result.data,
        guardrail: guardrail.class,
        phase: phase,
        metadata: result.
      )
      return [current_data, tripwire, modifications]
    end

    if result.transform?
      modifications << Riffer::Guardrails::Modification.new(
        guardrail: guardrail.class,
        phase: phase,
        message_indices: detect_changed_indices(current_data, result.data)
      )
    end

    current_data = result.data
  end

  [current_data, nil, modifications]
end