Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d384a10a8d | ||
|
|
86af2c968d | ||
|
|
964189387d | ||
|
|
2ee3b54661 | ||
|
|
a9837981b3 | ||
|
|
88769c508c |
+3
-1
@@ -35,7 +35,9 @@ lm[ExtractSignature]:
|
|||||||
# on slow local models (the 40-min arithmetic)
|
# on slow local models (the 40-min arithmetic)
|
||||||
|
|
||||||
budget:
|
budget:
|
||||||
max_llm_calls: 80 # per FLOOP run (children get a slice; fan-outs multiply
|
# owner ruling 26/10: completeness beats budget — the budget must never
|
||||||
|
# silently truncate extraction; it bounds runaway runs only
|
||||||
|
max_llm_calls: 200 # per FLOOP run (children get a slice; fan-outs multiply
|
||||||
# entity questions — a 3-river fan needs ~3x a scalar)
|
# entity questions — a 3-river fan needs ~3x a scalar)
|
||||||
min_child_budget: 6
|
min_child_budget: 6
|
||||||
max_depth: 2 # recursion cap (PIPELINE.md §8.4)
|
max_depth: 2 # recursion cap (PIPELINE.md §8.4)
|
||||||
|
|||||||
+16
-1
@@ -58,6 +58,8 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
||||||
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
||||||
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
|
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
|
||||||
|
self._seq_of: dict[str, int] = {} # lm call_id -> prompt seq (budget mirror)
|
||||||
|
self._fname_of: dict[str, str] = {} # lm call_id -> prompt file name
|
||||||
self.reasks = 0 # LM calls the budget did not charge
|
self.reasks = 0 # LM calls the budget did not charge
|
||||||
self.meter = None # callable(str stage) -> None; budget charge
|
self.meter = None # callable(str stage) -> None; budget charge
|
||||||
|
|
||||||
@@ -117,6 +119,8 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
self._file_of[call_id] = f
|
self._file_of[call_id] = f
|
||||||
|
self._seq_of[call_id] = n
|
||||||
|
self._fname_of[call_id] = fn
|
||||||
streams.log(
|
streams.log(
|
||||||
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
|
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
|
||||||
f"-> prompts/{fn}"
|
f"-> prompts/{fn}"
|
||||||
@@ -130,7 +134,10 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
label = self._stage_of.pop(call_id, "lm")
|
label = self._stage_of.pop(call_id, "lm")
|
||||||
start = self._starts.pop(call_id, None)
|
start = self._starts.pop(call_id, None)
|
||||||
f = self._file_of.pop(call_id, None)
|
f = self._file_of.pop(call_id, None)
|
||||||
dur = f"{time.monotonic() - start:.1f}s" if start is not None else "?"
|
n = self._seq_of.pop(call_id, None)
|
||||||
|
fn = self._fname_of.pop(call_id, None)
|
||||||
|
dur_s = (time.monotonic() - start) if start is not None else None
|
||||||
|
dur = f"{dur_s:.1f}s" if dur_s is not None else "?"
|
||||||
# RAW RESPONSE into the same file: the exact LM text, unmodified —
|
# RAW RESPONSE into the same file: the exact LM text, unmodified —
|
||||||
# the parsed OUTPUT can lie by omission (run I)
|
# the parsed OUTPUT can lie by omission (run I)
|
||||||
if f is not None:
|
if f is not None:
|
||||||
@@ -146,6 +153,14 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
+ ")\n" + (raw or "(empty)"))
|
+ ")\n" + (raw or "(empty)"))
|
||||||
if streams is not None:
|
if streams is not None:
|
||||||
streams.log(f"prompt {label} done in {dur}")
|
streams.log(f"prompt {label} done in {dur}")
|
||||||
|
try:
|
||||||
|
streams.recorder.emit(
|
||||||
|
"llm.done", stage=label, call_seq=n,
|
||||||
|
dur_s=(round(dur_s, 2) if dur_s is not None else None),
|
||||||
|
file=f"prompts/{fn}" if fn is not None else None,
|
||||||
|
exception=repr(exception)[:120] if exception else None)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
# dspy module class -> log stage label (knowledge/ + floop/ share the callback)
|
# dspy module class -> log stage label (knowledge/ + floop/ share the callback)
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""The flight recorder — every component of a run leaves a JSON line.
|
||||||
|
|
||||||
|
Owner ruling (26/10): 'vull poder fer com un debug amb l'IDE de
|
||||||
|
programació, però a posteriori de l'execució.' This is the recorder
|
||||||
|
half: LLM calls and code components (gate, skim, claims, type, merge,
|
||||||
|
probe, prover...) each emit one event to runs/<ts>/events.jsonl with
|
||||||
|
their input, output, and parent — the span tree comes from `parent`.
|
||||||
|
|
||||||
|
Design laws:
|
||||||
|
- The recorder must NEVER break a run: emitting is wrapped so any
|
||||||
|
failure is swallowed; with no run dir it is a silent no-op.
|
||||||
|
- One JSON object per line, appended and flushed: the file is
|
||||||
|
tail-able while the run is live and jq-able afterwards.
|
||||||
|
- `seq` is global per run (order of emission = file order).
|
||||||
|
- `in`/`out` carry only the caller-provided payload; the prompt files
|
||||||
|
keep the exact full text — events stay small and structured.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
class Recorder:
|
||||||
|
"""Append-only JSONL event log for one run. No-op without a run dir."""
|
||||||
|
|
||||||
|
def __init__(self, run_dir: str | Path | None = None,
|
||||||
|
memory: bool = False) -> None:
|
||||||
|
self.run_dir = Path(run_dir) if run_dir else None
|
||||||
|
self.run_ts = (datetime.now(timezone.utc).astimezone()
|
||||||
|
.strftime("%H:%M:%S.%f")[:-3])
|
||||||
|
self.seq = 0
|
||||||
|
self.events = 0
|
||||||
|
self._memory = memory # keep events in RAM even without a file
|
||||||
|
self._fh = None
|
||||||
|
self._buffer: list[dict] = []
|
||||||
|
if self.run_dir is not None:
|
||||||
|
try:
|
||||||
|
self._fh = (self.run_dir / "events.jsonl").open(
|
||||||
|
"a", encoding="utf-8")
|
||||||
|
except OSError:
|
||||||
|
self._fh = None
|
||||||
|
|
||||||
|
# -- emission ---------------------------------------------------------
|
||||||
|
|
||||||
|
def emit(self, event: str, **fields: Any) -> None:
|
||||||
|
"""One JSON line. `in_`/`out` are renamed to `in`/`out` (keywords).
|
||||||
|
Never raises: a run must not die for an observability side effect.
|
||||||
|
Without a run dir this is a TOTAL no-op (no file, no buffer, no
|
||||||
|
counters): disabled must mean zero effect.
|
||||||
|
"""
|
||||||
|
if self._fh is None and not self._memory:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
payload = dict(fields)
|
||||||
|
if "in_" in payload:
|
||||||
|
payload["in"] = payload.pop("in_")
|
||||||
|
self.seq += 1
|
||||||
|
line = {
|
||||||
|
"seq": self.seq,
|
||||||
|
"ts": datetime.now(timezone.utc).astimezone()
|
||||||
|
.strftime("%H:%M:%S.%f")[:-3],
|
||||||
|
"run_ts": self.run_ts,
|
||||||
|
"event": event,
|
||||||
|
**payload,
|
||||||
|
}
|
||||||
|
if self._fh is not None:
|
||||||
|
self._fh.write(json.dumps(line, default=str) + "\n")
|
||||||
|
self._fh.flush()
|
||||||
|
self._buffer.append(line)
|
||||||
|
self.events += 1
|
||||||
|
except Exception: # noqa: BLE001 — observability never kills the run
|
||||||
|
pass
|
||||||
|
|
||||||
|
# -- post-mortem reads --------------------------------------------------
|
||||||
|
|
||||||
|
def events_of(self, event: str) -> list[dict]:
|
||||||
|
"""In-memory events by name (for snapshot annotations)."""
|
||||||
|
return [e for e in self._buffer if e.get("event") == event]
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
if self._fh is not None and not self._fh.closed:
|
||||||
|
try:
|
||||||
|
self._fh.flush()
|
||||||
|
self._fh.close()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def timed(fn, recorder: Recorder, event: str, **parent_fields):
|
||||||
|
"""Wrap a code component: emit comp.done with in/out and duration."""
|
||||||
|
import functools
|
||||||
|
|
||||||
|
@functools.wraps(fn)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
t0 = time.monotonic()
|
||||||
|
try:
|
||||||
|
out = fn(*args, **kwargs)
|
||||||
|
recorder.emit(event, dur_ms=int((time.monotonic() - t0) * 1000),
|
||||||
|
ok=True, out=_safe(out), **parent_fields)
|
||||||
|
return out
|
||||||
|
except Exception as e: # noqa: BLE001 — record then re-raise
|
||||||
|
recorder.emit(event, dur_ms=int((time.monotonic() - t0) * 1000),
|
||||||
|
ok=False, error=repr(e)[:200], **parent_fields)
|
||||||
|
raise
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
def _safe(v: Any, _depth: int = 0) -> Any:
|
||||||
|
"""Best-effort JSON-safety: truncate strings, cap depth."""
|
||||||
|
if _depth > 4:
|
||||||
|
return "..."
|
||||||
|
if isinstance(v, str):
|
||||||
|
return v if len(v) <= 500 else v[:500] + "…"
|
||||||
|
if isinstance(v, dict):
|
||||||
|
return {str(k): _safe(x, _depth + 1) for k, x in list(v.items())[:30]}
|
||||||
|
if isinstance(v, (list, tuple)):
|
||||||
|
return [_safe(x, _depth + 1) for x in list(v)[:50]]
|
||||||
|
if v is None or isinstance(v, (bool, int, float)):
|
||||||
|
return v
|
||||||
|
return str(v)[:200]
|
||||||
@@ -12,6 +12,8 @@ import sys
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .recorder import Recorder
|
||||||
|
|
||||||
|
|
||||||
def _slug(text: str, maxlen: int = 40) -> str:
|
def _slug(text: str, maxlen: int = 40) -> str:
|
||||||
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
||||||
@@ -35,6 +37,7 @@ class RunStreams:
|
|||||||
self.log_path = self.run_dir / "run.log"
|
self.log_path = self.run_dir / "run.log"
|
||||||
self.verbose = verbose
|
self.verbose = verbose
|
||||||
self.prompt_seq = 0 # exact-prompt files: prompts/NN-stage.txt
|
self.prompt_seq = 0 # exact-prompt files: prompts/NN-stage.txt
|
||||||
|
self.recorder = Recorder(run_dir=self.run_dir, memory=True)
|
||||||
self._fh = open(self.log_path, "a", encoding="utf-8")
|
self._fh = open(self.log_path, "a", encoding="utf-8")
|
||||||
|
|
||||||
def bump_prompt_seq(self) -> int:
|
def bump_prompt_seq(self) -> int:
|
||||||
@@ -68,18 +71,21 @@ class RunStreams:
|
|||||||
def call(self, stage: str, description: str, think: str | None = None) -> None:
|
def call(self, stage: str, description: str, think: str | None = None) -> None:
|
||||||
"""An LLM call or engine step is starting."""
|
"""An LLM call or engine step is starting."""
|
||||||
self._emit_log(f"CALL {stage}: {description}")
|
self._emit_log(f"CALL {stage}: {description}")
|
||||||
|
self.recorder.emit("comp.start", comp=stage, desc=description[:200])
|
||||||
if think is not None:
|
if think is not None:
|
||||||
self.think_line(f"[{stage}] {think}")
|
self.think_line(f"[{stage}] {think}")
|
||||||
|
|
||||||
def output(self, stage: str, text: str, think: bool = True) -> None:
|
def output(self, stage: str, text: str, think: bool = True) -> None:
|
||||||
"""Raw LLM (or engine) output as it lands."""
|
"""Raw LLM (or engine) output as it lands."""
|
||||||
self._emit_log(f"OUTPUT {stage}: {text}")
|
self._emit_log(f"OUTPUT {stage}: {text}")
|
||||||
|
self.recorder.emit("comp.out", comp=stage, out=text[:500])
|
||||||
if think:
|
if think:
|
||||||
self.think(text)
|
self.think(text)
|
||||||
|
|
||||||
def state(self, text: str, think: bool = False) -> None:
|
def state(self, text: str, think: bool = False) -> None:
|
||||||
"""State change: evidence appended, question status, budget."""
|
"""State change: evidence appended, question status, budget."""
|
||||||
self._emit_log(f"STATE {text}")
|
self._emit_log(f"STATE {text}")
|
||||||
|
self.recorder.emit("state", text=text[:300])
|
||||||
if think:
|
if think:
|
||||||
self.think_line(text)
|
self.think_line(text)
|
||||||
|
|
||||||
@@ -94,6 +100,7 @@ class RunStreams:
|
|||||||
|
|
||||||
def final(self, text: str) -> None:
|
def final(self, text: str) -> None:
|
||||||
self._emit_log(f"FINAL {text}")
|
self._emit_log(f"FINAL {text}")
|
||||||
|
self.recorder.emit("run.final", out=text[:2000])
|
||||||
self.think_line(f"[FINAL] {text}")
|
self.think_line(f"[FINAL] {text}")
|
||||||
|
|
||||||
# ---- internals ---------------------------------------------------------
|
# ---- internals ---------------------------------------------------------
|
||||||
|
|||||||
@@ -164,6 +164,10 @@ class KnowledgeConfig:
|
|||||||
semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro
|
semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro
|
||||||
# cross-question 0.35-0.38 out, spouse-noise ~0.67
|
# cross-question 0.35-0.38 out, spouse-noise ~0.67
|
||||||
max_facts_per_chunk: int = 12 # question-blind extraction needs a cap
|
max_facts_per_chunk: int = 12 # question-blind extraction needs a cap
|
||||||
|
max_claims_per_chunk: int = 6 # DEPRECATED (owner ruling 26/10:
|
||||||
|
# completeness beats budget) — no longer
|
||||||
|
# read by the two-pass loop; kept only for
|
||||||
|
# the table-frags legacy path
|
||||||
extract_mode: str = "two_pass" # "two_pass" (claims -> typed Facts, short
|
extract_mode: str = "two_pass" # "two_pass" (claims -> typed Facts, short
|
||||||
# outputs) | "single" (legacy one-call typed
|
# outputs) | "single" (legacy one-call typed
|
||||||
# array — table frags keep using it)
|
# array — table frags keep using it)
|
||||||
@@ -205,6 +209,16 @@ class KnowledgeExpert:
|
|||||||
if self.streams:
|
if self.streams:
|
||||||
self.streams.state(text, think=think)
|
self.streams.state(text, think=think)
|
||||||
|
|
||||||
|
def _rec(self, event: str, **fields) -> None:
|
||||||
|
"""Flight-recorder event (post-mortem debugging, owner 26/10):
|
||||||
|
every component, LLM or not, leaves one JSON line. No streams ->
|
||||||
|
silent no-op (the recorder law: observability never breaks a run)."""
|
||||||
|
if self.streams is not None:
|
||||||
|
try:
|
||||||
|
self.streams.recorder.emit(event, **fields)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
def _qvec(self, question: str) -> list[float] | None:
|
def _qvec(self, question: str) -> list[float] | None:
|
||||||
"""Question vector, cached per question text. None = embedder down
|
"""Question vector, cached per question text. None = embedder down
|
||||||
(the probe degrades to lexical — offline fallback law, never dead)."""
|
(the probe degrades to lexical — offline fallback law, never dead)."""
|
||||||
@@ -231,9 +245,13 @@ class KnowledgeExpert:
|
|||||||
rows = self.store.probe(seeds)
|
rows = self.store.probe(seeds)
|
||||||
qv = self._qvec(question)
|
qv = self._qvec(question)
|
||||||
if qv is None:
|
if qv is None:
|
||||||
|
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
||||||
|
rows=len(rows), semantic=0)
|
||||||
return rows
|
return rows
|
||||||
sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau)
|
sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau)
|
||||||
if not sem:
|
if not sem:
|
||||||
|
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
||||||
|
rows=len(rows), semantic=0)
|
||||||
return rows
|
return rows
|
||||||
seen = {r.eid for r in rows}
|
seen = {r.eid for r in rows}
|
||||||
added = 0
|
added = 0
|
||||||
@@ -246,6 +264,9 @@ class KnowledgeExpert:
|
|||||||
if added:
|
if added:
|
||||||
self._log(f"semantic probe: +{added} edges the lexical probe missed "
|
self._log(f"semantic probe: +{added} edges the lexical probe missed "
|
||||||
f"(tau={self.cfg.semantic_tau})", think=True)
|
f"(tau={self.cfg.semantic_tau})", think=True)
|
||||||
|
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
||||||
|
rows=len(rows), semantic=added,
|
||||||
|
tau=self.cfg.semantic_tau)
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -331,14 +352,20 @@ class KnowledgeExpert:
|
|||||||
ok, reason = validate_query(q)
|
ok, reason = validate_query(q)
|
||||||
if not ok:
|
if not ok:
|
||||||
self._log(f"prover: invalid DSL term ({reason}); judge path", think=True)
|
self._log(f"prover: invalid DSL term ({reason}); judge path", think=True)
|
||||||
|
self._rec("prover.done", q=question[:80], verdict="invalid_dsl",
|
||||||
|
reason=reason, dsl=q)
|
||||||
return None
|
return None
|
||||||
proof = evaluate(self.store, q)
|
proof = evaluate(self.store, q)
|
||||||
if not proof.bindings:
|
if not proof.bindings:
|
||||||
self._log(f"prover: no closed path; judge path", think=True)
|
self._log(f"prover: no closed path; judge path", think=True)
|
||||||
|
self._rec("prover.done", q=question[:80], verdict="no_closed_path",
|
||||||
|
dsl=q)
|
||||||
return None
|
return None
|
||||||
if not re_execute(self.store, q, proof):
|
if not re_execute(self.store, q, proof):
|
||||||
self._log("prover: re-execution mismatch (store changed?); judge path",
|
self._log("prover: re-execution mismatch (store changed?); judge path",
|
||||||
think=True)
|
think=True)
|
||||||
|
self._rec("prover.done", q=question[:80],
|
||||||
|
verdict="reexecution_mismatch", dsl=q)
|
||||||
return None
|
return None
|
||||||
vals = []
|
vals = []
|
||||||
quote = ""
|
quote = ""
|
||||||
@@ -374,8 +401,47 @@ class KnowledgeExpert:
|
|||||||
self._log(f"prover: closed path ({n} binding(s): "
|
self._log(f"prover: closed path ({n} binding(s): "
|
||||||
f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call",
|
f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call",
|
||||||
think=True)
|
think=True)
|
||||||
|
self._rec("prover.done", q=question[:80],
|
||||||
|
verdict="closed" if n == 1 else "ambiguous",
|
||||||
|
dsl=q, n_bindings=n, bindings=[v[:80] for v in vals])
|
||||||
return answer
|
return answer
|
||||||
|
|
||||||
|
def kg_snapshot(self) -> dict:
|
||||||
|
"""The KG as a JSON-safe object for the flight recorder: every
|
||||||
|
live edge with its temporal window and its LAST-TOUCH event (owner
|
||||||
|
26/10: 'cada fila del kg podria tenir anotat quan s'afegeix o
|
||||||
|
edita'). The last-touch map comes from this run's merge events
|
||||||
|
(in the recorder's memory); rows the run never touched carry the
|
||||||
|
empty marker. One snapshot per run — emitted once at the end."""
|
||||||
|
try:
|
||||||
|
last_touch: dict[int, dict] = {}
|
||||||
|
rec = (self.streams.recorder if self.streams else None)
|
||||||
|
if rec is not None:
|
||||||
|
for e in rec.events_of("fact.merged"):
|
||||||
|
if e.get("eid") is not None:
|
||||||
|
last_touch[e["eid"]] = {"seq": e.get("seq"),
|
||||||
|
"ts": e.get("ts"),
|
||||||
|
"page": e.get("page")}
|
||||||
|
edges = []
|
||||||
|
for (eid, subj, rel, dstv, s, en, red) in self.store.db.execute(
|
||||||
|
"SELECT e.id, n.norm_name, e.rel, e.dst_value, "
|
||||||
|
"e.t_start, e.t_end, e.retracted "
|
||||||
|
"FROM edges e JOIN nodes n ON n.id=e.src_node "
|
||||||
|
"ORDER BY e.id").fetchall():
|
||||||
|
edges.append({
|
||||||
|
"eid": eid, "subject": subj, "rel": rel,
|
||||||
|
"object": dstv, "t_start": s, "t_end": en,
|
||||||
|
"retracted": bool(red),
|
||||||
|
"last_touch": last_touch.get(eid),
|
||||||
|
})
|
||||||
|
conflicts = self.store.db.execute(
|
||||||
|
"SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
|
return {"n_edges": len(edges),
|
||||||
|
"n_live": sum(1 for e in edges if not e["retracted"]),
|
||||||
|
"n_conflicts": conflicts, "edges": edges}
|
||||||
|
except Exception: # noqa: BLE001 — a snapshot must never kill a run
|
||||||
|
return {"n_edges": 0, "n_live": 0, "n_conflicts": 0, "edges": []}
|
||||||
|
|
||||||
def answer_question(self, question: str, parent_question: str = "",
|
def answer_question(self, question: str, parent_question: str = "",
|
||||||
evidence: str = "", charge_llm=None,
|
evidence: str = "", charge_llm=None,
|
||||||
answer_type: str = "") -> dict:
|
answer_type: str = "") -> dict:
|
||||||
@@ -1179,8 +1245,18 @@ class KnowledgeExpert:
|
|||||||
claims = claims_from(self, entities=ent_str,
|
claims = claims_from(self, entities=ent_str,
|
||||||
heading=chunk.heading_path,
|
heading=chunk.heading_path,
|
||||||
text=chunk.text, charge_llm=charge_llm)
|
text=chunk.text, charge_llm=charge_llm)
|
||||||
for claim in claims[: self.cfg.max_facts_per_chunk]:
|
self._rec("claims.done", page=page.title,
|
||||||
fact = fact_from_claim(self, claim, charge_llm=charge_llm)
|
heading=chunk.heading_path,
|
||||||
|
out_={"n_claims": len(claims),
|
||||||
|
"claims": list(claims)})
|
||||||
|
# owner ruling 26/10: completeness beats budget — every
|
||||||
|
# unique claim gets its TYPE call (no cap, dedup only)
|
||||||
|
for claim in claims:
|
||||||
|
fact = fact_from_claim(self, claim, text=chunk.text,
|
||||||
|
charge_llm=charge_llm)
|
||||||
|
self._rec("type.done", page=page.title, claim=claim[:200],
|
||||||
|
out_={"fact": getattr(fact, "__dict__", None)}
|
||||||
|
if fact is not None else {"fact": None})
|
||||||
if fact is None:
|
if fact is None:
|
||||||
continue # honestly declined: no invention
|
continue # honestly declined: no invention
|
||||||
merged, _eid = self._ingest_candidate(
|
merged, _eid = self._ingest_candidate(
|
||||||
@@ -1256,6 +1332,8 @@ class KnowledgeExpert:
|
|||||||
ok, reason = check_candidate(cand, containment)
|
ok, reason = check_candidate(cand, containment)
|
||||||
if not ok:
|
if not ok:
|
||||||
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
||||||
|
self._rec("fact.rejected", reason=reason, fact=dict(cand),
|
||||||
|
page=page.title)
|
||||||
return 0, None
|
return 0, None
|
||||||
doc_id = self.store.add_document(
|
doc_id = self.store.add_document(
|
||||||
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
||||||
@@ -1266,6 +1344,7 @@ class KnowledgeExpert:
|
|||||||
t_start=cand["start"] or None,
|
t_start=cand["start"] or None,
|
||||||
t_end=cand["end"] or None)
|
t_end=cand["end"] or None)
|
||||||
self._merged += 1
|
self._merged += 1
|
||||||
|
self._rec("fact.merged", eid=eid, fact=dict(cand), page=page.title)
|
||||||
if eid is not None:
|
if eid is not None:
|
||||||
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
|
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
|
||||||
cand["object"])
|
cand["object"])
|
||||||
|
|||||||
@@ -89,16 +89,22 @@ class ExtractClaims(dspy.Signature):
|
|||||||
|
|
||||||
|
|
||||||
class TypeClaim(dspy.Signature):
|
class TypeClaim(dspy.Signature):
|
||||||
"""You are the TYPE step of a knowledge machine. Given ONE single claim,
|
"""You are the TYPE step of a knowledge machine. Given ONE single claim
|
||||||
type it into the Fact schema: subject entity, relation, object/value,
|
and the TEXT it was extracted from, type the claim into the Fact
|
||||||
the VERBATIM quote from the text that states the claim (the FULL
|
schema: subject entity, relation, object/value, the VERBATIM quote
|
||||||
sentence or table row, copied exactly, at least 10 characters), and
|
copied EXACTLY from the text (the FULL sentence or table row that
|
||||||
the temporal restrictions the text states. All temporal fields are
|
states the claim, at least 10 characters), and the temporal
|
||||||
optional and must be contained in the quote. Only what the claim and
|
restrictions the text states. All temporal fields are optional and
|
||||||
its quote state; no inference."""
|
must be contained in the quote. Only what the claim and its quote
|
||||||
|
state; no inference. If the text does not state the claim, return
|
||||||
|
null."""
|
||||||
claim: str = dspy.InputField(desc="the claim to type")
|
claim: str = dspy.InputField(desc="the claim to type")
|
||||||
|
text: str = dspy.InputField(
|
||||||
|
desc="the text the claim was extracted from — find the VERBATIM "
|
||||||
|
"quote here, copied exactly")
|
||||||
fact: Fact | None = dspy.OutputField(
|
fact: Fact | None = dspy.OutputField(
|
||||||
desc="the typed Fact, or null when the claim cannot be typed honestly")
|
desc="the typed Fact with its verbatim quote from the text, or "
|
||||||
|
"null when the claim cannot be typed honestly")
|
||||||
|
|
||||||
|
|
||||||
class AnswerFromKG(dspy.Signature):
|
class AnswerFromKG(dspy.Signature):
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ def test_extract_claims_signature():
|
|||||||
def test_type_claim_signature():
|
def test_type_claim_signature():
|
||||||
"""Pass 2: one claim -> one typed Fact; orders NEVER produced here."""
|
"""Pass 2: one claim -> one typed Fact; orders NEVER produced here."""
|
||||||
fields = set(TypeClaim.__fields__)
|
fields = set(TypeClaim.__fields__)
|
||||||
assert fields == {"claim", "fact"}, fields
|
assert fields == {"claim", "text", "fact"}, fields # text: the quote must be COPIED from it (live finding: without it, 69/70 invented quotes rejected)
|
||||||
f = TypeClaim.model_fields["fact"].annotation
|
f = TypeClaim.model_fields["fact"].annotation
|
||||||
assert "Fact" in str(f), f
|
assert "Fact" in str(f), f
|
||||||
# Fact KEEPS orders (the legacy single-pass path and table frags use
|
# Fact KEEPS orders (the legacy single-pass path and table frags use
|
||||||
@@ -88,7 +88,7 @@ def test_fact_from_claim_types_one_fact():
|
|||||||
object="Spain", quote="is a Spanish politician who has been the "
|
object="Spain", quote="is a Spanish politician who has been the "
|
||||||
"prime minister of Spain since 2018",
|
"prime minister of Spain since 2018",
|
||||||
start="2018", end=None, point=None, granularity="year")))
|
start="2018", end=None, point=None, granularity="year")))
|
||||||
f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018")
|
f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018", text="...")
|
||||||
assert f.subject == "Pedro Sanchez" and f.start == "2018", f
|
assert f.subject == "Pedro Sanchez" and f.start == "2018", f
|
||||||
print("ok: fact_from_claim returns the typed Fact for one claim")
|
print("ok: fact_from_claim returns the typed Fact for one claim")
|
||||||
|
|
||||||
@@ -97,14 +97,40 @@ def test_honest_empty():
|
|||||||
e = Scripted(claims=Scripted(claims=[]))
|
e = Scripted(claims=Scripted(claims=[]))
|
||||||
assert claims_from(e, entities="", heading="", text="") == []
|
assert claims_from(e, entities="", heading="", text="") == []
|
||||||
e2 = Scripted(typeclaim=Scripted(fact=None))
|
e2 = Scripted(typeclaim=Scripted(fact=None))
|
||||||
assert fact_from_claim(e2, claim="") is None
|
assert fact_from_claim(e2, claim="", text="") is None
|
||||||
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
|
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
|
||||||
|
|
||||||
|
|
||||||
|
def test_claims_from_dedupes_exact_repeats():
|
||||||
|
"""Pass 1 sometimes repeats its own list (live: glm listed 46 claims,
|
||||||
|
~26 were exact repeats/thinking leakage). Dedup is CODE, cheap and
|
||||||
|
deterministic — the claim list must not be capped or filtered
|
||||||
|
semantically, only made honest: no exact duplicates survive."""
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
class E: # minimal expert double
|
||||||
|
def claims(self, entities, heading, text):
|
||||||
|
calls.append((entities, heading))
|
||||||
|
class Out:
|
||||||
|
claims = ["Pedro Sanchez is prime minister of Spain.",
|
||||||
|
"pedro sanchez is prime minister of spain. ",
|
||||||
|
"Pedro Sanchez is Secretary-General of the PSOE.",
|
||||||
|
"Pedro Sanchez is prime minister of Spain.",
|
||||||
|
"from the text. I need to list factual claims"]
|
||||||
|
return Out()
|
||||||
|
|
||||||
|
got = claims_from(E(), entities="Pedro Sanchez", heading="h", text="t")
|
||||||
|
assert got == ["Pedro Sanchez is prime minister of Spain.",
|
||||||
|
"Pedro Sanchez is Secretary-General of the PSOE.",
|
||||||
|
"from the text. I need to list factual claims"], got
|
||||||
|
print("ok: exact repeats deduped (case/space-insensitive); the rest kept")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
test_extract_claims_signature()
|
test_extract_claims_signature()
|
||||||
test_type_claim_signature()
|
test_type_claim_signature()
|
||||||
|
test_claims_from_dedupes_exact_repeats()
|
||||||
test_claims_from_runs_pass1()
|
test_claims_from_runs_pass1()
|
||||||
test_fact_from_claim_types_one_fact()
|
test_fact_from_claim_types_one_fact()
|
||||||
test_honest_empty()
|
test_honest_empty()
|
||||||
print("\ntwo_pass_extract: 5/5 ok")
|
print("\ntwo_pass_extract: 6/6 ok")
|
||||||
+30
-18
@@ -15,26 +15,38 @@ from __future__ import annotations
|
|||||||
|
|
||||||
def claims_from(expert, entities: str, heading: str, text: str,
|
def claims_from(expert, entities: str, heading: str, text: str,
|
||||||
charge_llm=None) -> list[str]:
|
charge_llm=None) -> list[str]:
|
||||||
"""Pass 1: the chunk's claims as plain strings, coreferences resolved."""
|
"""Pass 1: the chunk's claims as plain strings, coreferences resolved.
|
||||||
if charge_llm:
|
|
||||||
charge_llm()
|
|
||||||
pred = expert.claims(entities=entities, heading=heading, text=text)
|
|
||||||
out = []
|
|
||||||
for c in (pred.claims or []):
|
|
||||||
c = (c or "").strip()
|
|
||||||
if c:
|
|
||||||
out.append(c)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
The list is made honest by CODE only: exact repeats are dropped
|
||||||
def fact_from_claim(expert, claim: str, charge_llm=None):
|
(live finding 26/10: glm sometimes lists its whole list twice, and
|
||||||
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined).
|
thinking leakage leaks in as list items). Dedup is case- and
|
||||||
|
whitespace-insensitive; the FIRST occurrence's exact text is kept.
|
||||||
The Fact carries the verbatim quote and any temporal restrictions
|
NO cap, NO semantic filter: completeness beats budget (owner ruling
|
||||||
the text states; the store's containment checks validate everything
|
26/10) — every unique claim gets its TYPE call.
|
||||||
downstream exactly as before. No orders: no siblings by construction.
|
|
||||||
"""
|
"""
|
||||||
if charge_llm:
|
if charge_llm:
|
||||||
charge_llm()
|
charge_llm()
|
||||||
pred = expert.typeclaim(claim=claim)
|
pred = expert.claims(entities=entities, heading=heading, text=text)
|
||||||
|
seen: dict[str, str] = {}
|
||||||
|
for c in (pred.claims or []):
|
||||||
|
c = (c or "").strip()
|
||||||
|
if c:
|
||||||
|
key = " ".join(c.lower().split())
|
||||||
|
if key not in seen:
|
||||||
|
seen[key] = c
|
||||||
|
return list(seen.values())
|
||||||
|
|
||||||
|
|
||||||
|
def fact_from_claim(expert, claim: str, text: str, charge_llm=None):
|
||||||
|
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined).
|
||||||
|
|
||||||
|
The Fact's quote is copied VERBATIM from `text` (the chunk the claim
|
||||||
|
came from) — without the text the model invents a quote and the
|
||||||
|
containment check rejects it (live finding 26/10: 69/70 rejected).
|
||||||
|
The store's checks validate everything downstream as before. No
|
||||||
|
orders: no siblings by construction.
|
||||||
|
"""
|
||||||
|
if charge_llm:
|
||||||
|
charge_llm()
|
||||||
|
pred = expert.typeclaim(claim=claim, text=text)
|
||||||
return getattr(pred, "fact", None)
|
return getattr(pred, "fact", None)
|
||||||
@@ -143,6 +143,16 @@ def main() -> None:
|
|||||||
report: RunReport = FloopRun(question, budget, streams=streams,
|
report: RunReport = FloopRun(question, budget, streams=streams,
|
||||||
knowledge_engine=knowledge_engine).run()
|
knowledge_engine=knowledge_engine).run()
|
||||||
finally:
|
finally:
|
||||||
|
# THE FLIGHT RECORDER CLOSE-OUT: the KG snapshot (owner 26/10:
|
||||||
|
# one snapshot at the end, each row annotated with its last-touch
|
||||||
|
# event) and the recorder's file handle. Best-effort: the report
|
||||||
|
# has already been produced; observability never kills a run.
|
||||||
|
try:
|
||||||
|
if knowledge_engine is not None and streams is not None:
|
||||||
|
streams.recorder.emit("kg.snapshot",
|
||||||
|
kg=knowledge_engine.ke.kg_snapshot())
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
streams.close()
|
streams.close()
|
||||||
|
|
||||||
print(f"goal: {report.goal}")
|
print(f"goal: {report.goal}")
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""The flight recorder tests (events.jsonl).
|
||||||
|
|
||||||
|
Law: every component of a run — LLM or not — leaves one JSON line in
|
||||||
|
runs/<ts>/events.jsonl with its input, output, and parent, so the run
|
||||||
|
can be debugged a posteriori like an IDE session (owner 26/10: 'vull
|
||||||
|
fer com un debug amb l'IDE, però a posteriori'). The recorder must
|
||||||
|
never break a run: emitting is side-effect-free and cheap, and with no
|
||||||
|
run dir it is a silent no-op.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from floop.recorder import Recorder
|
||||||
|
|
||||||
|
|
||||||
|
def test_emit_writes_valid_jsonl_lines(tmp=None):
|
||||||
|
import tempfile
|
||||||
|
tmp = Path(tempfile.mkdtemp())
|
||||||
|
r = Recorder(run_dir=tmp)
|
||||||
|
r.emit("comp.done", comp="gate", parent="page:pedro", in_={"heading": "x"},
|
||||||
|
out={"kept": True}, dur_ms=3)
|
||||||
|
r.emit("fact.merged", fact={"s": "a"}, verdict="merged", eid=42)
|
||||||
|
lines = (tmp / "events.jsonl").read_text().strip().splitlines()
|
||||||
|
assert len(lines) == 2, lines
|
||||||
|
e1, e2 = (json.loads(l) for l in lines)
|
||||||
|
assert e1["event"] == "comp.done" and e1["comp"] == "gate", e1
|
||||||
|
assert e1["in"] == {"heading": "x"} and e1["out"] == {"kept": True}, e1
|
||||||
|
assert e1["parent"] == "page:pedro" and e1["seq"] == 1 and e1["dur_ms"] == 3
|
||||||
|
assert "ts" in e1 and e1["run_ts"], e1
|
||||||
|
assert e2["seq"] == 2 and e2["verdict"] == "merged" and e2["eid"] == 42
|
||||||
|
print("ok: emit -> one valid JSON line each, seq/ts/in/out/parent kept")
|
||||||
|
|
||||||
|
|
||||||
|
def test_disabled_recorder_is_a_silent_noop():
|
||||||
|
r = Recorder(run_dir=None)
|
||||||
|
r.emit("comp.done", comp="gate", out={"kept": True}) # must not raise
|
||||||
|
assert r.events == 0
|
||||||
|
print("ok: no run dir -> no-op, never breaks a run")
|
||||||
|
|
||||||
|
|
||||||
|
def test_in_memory_events_readable_for_snapshot():
|
||||||
|
import tempfile
|
||||||
|
tmp = Path(tempfile.mkdtemp())
|
||||||
|
r = Recorder(run_dir=tmp)
|
||||||
|
r.emit("merge.done", eid=7, verdict="merged")
|
||||||
|
r.emit("merge.done", eid=7, verdict="dup") # corroboration bump
|
||||||
|
evs = r.events_of("merge.done")
|
||||||
|
assert [e["eid"] for e in evs] == [7, 7]
|
||||||
|
assert [e["verdict"] for e in evs] == ["merged", "dup"]
|
||||||
|
# last-touch annotation: per-row latest event
|
||||||
|
last = {}
|
||||||
|
for e in evs:
|
||||||
|
last[e["eid"]] = e["verdict"]
|
||||||
|
assert last == {7: "dup"}
|
||||||
|
print("ok: events_of() lets the snapshot annotate each row's last touch")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_emit_writes_valid_jsonl_lines()
|
||||||
|
test_disabled_recorder_is_a_silent_noop()
|
||||||
|
test_in_memory_events_readable_for_snapshot()
|
||||||
|
print("\nrecorder: 3/3 ok")
|
||||||
Reference in New Issue
Block a user