Accept JSON-encoded writer rewrites
This commit is contained in:
@@ -90,7 +90,25 @@ def parse_ai_json(content: str) -> dict:
|
||||
raw = raw.strip("`")
|
||||
if raw.lower().startswith("json"):
|
||||
raw = raw[4:].strip()
|
||||
return json.loads(raw)
|
||||
data = json.loads(raw)
|
||||
data = decode_jsonish(data)
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("AI response root is not an object")
|
||||
return data
|
||||
|
||||
|
||||
def decode_jsonish(value: Any) -> Any:
|
||||
for _ in range(3):
|
||||
if not isinstance(value, str):
|
||||
return value
|
||||
raw = value.strip()
|
||||
if not raw:
|
||||
return value
|
||||
try:
|
||||
value = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return value
|
||||
return value
|
||||
|
||||
|
||||
def response_usage(response: Any) -> dict[str, Any]:
|
||||
@@ -133,14 +151,12 @@ def validate_rewrites(
|
||||
categories: list[dict[str, Any]],
|
||||
source_tags_by_id: dict[int, str],
|
||||
) -> list[dict]:
|
||||
rewrites = data.get("rewrites")
|
||||
data = decode_jsonish(data)
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("AI response root is not an object")
|
||||
rewrites = decode_jsonish(data.get("rewrites"))
|
||||
if not isinstance(rewrites, list) and isinstance(data.get("data"), dict):
|
||||
rewrites = data["data"].get("rewrites")
|
||||
if isinstance(rewrites, str):
|
||||
try:
|
||||
rewrites = json.loads(rewrites)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
rewrites = decode_jsonish(data["data"].get("rewrites"))
|
||||
if not isinstance(rewrites, list):
|
||||
raise ValueError("AI response has no rewrites list")
|
||||
out: list[dict] = []
|
||||
|
||||
Reference in New Issue
Block a user