| import re |
| import json |
| from typing import List, Dict, Any, Optional |
|
|
| def parse_llm_json_response_flexible(llm_output_string: str) -> Optional[List[Dict[str, Any]]]: |
| """ |
| Parses the JSON array from the LLM's output string. |
| It first attempts to find the JSON within a ```json ... ``` block |
| after "Output JSON:". If that fails, it searches the entire string |
| for the first valid JSON array of dictionaries. |
| |
| Args: |
| llm_output_string: The raw string output received from the LLM. |
| |
| Returns: |
| A Python list representing the parsed JSON array, or None if parsing fails |
| or the JSON block/list is not found in the expected format. |
| """ |
| if not isinstance(llm_output_string, str): |
| print("Input is not a string.") |
| return None |
|
|
| |
| |
| processed_string = llm_output_string.replace('{{', '{').replace('}}', '}') |
|
|
| |
| print("Attempting to parse from ```json ... ``` block after 'Output JSON:'") |
| |
| |
| pattern = r"Output JSON:.*?```json\s*\n(.*?)\n\s*```" |
| matches = re.finditer(pattern, processed_string, re.DOTALL) |
| |
| for match in matches: |
| json_content = match.group(1).strip() |
| if json_content: |
| try: |
| parsed_json = json.loads(json_content) |
| if isinstance(parsed_json, list) and all(isinstance(item, dict) for item in parsed_json): |
| print("Successfully parsed from ```json block.") |
| return parsed_json |
| else: |
| print(f"Parsed content from ```json block is not a list of dictionaries.") |
| except json.JSONDecodeError as e: |
| print(f"JSON parsing failed for ```json block content: {e}") |
| print(f"Attempted to parse string:\n---\n{json_content}\n---") |
| except Exception as e: |
| print(f"An unexpected error occurred during parsing ```json block content: {e}") |
|
|
| print("Could not find valid JSON in 'Output JSON:' and ```json ... ``` block structure.") |
|
|
| |
| print("Attempting to find the first valid JSON array in the entire string.") |
| |
| |
| return find_json_array_in_string(processed_string) |
|
|
|
|
| def find_json_array_in_string(text: str) -> Optional[List[Dict[str, Any]]]: |
| """ |
| Efficiently find and parse the first valid JSON array in a string. |
| |
| Args: |
| text: The string to search in. |
| |
| Returns: |
| The first valid JSON array found, or None if no valid array is found. |
| """ |
| i = 0 |
| while i < len(text): |
| |
| start = text.find('[', i) |
| if start == -1: |
| break |
| |
| |
| bracket_count = 0 |
| in_string = False |
| escape_next = False |
| end = start |
| |
| for j in range(start, len(text)): |
| char = text[j] |
| |
| |
| if not escape_next: |
| if char == '"' and not in_string: |
| in_string = True |
| elif char == '"' and in_string: |
| in_string = False |
| elif char == '\\' and in_string: |
| escape_next = True |
| continue |
| |
| |
| if not in_string: |
| if char == '[': |
| bracket_count += 1 |
| elif char == ']': |
| bracket_count -= 1 |
| |
| if bracket_count == 0: |
| end = j |
| break |
| else: |
| escape_next = False |
| |
| |
| if bracket_count == 0 and end > start: |
| candidate = text[start:end+1] |
| try: |
| parsed = json.loads(candidate) |
| |
| |
| if isinstance(parsed, list): |
| |
| if not parsed or all(isinstance(item, dict) for item in parsed): |
| print("Successfully parsed the first valid JSON array found.") |
| return parsed |
| else: |
| print("Found a JSON list, but its items are not all dictionaries. Continuing search.") |
| except json.JSONDecodeError: |
| |
| pass |
| except Exception as e: |
| print(f"Unexpected error during parsing: {e}") |
| |
| |
| i = start + 1 |
| |
| print("Failed to find and parse a valid JSON array in the expected format.") |
| return None |
|
|
|
|
| |
| if __name__ == "__main__": |
| |
| test1 = ''' |
| Some text here |
| Output JSON: |
| Here's the result: |
| ```json |
| [{"name": "Alice", "as": null}, {"name": "Bob", "age": 25}] |
| ``` |
| ''' |
| print(parse_llm_json_response_flexible(test1)) |
| |
| |
| test2 = ''' |
| Output JSON: |
| ```json |
| [{{"name": "Charlie", "age": 35}}, {{"name": "David", "age": 40}}] |
| ``` |
| ''' |
| print(parse_llm_json_response_flexible(test2)) |
| |
| |
| |