Spaces:
Running on Zero

checkjson / checkjson /trace.py
himanshu5trpth's picture
Upload 38 files
664563f verified
Raw History Blame Contribute Delete
7.03 kB
"""The trace: a snapshot of the call after each pipeline step.
`CheckJSON().repair(task, trace=True)` adds `result["trace"]`. The format is in docs/trace.md.
The tracer only records. It never changes a repair, and `trace=False` (the default) builds no tracer.
"""
import json
import time
from . import boxes
VERSION = 1
# When several steps share a box, the box shows the strongest state.
_ORDER = ("hole", "filled", "repaired", "no_call", "fail", "pass", "skipped")
def snapshot(value):
"""A JSON-safe deep copy."""
return json.loads(json.dumps(value, default=str))
def _clean(value):
"""Drop the internal `_original` key that the structural layer keeps while it works."""
if isinstance(value, dict):
return {k: _clean(v) for k, v in value.items() if k != "_original"}
if isinstance(value, list):
return [_clean(v) for v in value]
return value
def where(text, position):
"""'line L, column C' for a character position."""
position = max(0, min(position, len(text)))
line = text.count("\n", 0, position) + 1
column = position - (text.rfind("\n", 0, position) + 1) + 1
return f"line {line}, column {column}"
class Tracer:
def __init__(self, raw, tools):
self.raw, self.tools = raw, tools
self.steps = []
self.synced = 0 # trail entries already turned into steps
self.model_calls = 0 # engine calls already attributed to a step
self._t = time.perf_counter()
# ---- recording ------------------------------------------------------------------------
def add(self, box, outcome, rule=None, before=None, after=None, payload=None, message=None,
model_used=False, detail=None):
now = time.perf_counter()
step = {"index": len(self.steps), "stage": boxes.stage_of(box), "box": box, "rule": rule,
"outcome": outcome, "text_before": before, "text_after": after,
"payload_after": snapshot(_clean(payload)) if payload is not None else None,
"message": message, "model_used": model_used, "ms": round((now - self._t) * 1000, 3)}
if detail:
step["detail"] = snapshot(detail)
self.steps.append(step)
self._t = time.perf_counter()
return step
# ---- detection and the lexical layer ----------------------------------------------------
def parse(self, broken):
if broken is None:
self.add("detect.parse", "pass", before=self.raw, message="The text is valid JSON.")
else:
position, message = broken
at = where(self.raw, position) if position >= 0 else "the text"
self.add("detect.parse", "fail", before=self.raw, message=f"At {at}: {message}.")
def lexical(self, chosen, ambiguous, payload):
"""One step per applied edit, with the text before and after it."""
text = self.raw
edits, texts = chosen["edits"], chosen.get("texts", [])
for i, (label, after) in enumerate(zip(edits, texts)):
last = i == len(edits) - 1
message = boxes.describe(label, None)
if i == 0 and ambiguous:
message += f" {ambiguous} repairs fit. The one best supported by the conversation was kept."
self.add(boxes.box_of(label) or "lexical.punctuation", "repaired", rule=label, before=text,
after=after, payload=payload if last else None, message=message)
text = after
def unparseable(self):
self.add("lexical.truncation", "hole", rule="unparseable", before=self.raw,
message=boxes.describe("unparseable", None))
def schema(self, payload, errors):
if errors:
first = errors[0]
more = f" and {len(errors) - 1} more" if len(errors) > 1 else ""
self.add("detect.schema", "fail", payload=payload,
message=f"{first.get('code')} at {first.get('path') or '/'}{more}.")
else:
self.add("detect.schema", "pass", payload=payload, message="The call fits the tool schema.")
# ---- the structural layer (a callback of repair_structure) ----------------------------------
def structural(self, entry, ctx):
rule = entry["rule"]
if "ti" in ctx:
current = ctx["fixed"] + ctx["clean"][ctx["ci"]:]
turns = list(ctx["result"]["turns"]) + [{"calls": current}] + list(ctx["payload"]["turns"][ctx["ti"] + 1:])
payload = {"turns": turns}
else:
payload = ctx["payload"]
self.add(boxes.box_of(rule) or "semantic.names_types", boxes.outcome_of(rule), rule=rule, payload=payload,
message=boxes.describe(rule, entry), detail={k: v for k, v in entry.items() if k != "rule"})
# ---- everything after: model, decisions, safeguards ----------------------------------------------
def sync(self, trail, payload, traces):
"""Turn trail entries that are not yet steps into steps. `payload` is the payload right now."""
used = len(traces) > self.model_calls
self.model_calls = len(traces)
for entry in trail[self.synced:]:
rule = entry["rule"]
box = boxes.box_of(rule)
if rule in boxes.GROUPS or box is None:
continue
self.add(box, boxes.outcome_of(rule), rule=rule, payload=payload, message=boxes.describe(rule, entry),
model_used=used and box.startswith("model"), detail={k: v for k, v in entry.items() if k != "rule"})
self.synced = len(trail)
def mark_synced(self, trail):
self.synced = len(trail)
def failed(self, box, rule, message, traces):
"""A step that ended in a hole. It has no trail entry. The model was used when it was asked."""
used = len(traces) > self.model_calls
self.model_calls = len(traces)
self.add(box, "hole", rule=rule, message=message, model_used=used)
# ---- the end --------------------------------------------------------------------------------
def finish(self, status, payload, failure):
if status == "ok":
self.add("output.valid", "pass", payload=payload, message="A valid call. It is safe to run.")
elif status == "unresolved":
self.add("output.hole", "hole", payload=payload,
message="A hole is left (%s). Do not run this call." % (failure or "schema errors remain"))
else:
self.add("output.no_call", "no_call", payload=payload,
message="No call (%s)." % status)
states = {b: "skipped" for b in boxes.BOXES}
for s in self.steps:
old = states[s["box"]]
if old == "skipped" or _ORDER.index(s["outcome"]) < _ORDER.index(old):
states[s["box"]] = s["outcome"]
return {"version": VERSION, "candidate_text": self.raw, "steps": self.steps, "boxes": states,
"final": {"status": status, "payload": snapshot(payload), "failure": failure}}