9
10
11
12
13
14
15
16
17
18
19
20
21
|
# File 'lib/legion/guardrails.rb', line 9
def check(input, safe_embeddings:, threshold: 0.3)
return { safe: true, reason: 'no embeddings service' } unless defined?(Legion::LLM) && Legion::LLM.respond_to?(:embed)
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 }
end
|