From 21cedc43d1343a2d033db2b961cb2b0c73c6f534 Mon Sep 17 00:00:00 2001 From: Saurabh Misra Date: Sat, 8 Mar 2025 02:34:58 -0800 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20up=20function=20`f?= =?UTF-8?q?ix=5Funescaped=5Fquotes=5Fin=5Fjson`=20by=20106%=20(#1891)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com> Co-authored-by: Shuchang Zheng --- skyvern/forge/sdk/api/llm/utils.py | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/skyvern/forge/sdk/api/llm/utils.py b/skyvern/forge/sdk/api/llm/utils.py index 91042088..cbcb69c7 100644 --- a/skyvern/forge/sdk/api/llm/utils.py +++ b/skyvern/forge/sdk/api/llm/utils.py @@ -122,12 +122,10 @@ def fix_unescaped_quotes_in_json(json_string: str) -> str: str: The JSON-like string with unescaped quotation marks within strings. """ escape_char = "\\" - # Indices to add the escape character to. Since we're processing the string from left to right, we need to sort - # the indices in descending order to avoid index shifting. - indices_to_add_escape_char = [] in_string = False escape = False json_structure_chars = {",", ":", "}", "]", "{", "["} + result = [] i = 0 while i < len(json_string): @@ -146,23 +144,22 @@ def fix_unescaped_quotes_in_json(json_string: str) -> str: in_string = False else: # If the next character is not a JSON structure character, the quote is part of the string - # Update the indices to add the escape character with the current index - indices_to_add_escape_char.append(i) + # Add the escape character before the quote + result.append(escape_char) else: # Start of the JSON string in_string = True else: escape = False + + # Append the current character to the result + result.append(char) i += 1 - # Sort the indices in descending order to avoid index shifting then add the escape character to the string - if indices_to_add_escape_char: + if len(result) != len(json_string): LOG.warning("Unescaped quotes found in JSON string. Adding escape character to fix the issue.") - indices_to_add_escape_char.sort(reverse=True) - for index in indices_to_add_escape_char: - json_string = json_string[:index] + escape_char + json_string[index:] - return json_string + return "".join(result) def fix_and_parse_json_string(json_string: str) -> dict[str, Any]: