Attempts to repair a broken JSON string. Args: broken_json: The broken JSON text. error_message: The error message from parsing. Returns: A repaired JSON dictionary, or None on failure.
(broken_json: str, error_message: str)
| 707 | raise Exception(f"Failed to generate initial {format_name}: {error_msg}") |
| 708 | |
| 709 | def repair_json(broken_json: str, error_message: str) -> Optional[Dict]: |
| 710 | """ |
| 711 | Attempts to repair a broken JSON string. |
| 712 | |
| 713 | Args: |
| 714 | broken_json: The broken JSON text. |
| 715 | error_message: The error message from parsing. |
| 716 | |
| 717 | Returns: |
| 718 | A repaired JSON dictionary, or None on failure. |
| 719 | """ |
| 720 | prompt = f""" |
| 721 | You are a JSON syntax repair expert. The following text was intended to be a JSON object, but it has syntax errors. Please fix it. |
| 722 | |
| 723 | **Error message:** |
| 724 | {error_message} |
| 725 | |
| 726 | **Broken JSON text:** |
| 727 | ``` |
| 728 | {broken_json} |
| 729 | ``` |
| 730 | |
| 731 | **Instructions:** |
| 732 | 1. Analyze the error and the text to locate the syntax issue. |
| 733 | 2. Correct the syntax. Common issues are missing quotes, unescaped characters, or trailing commas. |
| 734 | 3. Return **ONLY** the corrected, valid JSON object, without any additional explanations or surrounding text. |
| 735 | """ |
| 736 | for attempt in range(CONFIG['MAX_REPAIR_RETRIES']): |
| 737 | print(f"Attempting to repair JSON (Attempt {attempt + 1}/{CONFIG['MAX_REPAIR_RETRIES']})...") |
| 738 | try: |
| 739 | response = call_google_genai_multimodal([prompt]) |
| 740 | if response is None: |
| 741 | continue |
| 742 | |
| 743 | fixed_json_match = re.search(r'\{.*\}', response, re.DOTALL) |
| 744 | if not fixed_json_match: |
| 745 | continue |
| 746 | |
| 747 | fixed_json_str = fixed_json_match.group(0) |
| 748 | return json.loads(fixed_json_str) |
| 749 | |
| 750 | except json.JSONDecodeError as e: |
| 751 | error_message = str(e) |
| 752 | print(f"Repaired JSON is still invalid: {error_message}") |
| 753 | except Exception as e: |
| 754 | print(f"Error calling LLM for JSON repair: {e}") |
| 755 | |
| 756 | print("Reached max retries, JSON repair failed.") |
| 757 | return None |
| 758 | |
| 759 | def repair_svg(svg_code: str, error_message: str) -> Optional[str]: |
| 760 | """ |
nothing calls this directly
no test coverage detected