Module: N2B::MessageUtils
- Defined in:
- lib/n2b/message_utils.rb
Constant Summary collapse
- MAX_MESSAGE_LENGTH =
500
- TRUNCATION_NOTICE =
"... (truncated)"
Class Method Summary collapse
-
.log_message(message, level = :info) ⇒ Object
Logs the message to STDOUT.
-
.sanitize_message(message_str) ⇒ Object
Performs basic sanitization on the message.
-
.validate_message(message_str) ⇒ Object
Validates the message length.
Class Method Details
.log_message(message, level = :info) ⇒ Object
Logs the message to STDOUT. level can be :info, :debug, :warn, :error
45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/n2b/message_utils.rb', line 45 def self.(, level = :info) return if .nil? || .strip.empty? prefix = case level when :debug then "[N2B Message DEBUG]" when :warn then "[N2B Message WARN]" when :error then "[N2B Message ERROR]" else "[N2B Message INFO]" # Default to info end output_stream = (level == :error || level == :warn) ? $stderr : $stdout output_stream.puts "#{prefix} #{}" end |
.sanitize_message(message_str) ⇒ Object
Performs basic sanitization on the message.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/n2b/message_utils.rb', line 19 def self.() return nil if .nil? = String() # Ensure it's a string # Strip leading/trailing whitespace sanitized = .strip # Replace triple backticks with single backticks to prevent code block formatting issues in prompts sanitized.gsub!('```', '`') # Remove multiple consecutive newlines, leaving only single newlines # This helps prevent prompt injection or excessive spacing. sanitized.gsub!(/\n{2,}/, "\n") # Example: Escape specific control characters if needed, e.g., null bytes # sanitized.gsub!(/\x00/, '') # Remove null bytes # Add more sanitization rules here as needed, e.g.: # - Removing or escaping other characters that might break formatting or cause security issues. # - For now, keeping it relatively simple. sanitized end |
.validate_message(message_str) ⇒ Object
Validates the message length. Truncates if it exceeds MAX_MESSAGE_LENGTH.
8 9 10 11 12 13 14 15 16 |
# File 'lib/n2b/message_utils.rb', line 8 def self.() return nil if .nil? # Ensure message is a string before calling length = String() if .length > MAX_MESSAGE_LENGTH return [0...(MAX_MESSAGE_LENGTH - TRUNCATION_NOTICE.length)] + TRUNCATION_NOTICE end end |