import os, copy, uuid, requests, jsonpatch
def render_with_auto_fix(body, attempt=0):
res = requests.post(
"https://api.kynva.ai/api/v1/facade/generate",
headers={
"Authorization": f"Bearer {os.environ['KYNVA_API_KEY']}",
"Content-Type": "application/json",
"Idempotency-Key": str(uuid.uuid4()),
},
json=body,
timeout=60,
)
if res.ok or attempt >= 1:
return res
err = res.json()
patches = [op for d in err.get("error", {}).get("details", [])
for op in d.get("fix_patch", [])]
if not patches:
return res
patched = jsonpatch.JsonPatch(patches).apply(copy.deepcopy(body))
return render_with_auto_fix(patched, attempt + 1)