[PRISM] Robust JSON extraction for LLM output
This commit is contained in:
1 parent
f659d6d176
commit
e5bde15ead
1 file changed
+15
-9
@@ -42,15 +42,21 @@ def parse_loose(text):
|
||||
raise ValueError("no JSON object")
|
||||
raw = t[start:]
|
||||
raw = raw.replace("\r", " ").replace("\n", " ")
|
||||
try:
|
||||
return _json.loads(raw, strict=False)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
obj, _ = _json.JSONDecoder(strict=False).raw_decode(raw)
|
||||
return obj
|
||||
except Exception as e:
|
||||
raise ValueError("JSON parse: %s" % e)
|
||||
end = raw.rfind("}")
|
||||
if end > 0:
|
||||
raw = raw[:end + 1]
|
||||
candidates = [raw, re.sub(r",\s*([}\]])", r"\1", raw)]
|
||||
for cand in candidates:
|
||||
try:
|
||||
return _json.loads(cand, strict=False)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
obj, _ = _json.JSONDecoder(strict=False).raw_decode(cand)
|
||||
return obj
|
||||
except Exception:
|
||||
pass
|
||||
raise ValueError("JSON parse: %s" % (raw[:120],))
|
||||
|
||||
|
||||
conn = psycopg2.connect(rag.DSN)
|
||||
|
||||
Reference in new issue
Block a user