Spaces:
Sleeping
Sleeping
File size: 583 Bytes
723bbe6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import re
import json
class JSONOutputParser:
"""
Handles code fences like ```json or ````json.
"""
CODE_BLOCK_REGEX = re.compile(r"^\s*`{3,4}json\s*|\s*`{3,4}\s*$" ,flags=re.DOTALL)
@staticmethod
def parse(llm_output: str) -> object:
cleaned = JSONOutputParser.CODE_BLOCK_REGEX.sub("", llm_output.strip())
cleaned = cleaned.strip()
try:
data = json.loads(cleaned)
except json.JSONDecodeError as e:
raise ValueError(f"Failed to decode JSON: {str(e)}\nRaw output:\n{llm_output}")
return data
|