Class: Scrubber::LLMGuard

Inherits:
Object
  • Object
show all
Defined in:
lib/scrubber/llm_guard.rb,
sig/scrubber_rb.rbs

Overview

Redacts prompts before they reach a model API.

Constant Summary collapse

CONTENT_KEYS =

Message hash keys whose values are prompt text.

Returns:

  • (Array[String])
%w[content text prompt input].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scrubber: nil, replacement: :hash, **options) ⇒ LLMGuard

Returns a new instance of LLMGuard.

Parameters:

  • scrubber: (Instance, nil) (defaults to: nil)
  • replacement: (replacement) (defaults to: :hash)
  • (Object)


30
31
32
# File 'lib/scrubber/llm_guard.rb', line 30

def initialize(scrubber: nil, replacement: :hash, **options)
  @scrubber = scrubber || Scrubber.new(replacement: replacement, **options)
end

Instance Attribute Details

#scrubberInstance (readonly)

Returns the value of attribute scrubber.

Returns:



28
29
30
# File 'lib/scrubber/llm_guard.rb', line 28

def scrubber
  @scrubber
end

Instance Method Details

#call(input) ⇒ Object Also known as: scrub

Redact input, preserving its shape.

Parameters:

  • (Object)

Returns:

  • (Object)


35
36
37
38
39
40
41
42
43
44
# File 'lib/scrubber/llm_guard.rb', line 35

def call(input)
  case input
  when String then @scrubber.scrub(input)
  when Array  then input.map { |item| call(item) }
  when Hash   then scrub_hash(input)
  when Symbol, Numeric, NilClass, TrueClass, FalseClass then input
  else
    input.respond_to?(:to_str) ? @scrubber.scrub(input.to_str) : input
  end
end

#findings(input) ⇒ Array[Match]

What would have been redacted. Handy for a "we blocked N leaks today" metric, or for failing a test when a prompt builder regresses.

Parameters:

  • (Object)

Returns:



54
55
56
57
58
59
60
61
# File 'lib/scrubber/llm_guard.rb', line 54

def findings(input)
  case input
  when String then @scrubber.detect(input)
  when Array  then input.flat_map { |item| findings(item) }
  when Hash   then content_values(input).flat_map { |v| findings(v) }
  else []
  end
end

#to_procProc

Usable directly as a block: messages.map(&guard).

Returns:

  • (Proc)


48
49
50
# File 'lib/scrubber/llm_guard.rb', line 48

def to_proc
  method(:call).to_proc
end