sync update from LAN repo (source dhk-1 @ fc974e93)
This commit is contained in:
1 parent
a1fa13a238
commit
e2fea6a801
432 files changed
+68707
-2270
No files matched your search
+27
-14
@@ -88,6 +88,10 @@ def extract_json_object(text: str | None) -> dict[str, Any] | None:
|
||||
return None
|
||||
candidate = text.strip()
|
||||
|
||||
# Strip reasoning blocks some models prepend (<think>…</think>).
|
||||
candidate = re.sub(r"<think>.*?</think>", "", candidate, flags=re.DOTALL | re.IGNORECASE)
|
||||
candidate = re.sub(r"</?think>", "", candidate).strip()
|
||||
|
||||
# Strip a single ```json ... ``` (or ``` ... ```) fence if present.
|
||||
fence = re.search(r"```(?:json)?\s*(.*?)```", candidate, flags=re.DOTALL | re.IGNORECASE)
|
||||
if fence:
|
||||
@@ -100,15 +104,24 @@ def extract_json_object(text: str | None) -> dict[str, Any] | None:
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Fallback: scan for the first balanced ``{ ... }`` and parse that.
|
||||
start = candidate.find("{")
|
||||
if start == -1:
|
||||
def _loads_lenient(blob: str) -> dict[str, Any] | None:
|
||||
# Tolerate trailing commas the model sometimes leaves before } or ].
|
||||
cleaned = re.sub(r",\s*([\]}])", chr(92) + chr(49), blob)
|
||||
for attempt in (blob, cleaned):
|
||||
try:
|
||||
parsed = json.loads(attempt)
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
return None
|
||||
|
||||
# Fallback: scan balanced ``{ ... }`` blocks; keep going when a block fails
|
||||
# (prose may contain stray braces before the real JSON payload).
|
||||
depth = 0
|
||||
in_string = False
|
||||
escape = False
|
||||
for index in range(start, len(candidate)):
|
||||
char = candidate[index]
|
||||
start = -1
|
||||
for index, char in enumerate(candidate):
|
||||
if in_string:
|
||||
if escape:
|
||||
escape = False
|
||||
@@ -120,16 +133,16 @@ def extract_json_object(text: str | None) -> dict[str, Any] | None:
|
||||
if char == '"':
|
||||
in_string = True
|
||||
elif char == "{":
|
||||
depth += 1
|
||||
elif char == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
blob = candidate[start : index + 1]
|
||||
try:
|
||||
parsed = json.loads(blob)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
start = index
|
||||
depth += 1
|
||||
elif char == "}" and depth:
|
||||
depth -= 1
|
||||
if depth == 0 and start != -1:
|
||||
parsed = _loads_lenient(candidate[start : index + 1])
|
||||
if parsed is not None:
|
||||
return parsed
|
||||
start = -1
|
||||
return None
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user