Class: Riffer::Guardrails::MaxLength
- Inherits:
-
Riffer::Guardrail
- Object
- Riffer::Guardrail
- Riffer::Guardrails::MaxLength
- Defined in:
- lib/riffer/guardrails/max_length.rb
Overview
A guardrail that blocks messages exceeding a maximum character length.
Demonstrates the guardrail pattern with a simple, practical use case.
guardrail :before, with: Riffer::Guardrails::MaxLength, max: 1000
guardrail :after, with: Riffer::Guardrails::MaxLength, max: 5000
Constant Summary collapse
- DEFAULT_MAX =
: Integer
10_000
Instance Attribute Summary collapse
-
#max ⇒ Object
readonly
The maximum allowed character length.
Instance Method Summary collapse
-
#initialize(max: DEFAULT_MAX) ⇒ MaxLength
constructor
Creates a new max length guardrail.
-
#process_input(messages, context:) ⇒ Object
Blocks if any user message exceeds the max length.
-
#process_output(response, messages:, context:) ⇒ Object
Blocks if response exceeds the max length.
Constructor Details
#initialize(max: DEFAULT_MAX) ⇒ MaxLength
Creates a new max length guardrail.
max - maximum allowed characters (default: 10_000).
: (?max: Integer) -> void
21 22 23 24 |
# File 'lib/riffer/guardrails/max_length.rb', line 21 def initialize(max: DEFAULT_MAX) super() @max = max end |
Instance Attribute Details
#max ⇒ Object (readonly)
The maximum allowed character length.
14 15 16 |
# File 'lib/riffer/guardrails/max_length.rb', line 14 def max @max end |
Instance Method Details
#process_input(messages, context:) ⇒ Object
Blocks if any user message exceeds the max length.
messages - the input messages. context - optional context.
: (Array, context: untyped) -> Riffer::Guardrails::Result
32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/riffer/guardrails/max_length.rb', line 32 def process_input(, context:) .each do |msg| next unless msg.respond_to?(:content) next if msg.content.nil? if msg.content.length > max return block( "Message exceeds maximum length of #{max} characters", metadata: {length: msg.content.length, max: max} ) end end pass() end |
#process_output(response, messages:, context:) ⇒ Object
Blocks if response exceeds the max length.
response - the LLM response. messages - the conversation messages. context - optional context.
: (Riffer::Messages::Assistant, messages: Array, context: untyped) -> Riffer::Guardrails::Result
54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/riffer/guardrails/max_length.rb', line 54 def process_output(response, messages:, context:) return pass(response) unless response.respond_to?(:content) return pass(response) if response.content.nil? if response.content.length > max block( "Response exceeds maximum length of #{max} characters", metadata: {length: response.content.length, max: max} ) else pass(response) end end |