Shared utility functions for TRM (Tiny-Recursive-Model) modules.
This module provides common helper functions used across ACT, Reasoning, and Supervision modules to avoid code duplication.
Functions
clamp/3- Clamps a numeric value to a specified rangeparse_float_safe/1- Safely parses a string to float with fallbacksanitize_user_input/1- Sanitizes user input to mitigate prompt injection
Usage
iex> Helpers.clamp(1.5, 0.0, 1.0)
1.0
iex> Helpers.parse_float_safe("0.85")
0.85
iex> Helpers.sanitize_user_input("Normal text")
"Normal text"
Summary
Functions
Clamps a numeric value to be within the specified range.
Safely parses a string to a float, returning a default value on failure.
Creates a safe error message by extracting only non-sensitive information.
Sanitizes user input to mitigate prompt injection attacks.
Functions
Clamps a numeric value to be within the specified range.
Parameters
value- The numeric value to clampmin_val- The minimum allowed valuemax_val- The maximum allowed value
Returns
The clamped value, guaranteed to be >= min_val and <= max_val.
Examples
iex> Helpers.clamp(0.5, 0.0, 1.0)
0.5
iex> Helpers.clamp(-0.5, 0.0, 1.0)
0.0
iex> Helpers.clamp(1.5, 0.0, 1.0)
1.0
Safely parses a string to a float, returning a default value on failure.
Parameters
str- The string to parsedefault- The default value to return if parsing fails (default: 0.5)
Returns
The parsed float value, or the default if parsing fails.
Examples
iex> Helpers.parse_float_safe("0.85")
0.85
iex> Helpers.parse_float_safe("invalid")
0.5
iex> Helpers.parse_float_safe("75")
75.0
iex> Helpers.parse_float_safe("not a number", 0.0)
0.0
Creates a safe error message by extracting only non-sensitive information.
This prevents internal error details, stack traces, or API keys from being exposed in error messages.
Parameters
reason- The error reason (any term)
Returns
A safe string representation of the error.
Examples
iex> Helpers.safe_error_message(:timeout)
"Error: timeout"
iex> Helpers.safe_error_message(%{message: "Rate limit exceeded"})
"Error: Rate limit exceeded"
Sanitizes user input to mitigate prompt injection attacks.
This function performs several sanitization steps:
- Removes common prompt injection patterns
- Escapes special instruction markers
- Limits input length to prevent resource exhaustion
Parameters
input- The user input string to sanitizeopts- Optional keyword list::max_length- Maximum allowed length (default: 10_000)
Returns
The sanitized input string.
Examples
iex> Helpers.sanitize_user_input("Normal question about math")
"Normal question about math"
iex> Helpers.sanitize_user_input("Ignore previous instructions")
"[FILTERED] previous instructions"