File size: 11,663 Bytes
22087d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
"""
JSON helper utilities for handling both legacy (string) and new (dict/list) formats.

These utilities help with the transition from storing JSON as strings to storing
them as proper JSONB objects in the database.
"""

import json
import re
import logging
from typing import Any, Union, Dict, List, Tuple

# Use orjson for hot paths (3-5x faster than stdlib json)
try:
    import orjson
    _HAS_ORJSON = True
except ImportError:
    _HAS_ORJSON = False

logger = logging.getLogger(__name__)


def repair_json(json_string: str) -> Tuple[str, bool]:
    """
    Attempt to repair malformed JSON that LLMs sometimes produce.
    
    Common LLM JSON mistakes this handles:
    - Missing closing brackets/braces (e.g., `[{"a": 1}, {"b": 2]` -> `[{"a": 1}, {"b": 2}]`)
    - Trailing commas (e.g., `[1, 2, 3,]` -> `[1, 2, 3]`)
    - Missing commas between array elements (e.g., `[{"a":1} {"b":2}]` -> `[{"a":1}, {"b":2}]`)
    
    Args:
        json_string: The potentially malformed JSON string
        
    Returns:
        Tuple of (repaired_string, was_repaired)
    """
    if not isinstance(json_string, str):
        return json_string, False
    
    original = json_string
    repaired = json_string.strip()
    was_repaired = False
    
    # First, try parsing as-is
    try:
        json.loads(repaired)
        return repaired, False
    except json.JSONDecodeError:
        pass
    
    # Fix 1: Remove trailing commas before ] or }
    # Pattern: comma followed by optional whitespace, then ] or }
    trailing_comma_pattern = r',(\s*[\]\}])'
    if re.search(trailing_comma_pattern, repaired):
        repaired = re.sub(trailing_comma_pattern, r'\1', repaired)
        was_repaired = True
    
    # Fix 2: Add missing commas between array elements or object properties
    # Pattern: } followed by optional whitespace, then { (missing comma)
    missing_comma_pattern = r'\}(\s*)\{'
    if re.search(missing_comma_pattern, repaired):
        repaired = re.sub(missing_comma_pattern, r'},\1{', repaired)
        was_repaired = True
    
    # Pattern: ] followed by optional whitespace, then [ (missing comma between arrays)
    missing_comma_array_pattern = r'\](\s*)\['
    if re.search(missing_comma_array_pattern, repaired):
        repaired = re.sub(missing_comma_array_pattern, r'],\1[', repaired)
        was_repaired = True
    
    # Fix 3: Balance brackets/braces - count and add missing ones
    # This handles the specific case: `[{...}, {...], {...]` -> `[{...}, {...}]`
    open_braces = repaired.count('{')
    close_braces = repaired.count('}')
    open_brackets = repaired.count('[')
    close_brackets = repaired.count(']')
    
    # Add missing closing braces
    if open_braces > close_braces:
        # Find position to insert - look for patterns like `], {` that should be `}], {`
        # or at the end of the string
        missing_braces = open_braces - close_braces
        
        # Try to find where braces are missing by checking for ], or ] at end
        # Common pattern: `["task1", "task2"], {` should be `["task1", "task2"]}, {`
        # Look for `],` or `]` followed by `,` or `}` or end - missing `}` before
        fixed = False
        for i in range(len(repaired) - 1, 0, -1):
            if repaired[i] == ']':
                # Check if there's a missing } before this ]
                # Count braces up to this point
                temp_open = repaired[:i+1].count('{')
                temp_close = repaired[:i+1].count('}')
                if temp_open > temp_close:
                    # Insert missing }s before the ]
                    needed = temp_open - temp_close
                    repaired = repaired[:i] + '}' * needed + repaired[i:]
                    was_repaired = True
                    fixed = True
                    break
        
        if not fixed:
            # Just append at end
            repaired = repaired + '}' * missing_braces
            was_repaired = True
    
    # Add missing closing brackets
    if open_brackets > close_brackets:
        missing_brackets = open_brackets - close_brackets
        repaired = repaired + ']' * missing_brackets
        was_repaired = True
    
    # Validate the repair worked
    try:
        json.loads(repaired)
        if was_repaired:
            logger.info(f"🔧 [JSON REPAIR] Successfully repaired malformed JSON")
            logger.debug(f"🔧 [JSON REPAIR] Original (first 200 chars): {original[:200]}")
            logger.debug(f"🔧 [JSON REPAIR] Repaired (first 200 chars): {repaired[:200]}")
        return repaired, was_repaired
    except json.JSONDecodeError as e:
        # Repair failed, return original
        logger.debug(f"🔧 [JSON REPAIR] Repair attempt failed: {e}")
        return original, False


def safe_json_parse_with_repair(value: Union[str, Dict, List, Any], default: Any = None) -> Any:
    """
    Safely parse JSON with automatic repair of common LLM mistakes.
    
    This is an enhanced version of safe_json_parse that attempts to repair
    malformed JSON before giving up.
    
    Args:
        value: The value to parse
        default: Default value if parsing fails
        
    Returns:
        Parsed value or default
    """
    if value is None:
        return default
        
    # If it's already a dict or list, return as-is
    if isinstance(value, (dict, list)):
        return value
        
    # If it's a string, try to parse it
    if isinstance(value, str):
        # First, try normal parsing
        try:
            return json.loads(value)
        except json.JSONDecodeError:
            pass
        
        # Try repair
        repaired, was_repaired = repair_json(value)
        if was_repaired:
            try:
                return json.loads(repaired)
            except json.JSONDecodeError:
                pass
        
        # If repair didn't work, return the string itself or default
        return value if default is None else default
            
    # For any other type, return as-is
    return value


def ensure_dict(value: Union[str, Dict[str, Any], None], default: Dict[str, Any] = None) -> Dict[str, Any]:
    """
    Ensure a value is a dictionary.
    
    Handles:
    - None -> returns default or {}
    - Dict -> returns as-is
    - JSON string -> parses and returns dict
    - Other -> returns default or {}
    
    Args:
        value: The value to ensure is a dict
        default: Default value if conversion fails
        
    Returns:
        A dictionary
    """
    if default is None:
        default = {}
        
    if value is None:
        return default
        
    if isinstance(value, dict):
        return value
        
    if isinstance(value, str):
        try:
            parsed = json.loads(value)
            if isinstance(parsed, dict):
                return parsed
            return default
        except (json.JSONDecodeError, TypeError):
            return default
            
    return default


def ensure_list(value: Union[str, List[Any], None], default: List[Any] = None) -> List[Any]:
    """
    Ensure a value is a list.
    
    Handles:
    - None -> returns default or []
    - List -> returns as-is
    - JSON string -> parses and returns list
    - Other -> returns default or []
    
    Args:
        value: The value to ensure is a list
        default: Default value if conversion fails
        
    Returns:
        A list
    """
    if default is None:
        default = []
        
    if value is None:
        return default
        
    if isinstance(value, list):
        return value
        
    if isinstance(value, str):
        try:
            parsed = json.loads(value)
            if isinstance(parsed, list):
                return parsed
            return default
        except (json.JSONDecodeError, TypeError):
            return default
            
    return default


def safe_json_parse(value: Union[str, Dict, List, Any], default: Any = None) -> Any:
    """
    Safely parse a value that might be JSON string or already parsed.
    
    This handles the transition period where some data might be stored as
    JSON strings (old format) and some as proper objects (new format).
    
    Args:
        value: The value to parse
        default: Default value if parsing fails
        
    Returns:
        Parsed value or default
    """
    if value is None:
        return default
        
    # If it's already a dict or list, return as-is
    if isinstance(value, (dict, list)):
        return value
        
    # If it's a string, try to parse it
    if isinstance(value, str):
        try:
            return json.loads(value)
        except (json.JSONDecodeError, TypeError):
            # If it's not valid JSON, return the string itself
            return value
            
    # For any other type, return as-is
    return value


def to_json_string(value: Any) -> str:
    """
    Convert a value to a JSON string if needed.
    
    This is used for backwards compatibility when yielding data that
    expects JSON strings.
    
    Uses ensure_ascii=False to preserve Unicode characters without escaping,
    preventing double-escaping issues when JSON strings are nested.
    
    Args:
        value: The value to convert
        
    Returns:
        JSON string representation
    """
    if isinstance(value, str):
        # If it's already a string, check if it's valid JSON
        try:
            json.loads(value)
            return value  # It's already a JSON string
        except (json.JSONDecodeError, TypeError):
            # It's a plain string, encode it as JSON
            return json.dumps(value, ensure_ascii=False)
    
    # For all other types, convert to JSON
    return json.dumps(value, ensure_ascii=False)


def to_json_string_fast(value: Any) -> str:
    """
    Fast path for converting to JSON string - no validation.
    
    Use this when you KNOW the value is a dict/list that needs serialization.
    This is optimized for the streaming hot path where we serialize every chunk.
    
    Uses orjson when available (3-5x faster than stdlib json) for hot paths.
    Falls back to stdlib json if orjson is not available.
    
    Args:
        value: The value to convert (must be JSON-serializable)
        
    Returns:
        JSON string representation
    """
    if _HAS_ORJSON:
        # orjson is 3-5x faster and handles Unicode correctly by default
        return orjson.dumps(value).decode('utf-8')
    else:
        # Fallback to stdlib json with compact format
        return json.dumps(value, separators=(',', ':'), ensure_ascii=False)


def format_for_yield(message_object: Dict[str, Any]) -> Dict[str, Any]:
    """
    Format a message object for yielding, ensuring content and metadata are JSON strings.
    
    This maintains backward compatibility with clients expecting JSON strings
    while the database now stores proper objects.
    
    Args:
        message_object: The message object from the database
        
    Returns:
        Message object with content and metadata as JSON strings
    """
    if not message_object:
        return message_object
        
    # Create a copy to avoid modifying the original
    formatted = message_object.copy()
    
    # Ensure content is a JSON string
    if 'content' in formatted and not isinstance(formatted['content'], str):
        formatted['content'] = json.dumps(formatted['content'])
        
    # Ensure metadata is a JSON string
    if 'metadata' in formatted and not isinstance(formatted['metadata'], str):
        formatted['metadata'] = json.dumps(formatted['metadata'])
        
    return formatted