| import json
|
| import re
|
|
|
|
|
| def _replace_new_line(match: re.Match[str]) -> str:
|
| value = match.group(2)
|
| value = re.sub(r"\n", r"\\n", value)
|
| value = re.sub(r"\r", r"\\r", value)
|
| value = re.sub(r"\t", r"\\t", value)
|
| value = re.sub(r'(?<!\\)"', r"\"", value)
|
|
|
| return match.group(1) + value + match.group(3)
|
|
|
| def _custom_parser(multiline_string: str) -> str:
|
| """
|
| The LLM response for `action_input` may be a multiline
|
| string containing unescaped newlines, tabs or quotes. This function
|
| replaces those characters with their escaped counterparts.
|
| (newlines in JSON must be double-escaped: `\\n`)
|
| """
|
| if isinstance(multiline_string, (bytes, bytearray)):
|
| multiline_string = multiline_string.decode()
|
|
|
| multiline_string = re.sub(
|
| r'("action_input"\:\s*")(.*?)(")',
|
| _replace_new_line,
|
| multiline_string,
|
| flags=re.DOTALL,
|
| )
|
|
|
| return multiline_string
|
|
|
| def parse_partial_json(s: str, *, strict: bool = False):
|
| """Parse a JSON string that may be missing closing braces.
|
|
|
| Args:
|
| s: The JSON string to parse.
|
| strict: Whether to use strict parsing. Defaults to False.
|
|
|
| Returns:
|
| The parsed JSON object as a Python dictionary.
|
| """
|
|
|
| try:
|
| return json.loads(s, strict=strict)
|
| except json.JSONDecodeError:
|
| pass
|
|
|
|
|
| new_s = ""
|
| stack = []
|
| is_inside_string = False
|
| escaped = False
|
|
|
|
|
| for char in s:
|
| if is_inside_string:
|
| if char == '"' and not escaped:
|
| is_inside_string = False
|
| elif char == "\n" and not escaped:
|
| char = "\\n"
|
| elif char == "\\":
|
| escaped = not escaped
|
| else:
|
| escaped = False
|
| else:
|
| if char == '"':
|
| is_inside_string = True
|
| escaped = False
|
| elif char == "{":
|
| stack.append("}")
|
| elif char == "[":
|
| stack.append("]")
|
| elif char == "}" or char == "]":
|
| if stack and stack[-1] == char:
|
| stack.pop()
|
| else:
|
|
|
| return None
|
|
|
|
|
| new_s += char
|
|
|
|
|
|
|
| if is_inside_string:
|
| new_s += '"'
|
|
|
|
|
| while new_s:
|
| final_s = new_s
|
|
|
|
|
|
|
| for closing_char in reversed(stack):
|
| final_s += closing_char
|
|
|
|
|
| try:
|
| return json.loads(final_s, strict=strict)
|
| except json.JSONDecodeError:
|
|
|
|
|
| new_s = new_s[:-1]
|
|
|
|
|
|
|
|
|
| return json.loads(s, strict=strict)
|
|
|
| def main(
|
| json_string: str
|
| ) -> dict:
|
| """
|
| Parse a JSON string from a Markdown string.
|
|
|
| Args:
|
| json_string: The Markdown string.
|
|
|
| Returns:
|
| The parsed JSON object as a Python dictionary.
|
| """
|
| try:
|
|
|
| match = re.search(r"```(json)?(.*)", json_string, re.DOTALL)
|
|
|
|
|
| if match is None:
|
| json_str = json_string
|
| else:
|
|
|
| json_str = match.group(2)
|
|
|
|
|
| json_str = json_str.strip().strip("`")
|
|
|
|
|
| json_str = _custom_parser(json_str)
|
|
|
|
|
| parsed = parse_partial_json(json_str)
|
|
|
| return parsed
|
| except Exception as e:
|
| print(e)
|
| return {
|
| } |