Spaces:
Running
Running
File size: 1,448 Bytes
557ee65 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | from typing import Any, Dict, List
def compact_raw_context(
raw_context: Dict[str, Any], max_elements: int = 25, max_string_len: int = 2000
) -> Dict[str, Any]:
"""
Compact raw context to keep the LLM prompt size bounded.
Slices large lists and truncates long strings.
"""
compacted = {}
for key, value in raw_context.items():
if isinstance(value, list):
count = len(value)
if count > max_elements * 2:
# Keep first N and last N
trimmed = value[:max_elements] + value[-max_elements:]
compacted[f"{key}_trimmed"] = trimmed
compacted[f"{key}_count"] = count
# Basic stats for numeric lists
numeric_values = [v for v in value if isinstance(v, (int, float))]
if numeric_values:
compacted[f"{key}_min"] = min(numeric_values)
compacted[f"{key}_max"] = max(numeric_values)
else:
compacted[key] = value
elif isinstance(value, str):
if len(value) > max_string_len:
compacted[key] = value[:max_string_len] + "... [truncated]"
else:
compacted[key] = value
elif isinstance(value, dict):
compacted[key] = compact_raw_context(value, max_elements, max_string_len)
else:
compacted[key] = value
return compacted
|