Skip to content

Commit bd326d2

Browse files
Only repair broken responses (#834)
* Only repair broken reponses * Format
1 parent 4822465 commit bd326d2

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"type": "patch",
3+
"description": "Try parsing json before even repairing"
4+
}

graphrag/llm/openai/utils.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,12 +91,23 @@ def get_completion_llm_args(
9191

9292
def try_parse_json_object(input: str) -> tuple[str, dict]:
9393
"""JSON cleaning and formatting utilities."""
94-
"""sometime, the llm return a json string with some extra description, this function will clean it up."""
94+
# Sometimes, the LLM returns a json string with some extra description, this function will clean it up.
95+
96+
result = None
97+
try:
98+
# Try parse first
99+
result = json.loads(input)
100+
except json.JSONDecodeError:
101+
log.info("Warning: Error decoding faulty json, attempting repair")
102+
103+
if result:
104+
return input, result
105+
95106
_pattern = r"\{(.*)\}"
96107
_match = re.search(_pattern, input)
97108
input = "{" + _match.group(1) + "}" if _match else input
98109

99-
"""Clean up json string."""
110+
# Clean up json string.
100111
input = (
101112
input.replace("{{", "{")
102113
.replace("}}", "}")
@@ -118,10 +129,10 @@ def try_parse_json_object(input: str) -> tuple[str, dict]:
118129
try:
119130
result = json.loads(input)
120131
except json.JSONDecodeError:
121-
"""Fixup potentially malformed json string using json_repair."""
132+
# Fixup potentially malformed json string using json_repair.
122133
input = str(repair_json(json_str=input, return_objects=False))
123134

124-
"""Generate JSON-string output using best-attempt prompting & parsing techniques."""
135+
# Generate JSON-string output using best-attempt prompting & parsing techniques.
125136
try:
126137
result = json.loads(input)
127138
except json.JSONDecodeError:

0 commit comments

Comments
 (0)