Tolerate malformed stringified writer rewrites
This commit is contained in:
@@ -107,10 +107,44 @@ def decode_jsonish(value: Any) -> Any:
|
|||||||
try:
|
try:
|
||||||
value = json.loads(raw)
|
value = json.loads(raw)
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
|
salvaged = loads_json_prefix(raw)
|
||||||
|
if salvaged is not None:
|
||||||
|
value = salvaged
|
||||||
|
continue
|
||||||
return value
|
return value
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def loads_json_prefix(raw: str) -> Any | None:
|
||||||
|
if not raw or raw[0] not in "[{":
|
||||||
|
return None
|
||||||
|
pairs = {"[": "]", "{": "}"}
|
||||||
|
stack: list[str] = []
|
||||||
|
in_string = False
|
||||||
|
escaped = False
|
||||||
|
for idx, char in enumerate(raw):
|
||||||
|
if in_string:
|
||||||
|
if escaped:
|
||||||
|
escaped = False
|
||||||
|
elif char == "\\":
|
||||||
|
escaped = True
|
||||||
|
elif char == '"':
|
||||||
|
in_string = False
|
||||||
|
continue
|
||||||
|
if char == '"':
|
||||||
|
in_string = True
|
||||||
|
elif char in pairs:
|
||||||
|
stack.append(pairs[char])
|
||||||
|
elif stack and char == stack[-1]:
|
||||||
|
stack.pop()
|
||||||
|
if not stack:
|
||||||
|
try:
|
||||||
|
return json.loads(raw[: idx + 1])
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def response_usage(response: Any) -> dict[str, Any]:
|
def response_usage(response: Any) -> dict[str, Any]:
|
||||||
usage = getattr(response, "usage", None)
|
usage = getattr(response, "usage", None)
|
||||||
if usage is None and isinstance(response, dict):
|
if usage is None and isinstance(response, dict):
|
||||||
|
|||||||
Reference in New Issue
Block a user