Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: extract JSON from prose and code fences

cipgysmo0d95958f5179
diff --git a/serve/structured.py b/serve/structured.py
index 3a726d607..101c78f6d 100644
--- a/serve/structured.py
+++ b/serve/structured.py
@@ -148,6 +148,43 @@ def prepare_format(response_format, messages):
return messages, validator
+def _extract_json(text: str) -> str:
+ s = (text or "").strip()
+ if not s:
+ return ""
+ if s.startswith("```"):
+ first = s.find("\n")
+ if first != -1:
+ end = s.find("```", first + 1)
+ if end != -1:
+ s = s[first + 1:end].strip()
+ start = s.find("{")
+ if start == -1:
+ return s
+ depth = 0
+ in_str = False
+ esc = False
+ for i in range(start, len(s)):
+ ch = s[i]
+ if in_str:
+ if esc:
+ esc = False
+ elif ch == "\\":
+ esc = True
+ elif ch == "\"":
+ in_str = False
+ else:
+ if ch == "\"":
+ in_str = True
+ elif ch == "{":
+ depth += 1
+ elif ch == "}":
+ depth -= 1
+ if depth == 0:
+ return s[start:i + 1]
+ return s[start:]
+
+
def validated_json(text, validator, finish):
def pairs(items):
obj = {}
@@ -163,7 +200,7 @@ def validated_json(text, validator, finish):
if finish != "stop":
raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget")
try:
- value = json.loads(text or "", object_pairs_hook=pairs, parse_constant=constant)
+ value = json.loads(_extract_json(text), object_pairs_hook=pairs, parse_constant=constant)
canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
except (ValueError, TypeError) as exc:
raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc