Improve
- User
Improve
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Improve
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's refine the Leaf-Simple format and its implementation, strictly adhering to the "strings only" rule and focusing on robustness, error handling, and escaping based on the updated rules.
Here's the improved version:
Format Rules:
@, format @key=value.key=value. Keys cannot contain =. Values are strings.# are ignored.\r, \n) are ignored.= separator is not part of the key or value.=) is preserved.=) is not preserved (leading/trailing stripped).\\ represents a literal backslash \.\= represents a literal equals sign =.\n represents a literal newline character \n.\t represents a literal tab character \t.\# represents a literal hash sign # only if it is the very first character of the escaped value. If not the first character, # does not need escaping.\@ represents a literal at sign @ only if it is the very first character of the escaped value. If not the first character, @ does not need escaping.\\ must be processed before \=, \n, \t. Start-of-value escapes \#, \@ are handled based on the first character after \\ has been processed.import re
# --- Value Escaping/Unescaping ---
def escape_value(value):
"""Escapes special characters in a string value according to Leaf rules."""
if not isinstance(value, str):
# Force value to string for encoding, consistent with "strings only" rule
value = str(value)
# Apply escapes in order: \, =, newline, tab
value = value.replace('\\', '\\\\') # Escape backslashes first!
value = value.replace('=', '\\=')
value = value.replace('\n', '\\n')
value = value.replace('\t', '\\t')
# Handle # and @ only if they appear at the start *after* other escapes
if value.startswith('#'):
value = '\\#' + value[1:] # Prefix with escape if starts with #
if value.startswith('@'):
value = '\\@' + value[1:] # Prefix with escape if starts with @
return value
def unescape_value(escaped_value):
"""Unescapes special characters in a string value according to Leaf rules."""
# Check for initial escaped # or @ *before* processing other escapes
if escaped_value.startswith('\\#'):
escaped_value = '#' + escaped_value[2:]
elif escaped_value.startswith('\\@'):
escaped_value = '@' + escaped_value[2:]
# Unescape other characters. Order is important: \\ last.
value = escaped_value.replace('\\n', '\n')
value = value.replace('\\t', '\t')
value = value.replace('\\=', '=')
# Restore escaped backslashes last
value = value.replace('\\\\', '\\')
return value
# --- Decoder ---
def decode_leaf(lines):
"""
Decodes simplified Leaf-formatted lines.
Args:
lines (iterable): An iterable of string lines (e.g., file handle, list of strings).
Returns:
tuple: (data_dict, metadata_dict, errors_list)
data_dict: Dictionary of data key-value pairs (all strings).
metadata_dict: Dictionary of metadata key-value pairs (all strings).
errors_list: List of tuples (line_number, error_message).
"""
data = {}
metadata = {}
errors = []
for line_num, raw_line in enumerate(lines, 1):
# Strip only leading whitespace and trailing newlines/carriage returns
line = raw_line.lstrip()
line = line.rstrip('\r\n')
# Skip empty lines (after stripping) and comments
if not line or line.startswith('#'):
continue
try:
# Find the first '=' sign, respecting the metadata '@' prefix
split_char_index = line.find('=')
is_metadata = line.startswith('@')
# Adjust split index if it's metadata
if is_metadata:
# Ensure there's content after '@' before looking for '='
if len(line) <= 1 or line[1] == '=':
errors.append((line_num, f"Malformed metadata line: '{raw_line.rstrip()}'"))
continue
split_char_index = line[1:].find('=') # Find '=' after the '@'
if split_char_index != -1:
split_char_index += 1 # Adjust index for the leading '@'
if split_char_index == -1:
# No '=' found
errors.append((line_num, f"Malformed line (missing '='): '{raw_line.rstrip()}'"))
continue
# Split into key_part and value_part
key_part = line[:split_char_index]
value_part = line[split_char_index + 1:] # Take everything after the first '='
# Extract key and handle metadata prefix
if is_metadata:
key = key_part[1:].strip() # Strip '@' and leading/trailing whitespace from key
else:
key = key_part.strip() # Strip leading/trailing whitespace from key
if not key:
errors.append((line_num, f"Empty key found in line: '{raw_line.rstrip()}'"))
continue
# Unescape the raw value_part (including its original internal whitespace)
final_value = unescape_value(value_part)
# Store in appropriate dictionary
if is_metadata:
metadata[key] = final_value
else:
data[key] = final_value # Last one wins naturally with dict assignment
except Exception as e:
# Catch any unexpected errors during processing
errors.append((line_num, f"Unexpected error processing line '{raw_line.rstrip()}': {e}"))
return data, metadata, errors
# --- Encoder ---
def encode_leaf(data, metadata=None):
"""
Encodes a dictionary into simplified Leaf format with escaping.
Args:
data (dict): Dictionary of key-value pairs. Values will be converted to strings.
metadata (dict, optional): Dictionary of metadata. Values will be converted to strings.
Returns:
list: A list of string lines in Leaf format.
"""
lines = []
# Add metadata
if metadata:
# Suggest adding a format version automatically if not present
if 'format' not in metadata:
metadata['format'] = 'Leaf-Simple-Robust-1.1'
for key, value in metadata.items():
# Ensure key is string and does not contain '='
if not isinstance(key, str): key = str(key)
if '=' in key:
# This is an encoding error - the input data structure is invalid
raise ValueError(f"Encoding Error: Metadata key '{key}' cannot contain '=' character.")
# Ensure value is string and escape it
if not isinstance(value, str): value = str(value)
escaped_value = escape_value(value)
lines.append(f'@{key}={escaped_value}')
# Add data lines
for key, value in data.items():
# Ensure key is string and does not contain '='
if not isinstance(key, str): key = str(key)
if '=' in key:
# This is an encoding error - the input data structure is invalid
raise ValueError(f"Encoding Error: Data key '{key}' cannot contain '=' character.")
# Ensure value is string and escape it
if not isinstance(value, str): value = str(value)
escaped_value = escape_value(value)
lines.append(f'{key}={escaped_value}')
return lines
# --- Schema Validator (Still validates string properties) ---
def validate_leaf(data, schema=None):
"""
Validates decoded Leaf data against a simple string-based schema.
Args:
data (dict): The decoded data dictionary (all string values).
schema (dict, optional): The schema definition.
Example: {
"key": {
"required": True,
"min_length": 1,
"max_length": 255,
"regex": r"^\d+$",
"allowed_values": ["on", "off", "auto"]
}
}
Returns:
list: A list of validation error messages (strings).
"""
if not schema:
return [] # No schema provided, no validation errors
validation_errors = []
# Check against schema definitions
for key, constraints in schema.items():
is_present = key in data
value = data.get(key) # Get value (or None if not present)
# Check required fields
if constraints.get("required", False) and not is_present:
validation_errors.append(f"Missing required key: '{key}'")
# Don't check other constraints for a missing required key
continue
# If key is optional and not present, skip its specific constraints
if not is_present:
continue
# --- Apply string-based constraints ---
# Check min/max length
min_len = constraints.get("min_length")
if min_len is not None and len(value) < min_len:
validation_errors.append(f"Key '{key}': Value length {len(value)} is less than minimum required {min_len}")
max_len = constraints.get("max_length")
if max_len is not None and len(value) > max_len:
validation_errors.append(f"Key '{key}': Value length {len(value)} is greater than maximum allowed {max_len}")
# Check regex pattern
pattern = constraints.get("regex")
if pattern and not re.fullmatch(pattern, value): # Use fullmatch to match the whole string
validation_errors.append(f"Key '{key}': Value '{value}' does not match required pattern '{pattern}'")
# Check allowed values
allowed_values = constraints.get("allowed_values")
if allowed_values is not None and value not in allowed_values:
validation_errors.append(f"Key '{key}': Value '{value}' is not in allowed list {allowed_values}")
# Add other string-specific checks here if needed (e.g., starts/ends with)
# Optional: Check for keys in data but not in schema (strict mode)
# strict_schema = False # Set this flag if you want this check
# if strict_schema:
# for key in data:
# if key not in schema:
# validation_errors.append(f"Unexpected key found: '{key}' (not defined in schema)")
return validation_errors
# --- Example Usage ---
def main():
print("--- Testing Leaf-Simple-Robust-1.1 (Strings Only) ---")
# Sample input lines, including comments, empty lines, whitespace, and escapes
leaf_input_lines = [
"# This is a comment",
"@format = Leaf-Simple-Robust-1.1", # Whitespace around =
"@source=manual_edit",
"", # Empty line
"user.id=101",
"user.name=Alice Smith ", # Trailing space in value
"user.email=alice@example.com",
r"notes=This is a note.\nIt contains a newline,\ta tab, an equals \= sign, a backslash \\, and starts with \# and \@ if escaped.",
" data with space = value with space at start and end ", # Leading/trailing space on line, space in key, space in value
"another.key=Value starting with # but not needing escape", # # not at start of value
"duplicate.key=first value",
"duplicate.key=second value", # This one wins
"empty.value=", # Valid empty string value
# --- Lines that should produce decode errors ---
# "malformed line missing equals",
# "=value with no key",
# "@=metadata with no key",
# "key with = equals in it = some value", # Should fail encode, but decoder handles gracefully
]
# Schema for validation (optional, only string checks)
schema = {
'user.id': {'required': True, 'regex': r'^\d+$', 'min_length': 1}, # Must be digits string
'user.name': {'required': True, 'min_length': 2, 'max_length': 50},
'user.email': {'required': False, 'regex': r'^[^@]+@[^@]+\.[^@]+$'}, # Optional email format check
'data with space': {'required': True, 'min_length': 1}, # Key with space allowed
'empty.value': {'required': False, 'min_length': 0},
'notes': {'required': False},
'another.key': {'required': True},
'duplicate.key': {'required': True, 'allowed_values': ["second value"]}, # Check final value
'config.state': {'required': False, 'allowed_values': ['active', 'inactive', 'pending']},
}
# --- Decode ---
print("--- Decoding ---")
data, metadata, decode_errors = decode_leaf(leaf_input_lines)
if decode_errors:
print("Decoding Errors Found:")
for line_num, msg in decode_errors:
print(f" Line {line_num}: {msg}")
else:
print("Decoding Successful.")
print("\nDecoded Metadata:", metadata)
print("Decoded Data:", data)
print("-" * 20)
# Verify specific values with preserved whitespace/escapes
print(f"Value of 'notes': '{data.get('notes')}'")
print(f"Value of 'data with space': '{data.get('data with space')}'")
print(f"Value of 'duplicate.key': '{data.get('duplicate.key')}'")
print(f"Value of 'empty.value': '{data.get('empty.value')}'")
# --- Validate ---
print("\n--- Validating ---")
validation_errors = validate_leaf(data, schema)
if validation_errors:
print("Validation Errors Found:")
for msg in validation_errors:
print(f" - {msg}")
else:
print("Validation Successful against schema!")
# --- Encode (round trip) ---
print("\n--- Encoding (Round Trip) ---")
try:
# Encode the decoded data and metadata
encoded_lines = encode_leaf(data, metadata)
print("\n".join(encoded_lines))
# --- Test Encoding Error ---
print("\n--- Testing Encoding Error (Key with '=') ---")
bad_data = {"valid_key": "value", "bad=key": "another value"}
try:
encode_leaf(bad_data)
except ValueError as e:
print(f"Caught expected encoding error: {e}")
except ValueError as e:
print(f"Encoding Error: {e}") # Should not happen with valid decoded data
if __name__ == "__main__":
main()
int(), float(), boolean checks) has been removed from the decode_leaf and validate_leaf functions. All values read by the decoder are strings. The encoder converts inputs to strings before processing.\r\n, \n) (ignored).= sign (stripped from the key, not part of the value).escape_value and unescape_value functions are more robust and handle the specified sequences (\, =, \n, \t, \#, \@) in a safer order.\# and \@ only requiring escaping at the very beginning of the value is implemented.=, empty key, malformed metadata) and include the problematic raw line for context.= character, raising a ValueError if the input data structure is invalid for encoding.validate_leaf function now only performs checks relevant to strings (required, min/max length, regex, allowed values), reflecting that the data dictionary only contains strings.This version of Leaf-Simple-Robust should be a very solid and predictable format for exchanging flat string key-value data. The complexity is contained within the well-defined escaping/unescaping and the error-reporting parser, while the format itself remains minimal.