9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
# File 'lib/legion/guardrails.rb', line 9
def check(input, safe_embeddings:, threshold: 0.3)
unless defined?(Legion::LLM) && Legion::LLM.respond_to?(:embed) && Legion::LLM.respond_to?(:started?) && Legion::LLM.started?
return { safe: true,
reason: 'no embeddings service' }
end
input_vec = Legion::LLM.embed(input)
return { safe: true, reason: 'embedding failed' } unless input_vec
min_dist = safe_embeddings.map { |se| cosine_distance(input_vec, se) }.min || 1.0
safe = min_dist <= threshold
if !safe && defined?(Legion::Logging)
Legion::Logging.warn "[Guardrails] EmbeddingSimilarity rejected input: distance=#{min_dist.round(4)} threshold=#{threshold}"
end
{ safe: safe, distance: min_dist.round(4), threshold: threshold }
rescue StandardError
{ safe: true, reason: 'embedding failed' }
end
|