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