Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c9c762b91 | ||
|
|
985aec2f60 | ||
|
|
e594339629 | ||
|
|
7dfac55cf4 | ||
|
|
302e50120c | ||
|
|
004c7974c6 | ||
|
|
1df3ec591b | ||
|
|
8a3f8b37e3 | ||
|
|
bb4afb6a66 | ||
|
|
dec1fccb53 | ||
|
|
30d0a48f7a | ||
|
|
86b444391d | ||
|
|
aabacf8c44 | ||
|
|
cc1eceb720 | ||
|
|
4766b47127 | ||
|
|
56e3b22bbf | ||
|
|
0ed26d3406 | ||
|
|
4301277ccd | ||
|
|
c257e9fe88 | ||
|
|
12a1ffd77f | ||
|
|
65d42d1942 | ||
|
|
ce028b6973 | ||
|
|
a6453b0cb3 | ||
|
|
66e8bd4daa | ||
|
|
c3d1b5d6d3 | ||
|
|
f953778f0a | ||
|
|
c7bd010f47 | ||
|
|
2a515795e5 |
@@ -136,6 +136,40 @@ them) are dimensions of the answer function, never branches. And one thing can n
|
||||
retracted: the user. A user-supplied fact colliding with a source is presented verbatim
|
||||
to the user — never silently resolved.
|
||||
|
||||
## 6-bis. Execution branches over ambiguity (2026-10-23, coded)
|
||||
|
||||
When an expert answers with SEVERAL defensible readings (the knowledge ablation audit
|
||||
flags `ambiguous` + named alternatives), a question that DEPENDS on that row does not
|
||||
inherit the coin-flip. The machine opens ONE EXECUTION BRANCH PER READING:
|
||||
|
||||
- **Lazy.** The branch is born only when the ambiguous row has an open dependent
|
||||
subtree — an ambiguity nobody downstream needs stays a note; the picked reading rides.
|
||||
The subtree is frozen at fork time: every branch of the fork copies the same questions.
|
||||
- **A branch is a world, not a fork of the run.** The branch reads the shared evidence
|
||||
table through a VIEW that binds the ambiguous row to its reading (the same law as the
|
||||
ablation mask: the table is never mutated — the original row keeps all its readings)
|
||||
and hides other branches' rows. Acquired knowledge (new rows, KG facts, fetched
|
||||
articles, conclusions) lands in the ONE shared store, tagged with the branch id —
|
||||
a later branch reuses an earlier branch's gathering for free.
|
||||
- **Death is honest.** A branch dies by contradiction, dead end (all its questions
|
||||
failed — UNKNOWN), or natural merge (its answer equals another branch's — deduped by
|
||||
normalized value, one conclusion). Never by an absurdity judge: surprising-but-cited
|
||||
answers render.
|
||||
- **Nesting composes.** An ambiguous row answered INSIDE a branch (with its own
|
||||
dependent) opens sub-branches under it, under the same branch cap; a parent carries
|
||||
its children's conditional as its answer.
|
||||
- **The final answer is conditional, composed by fixed code** — `if you meant the
|
||||
PM-of-Spain reading -> Rajoy | if you meant Socialist International -> Papandreou`.
|
||||
Never one reading chosen inside a synthesis prompt; never the alternatives handed to
|
||||
the next question's context (that only moves the coin-flip into answer_kg).
|
||||
- Clarifying with the user instead of running the branches is a POLICY ABOVE this
|
||||
mechanism (layer 3): asking = picking one branch upstairs. The mechanism itself
|
||||
always runs the worlds it needs.
|
||||
|
||||
Budget: branches share the run's `llm_calls` pool (a fork of N readings costs ~N× the
|
||||
dependent subtree — leave headroom or the later branches die by budget, honestly noted);
|
||||
branch count is capped (extra readings are dropped and NAMED, never silent).
|
||||
|
||||
## 7. Per-call context composition
|
||||
|
||||
Every LLM call gets its own purpose-built context, assembled by fixed code within the
|
||||
|
||||
@@ -260,6 +260,28 @@ branches compete for budget, a learned router earns its place (v2).
|
||||
becomes data-driven. v1's logs — enriched by meta-level critiques — are v2's training
|
||||
data, and the same data feeds prompt optimization and fine-tuning (META.md).
|
||||
|
||||
## 9-bis. Observability roadmap (future plan): OpenTelemetry
|
||||
|
||||
Today a run's observability is files: `runs/<ts>/run.log` (the line-based technical
|
||||
superset), `prompts/NN-stage.txt` (every exact rendered prompt + raw response), and the
|
||||
WARNING channel (machine judgements worth a human's eye — the mask seed that
|
||||
auto-answered a question, guards refusing ingests, budget starvation). This is complete
|
||||
but closed: reading it means tailing files.
|
||||
|
||||
**Planned, not built:** export the run as **OpenTelemetry** traces/spans so floop is
|
||||
observable from the standard tooling that already exists — Jaeger, Grafana Tempo,
|
||||
any OTLP consumer — instead of floop growing its own dashboards. The mapping is
|
||||
natural: one run = one trace; each LLM call, engine step (probe, search, fetch, check,
|
||||
merge) and evidence append = one span, carrying the fields the logs carry today
|
||||
(stage, budget tick, duration, prompt-file pointer, verification flags, warnings).
|
||||
The planned `events.jsonl` (machine-readable event stream) becomes the in-process
|
||||
event bus this exporter reads — one schema, two consumers (offline self-analysis in
|
||||
META.md, live OTel export). Warnings export as span events first-class, since they are
|
||||
the self-improvement signal the lessons bank counts.
|
||||
|
||||
Deferred until the loop hardening is done — building it before v1's shape settles
|
||||
would instrument a moving target.
|
||||
|
||||
## 10. Risks
|
||||
|
||||
1. **Misformalization** (top failure mode) — wrong formalization, correct math, wrong
|
||||
|
||||
+2
-1
@@ -48,8 +48,9 @@ Compare: `--baseline` vs the loop's many small directed calls.
|
||||
| MISSING — gap decomposition on stuck goal | real (dspy) | `floop/dspy_modules.py` |
|
||||
| ROUTE — one LLM judgement over the catalogue | real (dspy) | `floop/dspy_modules.py` |
|
||||
| Expert attendants (the draft answer) | **BASELINE engine**: LLM answers from its weights; `verified=False`; source recorded (`model_weights`/`given_evidence`) | `floop/engine.py` |
|
||||
| **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> TRANSLATE (queries+entities from context) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` |
|
||||
| **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> COMPOSE queries (deterministic, from question ∪ evidence — the old TRANSLATE LLM removed 23/10) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` |
|
||||
| Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` |
|
||||
| Execution branches over ambiguity (ALGORITHM §6-bis) | **REAL** (2026-10-23): lazy fork per reading of an ambiguous row with an open dependent; BranchView binds the reading (table never mutated), acquired knowledge shared + branch-tagged; death by contradiction/dead end/natural merge; nested sub-branches; conditional final answer composed by fixed code | `floop/branches.py` + `floop/machine.py:_run_branch` |
|
||||
| Prover (stop condition, derivability) | **STUB**: question stack terminal | `machine._finish` |
|
||||
| `user` expert | not wired — explicit failure row | `floop/engine.py` |
|
||||
| Backtracking / retraction (TMS) | not in the draft (§5 comes with the prover) | — |
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Query anonymization before INIT (his design, 22/10): the model must
|
||||
decompose the question's SHAPE, not lean on its knowledge of the people in
|
||||
it. Named entities are masked to typed placeholders (PERSON_1, ORGANIZATION_1,
|
||||
...) before INIT sees the query; the placeholders are restored in the
|
||||
returned subquestions — deterministically, by exact string replacement.
|
||||
|
||||
LLMs translate (NER proposal); fixed code applies and restores (ALGORITHM
|
||||
§7: LLMs never decide). The mask map is run-scoped state, not a prompt.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class NamedEntity(BaseModel):
|
||||
"""One named entity found in the question."""
|
||||
name: str = dspy.OutputField(
|
||||
desc="the entity's exact surface text as it appears in the question, copied verbatim")
|
||||
kind: str = dspy.OutputField(
|
||||
desc="PERSON, ORGANIZATION, PLACE, WORK, EVENT, or OTHER")
|
||||
|
||||
|
||||
class EntityMaskSignature(dspy.Signature):
|
||||
"""You are the MASK step of a reasoning machine. Find the named entities
|
||||
in the question — people, organizations, places, titles of works, events.
|
||||
Copy each one's text exactly as it appears; do not add entities that are
|
||||
not explicitly named."""
|
||||
question: str = dspy.InputField()
|
||||
entities: list[NamedEntity] = dspy.OutputField(
|
||||
desc="the named entities found; empty when none")
|
||||
|
||||
|
||||
# placeholder order: PERSON_1, PERSON_2, ORGANIZATION_1, ...
|
||||
_PREFIX = {"PERSON": "PERSON", "ORGANIZATION": "ORGANIZATION", "PLACE": "PLACE",
|
||||
"WORK": "WORK", "EVENT": "EVENT", "OTHER": "OTHER"}
|
||||
|
||||
|
||||
def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]:
|
||||
"""Mask the question deterministically. Longer names first (so
|
||||
'Pedro Sánchez Pérez-Castejón' is masked before its substrings).
|
||||
Returns (masked_question, restore_map placeholder -> original)."""
|
||||
restore: dict[str, str] = {}
|
||||
counters: dict[str, int] = {}
|
||||
masked = question
|
||||
for ent in sorted(entities, key=lambda e: len(e.name), reverse=True):
|
||||
name = ent.name.strip()
|
||||
if not name or name not in masked:
|
||||
continue
|
||||
kind = ent.kind.strip().upper()
|
||||
prefix = _PREFIX.get(kind, "OTHER")
|
||||
counters[prefix] = counters.get(prefix, 0) + 1
|
||||
ph = f"{prefix}_{counters[prefix]}"
|
||||
if ph in restore: # same surface text twice: keep one mask
|
||||
continue
|
||||
masked = masked.replace(name, ph)
|
||||
restore[ph] = name
|
||||
return masked, restore
|
||||
|
||||
|
||||
def restore_mask(text: str, restore: dict[str, str]) -> str:
|
||||
"""Restore placeholders to the original names, longest first (so
|
||||
PERSON_10 is not eaten by PERSON_1)."""
|
||||
for ph, name in sorted(restore.items(), key=lambda kv: len(kv[0]),
|
||||
reverse=True):
|
||||
text = text.replace(ph, name)
|
||||
return text
|
||||
|
||||
|
||||
# an identity question about ONE placeholder — the model asking who/what
|
||||
# the mask refers to. Detection lives in identity_answer: conservative
|
||||
# by law (his: never over-detect) — 'who/what is <ph>' exactly, or the
|
||||
# text names the mask mechanism ('placeholder', 'refer(s) to').
|
||||
|
||||
|
||||
def identity_answer(masked_text: str, restore: dict[str, str]) -> str | None:
|
||||
"""If a subquestion only asks who/what one placeholder refers to, the
|
||||
answer is the mask map itself — no expert ever needed. None otherwise.
|
||||
|
||||
Conservative by law (never over-detect): exactly one placeholder in
|
||||
the text, and the question is literally 'who/what is <ph>' (ending
|
||||
there or in punctuation — 'who is PERSON_1's predecessor' does NOT
|
||||
match) or it names the mask mechanism with the placeholder as the
|
||||
REFERENT: 'refer(s) to' must govern <ph> DIRECTLY ('what does
|
||||
PERSON_1 refer to?', 'the placeholder PERSON_1 refers to…'). A bare
|
||||
'refer to' anywhere in the sentence no longer fires — his 23/10 run:
|
||||
INIT's hidden-precondition phrasing 'does the title "President"
|
||||
refer to in relation to PERSON_1?' asked about the TITLE, the old
|
||||
clause seeded 'Pedro Sanchez' as the answer to which office was
|
||||
meant (a false positive with wrong semantics)."""
|
||||
phs = [ph for ph in restore if re.search(rf"\b{re.escape(ph)}\b",
|
||||
masked_text)]
|
||||
if len(phs) != 1:
|
||||
return None
|
||||
ph = phs[0]
|
||||
t = masked_text.strip()
|
||||
# lookahead: end-of-sentence/punctuation AFTER the placeholder — but
|
||||
# never an apostrophe: "PERSON_1's predecessor" is a possessive, not an
|
||||
# identity question (pre-existing trap found while verifying the 23/10
|
||||
# fix; the old test only covered 'Who WAS…', which dodges the literal)
|
||||
literal = re.match(
|
||||
rf"^(?:who|what)\s+(?:is|are)\s+{re.escape(ph)}(?=$|[\s,.?!:;)\"])",
|
||||
t, flags=re.IGNORECASE)
|
||||
if literal:
|
||||
return restore[ph]
|
||||
# mechanism mention: strict — the placeholder must be the REFERENT of
|
||||
# 'refer(s) to', not merely present in a sentence that uses the verb
|
||||
for pat in (rf"\brefer(?:s)?\s+to\s+{re.escape(ph)}\b",
|
||||
rf"{re.escape(ph)}\s+refer(?:s)?\s+to\b"):
|
||||
if re.search(pat, t, flags=re.IGNORECASE):
|
||||
return restore[ph]
|
||||
return None
|
||||
@@ -0,0 +1,319 @@
|
||||
"""Execution branches (his branching design, 22-23/10 — now coded).
|
||||
|
||||
When an expert answers a question with SEVERAL defensible readings
|
||||
(payload['ambiguous'] + alternatives, the knowledge expert's ablation
|
||||
audit), the machine does NOT hand the alternatives to the next
|
||||
subquestion's context (the rejected design — it only moves the
|
||||
coin-flip into answer_kg) and does NOT collapse them inside ANSWER
|
||||
(run L: 'Papandreou was the predecessor' — the exact rejected
|
||||
behaviour). Instead, when a question DEPENDS on an ambiguous row, the
|
||||
machine opens ONE LAZY EXECUTION BRANCH PER READING:
|
||||
|
||||
- a branch is a machine-level construct at floop DEPTH+1-like nesting,
|
||||
but INSIDE this run: it owns its question stack and reads the
|
||||
evidence through a BranchView that BINDS the ambiguous row to ONE
|
||||
reading (a VIEW, never a store mutation — the same law as the
|
||||
ablation mask);
|
||||
- LAZY: the branch is born only when a dependent of the ambiguous row
|
||||
becomes pickable — until then, nothing forks;
|
||||
- SHARED: the knowledge acquired by every branch lands in the ONE
|
||||
evidence table (the machine's working memory) and the KG/seen-index
|
||||
live in the expert, shared by construction — a later branch reuses
|
||||
what an earlier one gathered for free;
|
||||
- per-branch is the READING of the ambiguous row + the subquestions
|
||||
born under it; branch id rides every row's provenance;
|
||||
- a branch DIES only by contradiction (its checked arrival refusing a
|
||||
value), dead end (its terminal questions all failed — honest
|
||||
UNKNOWN), or NATURAL MERGE (its answers converge with another
|
||||
branch's — dedupe by value, keep the first) — never by an absurdity
|
||||
judge (surprising-but-cited answers render, they are not
|
||||
pocket-judged);
|
||||
- the final answer is CONDITIONAL over surviving branches, composed
|
||||
by FIXED CODE from the branch results — 'si et referies a president
|
||||
d'Espanya -> Rajoy; si SI -> Papandreou; si PSOE -> qui sigui' —
|
||||
never one reading chosen inside a synthesis prompt;
|
||||
- nested ambiguity: a branch that hits its OWN ambiguous row forks
|
||||
sub-branches under the same mechanism and the same caps.
|
||||
|
||||
Open by design (layer 3, a policy ABOVE this mechanism): asking the
|
||||
user instead of running all branches = picking one branch upstairs.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .state import EvidenceRow, EvidenceTable
|
||||
|
||||
# a branch result that is honestly nothing: dead end / contradiction /
|
||||
# everything failed. The conditional render skips it (the branch's death
|
||||
# is already in the notes), it never masquerades as an answer reading.
|
||||
DEAD_END = "UNKNOWN"
|
||||
|
||||
|
||||
def _norm(v: str) -> str:
|
||||
"""Merge/dedupe key: casefolded alphanumerics (norm_name's machine-level
|
||||
cousin — 'Rajoy' == 'rajoy', 'Pedro Sánchez' == 'Pedro Sanchez')."""
|
||||
return re.sub(r"[^a-z0-9]+", " ", (v or "").casefold()).strip()
|
||||
|
||||
|
||||
@dataclass
|
||||
class BranchSpec:
|
||||
"""One reading of one ambiguous row. The branch binds the row to
|
||||
value; reading is the human-legible label ('as President of Spain')."""
|
||||
id: str
|
||||
ambiguous_eid: str
|
||||
ambiguous_qid: str
|
||||
value: str # the reading this branch binds
|
||||
reading: str # label for the conditional render
|
||||
origin: str = "" # the id of the branch that forked this one ("" = root)
|
||||
# the open dependent SUBTREE copied into every branch of this fork,
|
||||
# frozen at fork time (B1 consuming the originals must not change
|
||||
# what B2 copies — the qids in qid order, deps rewired per branch)
|
||||
subtree_qids: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BranchResult:
|
||||
"""What a branch concluded, for the conditional render."""
|
||||
spec: BranchSpec
|
||||
answer: str = "" # the branch's final answer (synthesized inside it)
|
||||
status: str = "open" # open | answered | dead | merged
|
||||
|
||||
|
||||
class BranchView:
|
||||
"""The evidence table AS ONE BRANCH SEES IT.
|
||||
|
||||
The shared table is untouched — the ambiguous row is REPLACED in
|
||||
this view by a synthetic row binding the branch's reading (same
|
||||
qid, same answer_type, the reading's own quote/url, verified as
|
||||
its source rows were — the reading IS the expert's pick or one of
|
||||
its alternatives, each carried with quote+url by the audit). Rows
|
||||
from other branches (provenance['branch'] set and different) are
|
||||
HIDDEN: they answer questions that never existed in this world.
|
||||
|
||||
Everything else (rows with no branch tag, rows this branch appended)
|
||||
passes through unchanged — acquired knowledge is shared.
|
||||
"""
|
||||
|
||||
def __init__(self, table: "EvidenceTable", spec: BranchSpec) -> None:
|
||||
self._table = table
|
||||
self._spec = spec
|
||||
|
||||
def _bound_row(self) -> "EvidenceRow":
|
||||
from .state import EvidenceRow
|
||||
src = self._table.row(self._spec.ambiguous_eid)
|
||||
payload = {k: v for k, v in (src.payload or {}).items()
|
||||
if k not in ("ambiguous", "alternatives")}
|
||||
payload["value"] = self._spec.value
|
||||
payload["quote"] = self._reading_quote()
|
||||
payload["branch_binding"] = True # the branch-fake's marker: this
|
||||
# row IS the bound reading
|
||||
if self._spec.origin:
|
||||
payload["branch_reading"] = self._spec.reading
|
||||
return EvidenceRow(
|
||||
qid=src.qid, answer_type=src.answer_type, payload=payload,
|
||||
engine=src.engine + ":branch-bind",
|
||||
trace=[f"branch {self._spec.id}: ambiguous row bound to reading "
|
||||
f"'{self._spec.value}'"],
|
||||
provenance=dict(src.provenance, branch=self._spec.id),
|
||||
verified=src.verified, note="")
|
||||
|
||||
def _reading_quote(self) -> str:
|
||||
"""The reading's OWN quote when the row carries alternatives with
|
||||
quotes; else the picked answer's quote (branch = the pick)."""
|
||||
src = self._table.row(self._spec.ambiguous_eid)
|
||||
for a in (src.payload.get("alternatives") or []):
|
||||
if _norm(a.get("value", "")) == _norm(self._spec.value) and a.get("quote"):
|
||||
return a["quote"]
|
||||
return str(src.payload.get("quote", ""))
|
||||
|
||||
# -- the EvidenceTable interface the machine reads ---------------------
|
||||
def row(self, eid: str) -> "EvidenceRow | None":
|
||||
if eid == self._spec.ambiguous_eid:
|
||||
return self._bound_row()
|
||||
r = self._table.row(eid)
|
||||
if r is not None and self._hidden(r):
|
||||
return None
|
||||
return r
|
||||
|
||||
def append(self, row: "EvidenceRow") -> "EvidenceRow":
|
||||
"""A branch's new rows land in the SHARED table (acquired knowledge
|
||||
is shared — a later branch reuses them) tagged with the branch id
|
||||
(other branches' views hide them until they merge)."""
|
||||
row.provenance["branch"] = self._spec.id
|
||||
return self._table.append(row)
|
||||
|
||||
def rows(self) -> "list[EvidenceRow]":
|
||||
return ([self._bound_row()] if self._bound_row() else []) + \
|
||||
[r for r in self._table.rows() if r.eid != self._spec.ambiguous_eid
|
||||
and not self._hidden(r)]
|
||||
|
||||
def for_question(self, qid: str) -> "list[EvidenceRow]":
|
||||
return [r for r in self.rows() if r.qid == qid]
|
||||
|
||||
def dump(self) -> str:
|
||||
from .state import EvidenceTable
|
||||
flat = EvidenceTable()
|
||||
for r in self.rows():
|
||||
flat.append(type(r)(
|
||||
answer_type=r.answer_type, payload=dict(r.payload),
|
||||
engine=r.engine, qid=r.qid, trace=list(r.trace),
|
||||
provenance=dict(r.provenance), verified=r.verified,
|
||||
note=r.note, retracted=r.retracted))
|
||||
return flat.dump()
|
||||
|
||||
def _hidden(self, r: "EvidenceRow") -> bool:
|
||||
b = r.provenance.get("branch")
|
||||
return bool(b) and b != self._spec.id
|
||||
|
||||
|
||||
@dataclass
|
||||
class BranchManager:
|
||||
"""The fork bookkeeping. The machine asks 'should I fork on this row?'
|
||||
(is it ambiguous AND does an open question depend on it), gets one
|
||||
BranchSpec per reading, executes branches lazily, and renders the
|
||||
surviving results conditionally.
|
||||
|
||||
The manager holds no execution logic — the machine runs each branch
|
||||
as a plain FloopRun loop over its own stack; the manager owns the
|
||||
specs, the merge policy, and the conditional render.
|
||||
"""
|
||||
max_branches: int = 6
|
||||
specs: list[BranchSpec] = field(default_factory=list)
|
||||
results: dict[str, BranchResult] = field(default_factory=dict)
|
||||
dropped: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def pending(self) -> list[BranchSpec]:
|
||||
"""Specs not yet executed (FIFO — the picked reading runs first)."""
|
||||
return [s for s in self.specs
|
||||
if self.results.get(s.id) is None
|
||||
or self.results[s.id].status == "open"]
|
||||
|
||||
def fork_specs(self, row: "EvidenceRow", origin: str = "",
|
||||
subtree_qids: list[str] | None = None) -> list[BranchSpec]:
|
||||
"""One spec per defensible reading of an ambiguous row whose open
|
||||
dependent subtree (computed by the caller, frozen here) is non-
|
||||
empty. LAZY LAW: an empty subtree means no fork — the ambiguity
|
||||
is noted, the run continues on the pick.
|
||||
`origin`: the branch we are inside when the fork fires ("" = the
|
||||
root run) — nested ambiguity nests sub-branches under it.
|
||||
Branch cap: past max_branches live specs, the extra readings are
|
||||
dropped and NAMED (never silent)."""
|
||||
if not row.payload.get("ambiguous"):
|
||||
return []
|
||||
alts = row.payload.get("alternatives") or []
|
||||
readings = [(row.payload.get("value", ""), "the picked reading")]
|
||||
readings += [(a.get("value", ""), a.get("value", ""))
|
||||
for a in alts if a.get("value")]
|
||||
specs = []
|
||||
for i, (val, label) in enumerate(readings):
|
||||
if not val or str(val).upper() == "UNKNOWN":
|
||||
continue
|
||||
bid = f"B{len(self.specs) + len(specs) + 1}"
|
||||
spec = BranchSpec(
|
||||
id=bid, ambiguous_eid=row.eid, ambiguous_qid=row.qid,
|
||||
value=str(val),
|
||||
reading=label if label and label != val else f"reading {bid}",
|
||||
origin=origin,
|
||||
subtree_qids=list(subtree_qids or []))
|
||||
specs.append(spec)
|
||||
if len(self.specs) + len(specs) > self.max_branches:
|
||||
keep = self.max_branches - len(self.specs)
|
||||
dropped = [s.reading for s in specs[keep:]]
|
||||
specs = specs[:keep]
|
||||
self.dropped = self.dropped + dropped
|
||||
for s in specs:
|
||||
self.specs.append(s)
|
||||
self.results[s.id] = BranchResult(spec=s)
|
||||
return specs
|
||||
|
||||
def record_answer(self, spec_id: str, answer: str) -> None:
|
||||
res = self.results.get(spec_id)
|
||||
if res is not None:
|
||||
res.answer = answer
|
||||
res.status = "answered"
|
||||
|
||||
def record_dead(self, spec_id: str) -> None:
|
||||
res = self.results.get(spec_id)
|
||||
if res is not None:
|
||||
res.status = "dead"
|
||||
|
||||
def record_merge(self, spec_id: str, into: str) -> None:
|
||||
res = self.results.get(spec_id)
|
||||
if res is not None:
|
||||
res.status = "merged"
|
||||
res.answer = f"(merged with {into})"
|
||||
|
||||
def survivors(self, origin: str = "") -> list[BranchResult]:
|
||||
"""Answered branches at one nesting level (origin), deduped by
|
||||
normalized value — natural merge: two branches that concluded the
|
||||
same thing are one conclusion. First-come order (the picked
|
||||
reading usually leads)."""
|
||||
seen: dict[str, BranchResult] = {}
|
||||
order: list[BranchResult] = []
|
||||
for res in self.results.values():
|
||||
if res.status != "answered" or res.spec.origin != origin:
|
||||
continue
|
||||
key = _norm(res.answer)
|
||||
if key and key in seen:
|
||||
self.record_merge(res.spec.id, seen[key].spec.id)
|
||||
continue
|
||||
if key:
|
||||
seen[key] = res
|
||||
order.append(res)
|
||||
return order
|
||||
|
||||
def conditional_answer(self, goal: str, origin: str = "") -> str:
|
||||
"""The CONDITIONAL final answer, composed by FIXED CODE (run L
|
||||
law: never collapse readings inside a synthesis prompt). All
|
||||
surviving branch answers at one nesting level, one clause per
|
||||
reading; a single survivor renders plain, its branch noted. A
|
||||
branch whose own children answered carries its conditional as
|
||||
its recorded answer — nesting is baked in, not re-rendered.
|
||||
Dead branches are already in the notes; the render never
|
||||
invents their content."""
|
||||
alive = self.survivors(origin)
|
||||
dropped = self.dropped
|
||||
if not alive:
|
||||
parts = ["No reading reached an answer."]
|
||||
if dropped:
|
||||
parts.append(f"(branch cap: readings dropped: {', '.join(dropped)})")
|
||||
return " ".join(parts)
|
||||
if len(alive) == 1:
|
||||
r = alive[0]
|
||||
out = f"{r.answer} (reading: {r.spec.reading})"
|
||||
if dropped:
|
||||
out += f" — other readings hit the branch cap: {', '.join(dropped)}"
|
||||
return out
|
||||
clauses = [f"if you meant {res.spec.reading} -> {res.answer}"
|
||||
for res in alive]
|
||||
out = " | ".join(clauses)
|
||||
if dropped:
|
||||
out += f" | (branch cap: {', '.join(dropped)} not run)"
|
||||
return out
|
||||
|
||||
|
||||
def open_subtree(stack, ambiguous_qid: str) -> list[str]:
|
||||
"""The OPEN dependent subtree below one question: direct AND transitive
|
||||
open dependents, qids in discovery order. LAZY: an empty list means
|
||||
no fork — a branch is born only when someone needs the reading.
|
||||
Frozen at fork time: every branch of the fork copies the SAME list
|
||||
(the first branch consuming the originals must not change what the
|
||||
second copies)."""
|
||||
found: dict[str, str] = {} # orig qid -> branch copy qid (filled later)
|
||||
order: list[str] = []
|
||||
changed = True
|
||||
while changed:
|
||||
changed = False
|
||||
for q in stack.items:
|
||||
if (q.status == "open" and not q.parent_goal
|
||||
and q.qid not in order
|
||||
and any(d in found or d == ambiguous_qid for d in q.deps)):
|
||||
order.append(q.qid)
|
||||
found[q.qid] = ""
|
||||
changed = True
|
||||
return order
|
||||
+136
-26
@@ -7,24 +7,65 @@ Every module's docstring is the draft prompt — kept minimal on purpose.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .state import AnswerType
|
||||
|
||||
try:
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
except ImportError: # pragma: no cover — dspy <3.x
|
||||
AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""})
|
||||
|
||||
from .anonymize import (EntityMaskSignature, apply_mask, identity_answer,
|
||||
restore_mask)
|
||||
|
||||
|
||||
class Subquestion(BaseModel):
|
||||
"""One open subquestion in the goal's decomposition."""
|
||||
text: str = dspy.OutputField(desc="the subquestion, phrased as a question")
|
||||
depends_on: list[int] = dspy.OutputField(
|
||||
desc="1-based positions of the subquestions whose answers this one needs first; empty when none")
|
||||
answer_type: AnswerType = dspy.OutputField(
|
||||
desc="OPEN for a single value, FUNCTION for a formula, INTERVAL for a range, "
|
||||
"CONSTANT for a universal constant, LIST for an enumeration of things, "
|
||||
"DATE for a specific date")
|
||||
|
||||
|
||||
class InitSignature(dspy.Signature):
|
||||
"""You are the INIT step of a reasoning machine. Using ONLY concepts literally
|
||||
present in the question plus a generic planning scaffold (number, method,
|
||||
machine, resources, dependencies), ask: what information or knowledge do I
|
||||
need to answer this? Write 1-4 open subquestions in dependency order.
|
||||
Use answer_type LIST when the subquestion asks for an enumeration of
|
||||
things (which countries, what rivers, list all members...)."""
|
||||
"""You are the INIT step of a reasoning machine. Your job is to make the
|
||||
final answer a direct lookup. Follow this procedure:
|
||||
1. Re-read the question and:
|
||||
1.1. List every word or phrase that could refer to more than one
|
||||
real thing or moment.
|
||||
1.2. Think: what information or knowledge do I need to answer this?
|
||||
2. HIDDEN PRECONDITIONS: for every entity, relation, or value that the
|
||||
question assumes but does not state and that is required to answer
|
||||
it (an implicit owner, role, time window, or intermediate fact),
|
||||
write an explicit subquestion that resolves it. NEVER collapse a
|
||||
hidden precondition into the final subquestion. Always use the most
|
||||
generic term to ask about them.
|
||||
3. Write the subquestion that produces the final answer, with
|
||||
depends_on pointing at the preconditions it needs.
|
||||
Order the subquestions by dependency (1-4 in total).
|
||||
Masked entities like PERSON_1 or ORGANIZATION_1 are ALREADY-RESOLVED named
|
||||
entities from the question — treat each as a known specific entity; do not
|
||||
ask what or who the placeholder is."""
|
||||
question: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField(
|
||||
desc="one subquestion per line, pipe-separated fields: "
|
||||
"text | depends_on (line numbers or 'none') | answer_type (OPEN|FUNCTION|INTERVAL|CONSTANT|LIST)"
|
||||
)
|
||||
subquestions: list[Subquestion] = dspy.OutputField(
|
||||
desc="1-4 subquestions in dependency order; never empty")
|
||||
|
||||
|
||||
class Attendant(str, Enum):
|
||||
"""The closed set of attendants the ROUTE step may pick."""
|
||||
KNOWLEDGE = "knowledge"
|
||||
LOGIC = "logic"
|
||||
ANALYTIC = "analytic"
|
||||
NUMERIC = "numeric"
|
||||
FLOOP = "floop"
|
||||
USER = "user"
|
||||
|
||||
|
||||
class RouteSignature(dspy.Signature):
|
||||
@@ -33,10 +74,22 @@ class RouteSignature(dspy.Signature):
|
||||
question: str = dspy.InputField()
|
||||
catalog: str = dspy.InputField(desc="experts | floop | user, one per line with a summary")
|
||||
evidence: str = dspy.InputField(desc="relevant evidence rows, may be empty")
|
||||
attendant: str = dspy.OutputField(desc="one of: knowledge logic analytic numeric floop user")
|
||||
attendant: Attendant = dspy.OutputField(
|
||||
desc="knowledge: factual lookups from trusted sources; logic: deriving conclusions "
|
||||
"from provided premises, counting over evidence; analytic: equations/symbolic "
|
||||
"relations over provided quantities; numeric: closed arithmetic over provided "
|
||||
"numbers; floop: needs a sub-goal; user: nothing else plausibly answers it")
|
||||
reason: str = dspy.OutputField(desc="one sentence, for the log")
|
||||
|
||||
|
||||
class Confidence(str, Enum):
|
||||
"""The expert's honest self-assessment (baseline draft — no engine
|
||||
verifies the expert yet)."""
|
||||
HIGH = "high"
|
||||
MEDIUM = "medium"
|
||||
LOW = "low"
|
||||
|
||||
|
||||
class ExpertSignature(dspy.Signature):
|
||||
"""You are an expert attendant answering a small, focused subquestion.
|
||||
Use the evidence rows when they answer it; otherwise answer from your own
|
||||
@@ -50,7 +103,9 @@ class ExpertSignature(dspy.Signature):
|
||||
value: str = dspy.OutputField(desc="the answer value in its declared type, or 'UNKNOWN'")
|
||||
source_quote: str = dspy.OutputField(
|
||||
desc="VERBATIM text from the given evidence if the answer comes from it; EMPTY when answering from your own knowledge")
|
||||
confidence: str = dspy.OutputField(desc="high medium low")
|
||||
confidence: Confidence = dspy.OutputField(
|
||||
desc="high: the evidence or your knowledge settles it; medium: plausible "
|
||||
"but not fully settled; low: a guess you would verify first")
|
||||
|
||||
|
||||
class MissingSignature(dspy.Signature):
|
||||
@@ -60,9 +115,8 @@ class MissingSignature(dspy.Signature):
|
||||
the evidence."""
|
||||
goal: str = dspy.InputField()
|
||||
evidence: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField(
|
||||
desc="one subquestion per line, pipe-separated: text | depends_on ('none' or #E refs) | answer_type"
|
||||
)
|
||||
subquestions: list[Subquestion] = dspy.OutputField(
|
||||
desc="1-3 subquestions that would close the gap; empty when nothing helps")
|
||||
|
||||
|
||||
class AnswerSignature(dspy.Signature):
|
||||
@@ -72,7 +126,8 @@ class AnswerSignature(dspy.Signature):
|
||||
marks verification status separately, do not hedge about it."""
|
||||
goal: str = dspy.InputField()
|
||||
evidence: str = dspy.InputField()
|
||||
unverified: str = dspy.InputField(desc="'true' if the prover could not verify derivability")
|
||||
unverified: bool = dspy.InputField(
|
||||
desc="True when the prover could not verify the answer's derivability from the evidence")
|
||||
final_answer: str = dspy.OutputField(desc="answer in natural language; cite only given row ids; no outside facts")
|
||||
|
||||
|
||||
@@ -85,22 +140,76 @@ class FloopModules:
|
||||
self.expert = dspy.Predict(ExpertSignature)
|
||||
self.missing = dspy.Predict(MissingSignature)
|
||||
self.answer = dspy.Predict(AnswerSignature)
|
||||
self.mask = dspy.Predict(EntityMaskSignature)
|
||||
|
||||
def init_decompose(self, question: str) -> tuple[list[dict], str]:
|
||||
"""(parsed subquestions, raw model output). The machine decides what
|
||||
an empty parse means: empty raw = the question is atomic; non-empty
|
||||
raw that parses to nothing = model garbage (run I) — degrade."""
|
||||
pred = self.init(question=question)
|
||||
raw = pred.subquestions or ""
|
||||
return parse_subquestions(raw), raw
|
||||
raw that parses to nothing = model garbage (run I) — degrade.
|
||||
|
||||
Typed output: a response that violates the Subquestion schema raises
|
||||
AdapterParseError AFTER dspy's own JSON re-ask; its lm_response IS
|
||||
the raw garbage — hand it back as the degrade signal.
|
||||
|
||||
ANONYMIZATION (his design): named entities are masked before INIT
|
||||
so the model decomposes shape, not identity — restored in the
|
||||
returned subquestions, deterministically. Identity questions about
|
||||
the placeholders (PR-16 live run: 'who is PERSON_1?') carry a
|
||||
KNOWN answer; the machine seeds them as evidence instead of
|
||||
routing them to an expert."""
|
||||
masked, restore = self.anonymize(question)
|
||||
try:
|
||||
pred = self.init(question=masked)
|
||||
except AdapterParseError as e:
|
||||
return [], (e.lm_response or "unparseable response")
|
||||
subs = []
|
||||
for s in self._subs_from_typed(pred.subquestions):
|
||||
# identity detection on the MASKED text (placeholders still
|
||||
# present); then restore for the machine's question text
|
||||
ans = identity_answer(s["text"], restore)
|
||||
text = restore_mask(s["text"], restore)
|
||||
if ans is not None:
|
||||
s = {**s, "known_answer": ans} # seeded by the machine
|
||||
subs.append({**s, "text": text})
|
||||
return subs, ""
|
||||
|
||||
def anonymize(self, question: str) -> tuple[str, dict]:
|
||||
"""Mask named entities to typed placeholders. No entity found (or the
|
||||
mask call dies) -> the question passes unchanged, mask map empty."""
|
||||
try:
|
||||
pred = self.mask(question=question)
|
||||
entities = pred.entities or []
|
||||
except AdapterParseError:
|
||||
return question, {}
|
||||
masked, restore = apply_mask(question, entities)
|
||||
return masked, restore
|
||||
|
||||
@staticmethod
|
||||
def _subs_from_typed(subs) -> list[dict]:
|
||||
"""Typed Subquestion objects -> machine dicts. A bare number is a
|
||||
line number, never a question (run I law kept)."""
|
||||
out = []
|
||||
for s in (subs or []):
|
||||
text = (s.text or "").strip()
|
||||
if not text or text.isdigit():
|
||||
continue
|
||||
out.append({"text": text, "deps": list(s.depends_on or []),
|
||||
"answer_type": s.answer_type})
|
||||
return out
|
||||
|
||||
def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
return parse_subquestions(pred.subquestions)
|
||||
try:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
except AdapterParseError:
|
||||
return []
|
||||
return self._subs_from_typed(pred.subquestions)
|
||||
|
||||
def route_question(self, question: str, catalog: str, evidence: str) -> tuple[str, str]:
|
||||
"""Typed attendant: the enum is the closed contract. A response
|
||||
outside the set raises AdapterParseError after dspy's re-ask —
|
||||
the machine's invalid-attendant branch stays as a contract guard."""
|
||||
pred = self.route(question=question, catalog=catalog, evidence=evidence)
|
||||
return pred.attendant.strip().lower(), pred.reason.strip()
|
||||
return str(pred.attendant.value), pred.reason.strip()
|
||||
|
||||
def expert_draft(self, question: str, expert_kind: str, evidence: str,
|
||||
parent_question: str = "") -> dict:
|
||||
@@ -109,11 +218,12 @@ class FloopModules:
|
||||
return {
|
||||
"value": pred.value.strip(),
|
||||
"source_quote": pred.source_quote.strip(),
|
||||
"confidence": pred.confidence.strip().lower(),
|
||||
"confidence": str(pred.confidence.value),
|
||||
}
|
||||
|
||||
def synthesize(self, goal: str, evidence: str, unverified: bool) -> str:
|
||||
pred = self.answer(goal=goal, evidence=evidence, unverified="true" if unverified else "false")
|
||||
pred = self.answer(goal=goal, evidence=evidence,
|
||||
unverified=unverified)
|
||||
return pred.final_answer.strip()
|
||||
|
||||
|
||||
@@ -159,4 +269,4 @@ def parse_subquestions(raw: str) -> list[dict]:
|
||||
deps.append(int(tok)) # sibling line number, resolved by the machine
|
||||
atype = next((t for t in AnswerType if t.value == atype_raw), AnswerType.OPEN)
|
||||
out.append({"text": text, "deps": deps, "answer_type": atype})
|
||||
return out
|
||||
return out
|
||||
|
||||
+9
-2
@@ -156,6 +156,7 @@ _STAGE_BY_MODULE = {
|
||||
"Expert": "EXPERT",
|
||||
"Missing": "MISSING",
|
||||
"Answer": "ANSWER",
|
||||
"EntityMaskSignature": "MASK",
|
||||
"KnowledgeExpert": "knowledge",
|
||||
"InitSignature": "INIT",
|
||||
"RouteSignature": "ROUTE",
|
||||
@@ -164,16 +165,20 @@ _STAGE_BY_MODULE = {
|
||||
"AnswerSignature": "ANSWER",
|
||||
"ExtractSignature": "EXTRACT",
|
||||
"AnswerFromKG": "answer_kg",
|
||||
"TranslateSignature": "TRANSLATE",
|
||||
"SelectTableSignature": "SELECT_TABLE",
|
||||
"VerifyCountSignature": "VERIFY_COUNT",
|
||||
"SkimPromoteSignature": "PROMOTE",
|
||||
}
|
||||
|
||||
|
||||
def configure_lm() -> dict:
|
||||
def configure_lm(no_cache: bool = False) -> dict:
|
||||
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
|
||||
|
||||
no_cache=True builds the LM with dspy's response cache DISABLED for this
|
||||
process (his ruling 25/10: the cache is caching doing its job — the
|
||||
default stays cache=True; the flag exists for A/B and freshness testing
|
||||
so a repeated question is a real run, not a byte-identical replay).
|
||||
|
||||
Returns the active provider settings (for provenance logs).
|
||||
"""
|
||||
cfg = _load_yaml()["lm"]
|
||||
@@ -190,6 +195,8 @@ def configure_lm() -> dict:
|
||||
"temperature": p["temperature"],
|
||||
"api_key": os.environ.get(p.get("api_key_env", ""), "empty"),
|
||||
}
|
||||
if no_cache:
|
||||
kwargs["cache"] = False
|
||||
lm = dspy.LM(**kwargs)
|
||||
global _ACTIVE
|
||||
_ACTIVE = lm
|
||||
|
||||
+282
-15
@@ -16,6 +16,8 @@ from dataclasses import dataclass, field
|
||||
|
||||
from .engine import CATALOG, LLMExpertEngine, UserRequestEngine
|
||||
from .setops import detect_setop, setop_row
|
||||
from .branches import (BranchManager, BranchResult, BranchSpec, BranchView,
|
||||
DEAD_END, open_subtree)
|
||||
from .dspy_modules import FloopModules
|
||||
from .state import (AnswerType, Budget, BudgetExhausted, EvidenceRow,
|
||||
EvidenceTable, OpenQuestion, QuestionStack, instantiate)
|
||||
@@ -23,6 +25,16 @@ from .stream import RunStreams
|
||||
|
||||
EXPERT_ENGINES = ("knowledge", "logic", "analytic", "numeric")
|
||||
|
||||
_YEAR_RE = re.compile(r"\b(?:1[5-9]\d{2}|20\d{2}|2[1-9]\d{2})\b") # 1500–2999
|
||||
|
||||
|
||||
def _looks_like_date(v: str) -> bool:
|
||||
"""Deterministic DATE admission: the value must carry a plausible
|
||||
year (1500-2999). '2 June 2018', 'June 2018', '2018' pass; a bare
|
||||
'15' — or a month name alone — is NOT a date and must never
|
||||
satisfy a DATE question (his 22/10 local run)."""
|
||||
return bool(_YEAR_RE.search(v or ""))
|
||||
|
||||
|
||||
def _fmt_num(x: float) -> str:
|
||||
"""Deterministic number formatting for computed rows: integers plain,
|
||||
@@ -91,6 +103,13 @@ class FloopRun:
|
||||
self.knowledge_engine = knowledge_engine # None -> baseline LLM expert
|
||||
self.notes: list[str] = []
|
||||
self.engine_calls = 0
|
||||
# BRANCHING (his design, 22-23/10): the fork bookkeeping. Specs are
|
||||
# created lazily (only when a dependent of an ambiguous row exists);
|
||||
# the shared table/stack stay THE run's own — a branch reads the
|
||||
# table through a BranchView that binds the ambiguous row to its
|
||||
# reading and hides other branches' rows.
|
||||
self.branches = BranchManager()
|
||||
self._current_branch = "" # "" = the root run; else the branch id
|
||||
# RE-ASK METER (run L): dspy's adapter fallback fires extra LM calls
|
||||
# the budget never charged. The prompt-log callback sees them; wire
|
||||
# its meter to our budget so the count is honest. The BEHAVIOUR of
|
||||
@@ -124,6 +143,14 @@ class FloopRun:
|
||||
self._init_decompose()
|
||||
while True:
|
||||
try:
|
||||
# BRANCHING: a fork pending means an ambiguous row gained a
|
||||
# dependent — its readings each own a world now. Run the
|
||||
# branches to their end BEFORE the main loop continues
|
||||
# (their conclusions/notes land in the shared table/notes;
|
||||
# the conditional render happens at _finish).
|
||||
while self.branches.pending:
|
||||
spec = self.branches.pending[0]
|
||||
self._run_branch(spec)
|
||||
q = self.stack.pickable(self.table)
|
||||
if q is None:
|
||||
if self.stack.all_terminal():
|
||||
@@ -192,6 +219,26 @@ class FloopRun:
|
||||
if isinstance(tok, int) and 1 <= tok <= len(created):
|
||||
resolved.append(created[tok - 1].qid)
|
||||
q.deps = resolved
|
||||
# anonymization seeds (his design): identity questions the mask map
|
||||
# already answers land as evidence NOW — zero LLM calls. WARN on
|
||||
# screen AND log (his 23/10 ask): the machine auto-answered a
|
||||
# question without any expert — legible, and a self-improvement
|
||||
# signal (which phrasings the seed eats -> META's lessons bank).
|
||||
for q, s in zip(created, subs):
|
||||
if s.get("known_answer"):
|
||||
self.table.append(EvidenceRow(
|
||||
qid=q.qid, answer_type=q.answer_type,
|
||||
payload={"value": s["known_answer"],
|
||||
"quote": f"{s['known_answer']} — named in the question itself"},
|
||||
engine="mask:seed", trace=["anonymization: placeholder resolved from the mask map"],
|
||||
provenance={}, verified=True))
|
||||
q.status = "answered"
|
||||
q.reason = "identity seeded from the mask map"
|
||||
self.notes.append(
|
||||
f"{q.qid}: seeded from anonymization — no expert call needed")
|
||||
self.streams.warn(
|
||||
f"SEED auto-answered {q.qid} '{q.text[:60]}' -> "
|
||||
f"'{s['known_answer']}' (mask map; zero expert calls)")
|
||||
|
||||
# ---- fan-out (the planner's expansion; deterministic guard) --------------
|
||||
|
||||
@@ -349,6 +396,135 @@ class FloopRun:
|
||||
note=(f"partial: {len(nums)} of {len(entity_rows)} values summed"
|
||||
if partial else ""))
|
||||
|
||||
def _run_branch(self, spec: BranchSpec) -> None:
|
||||
"""Execute ONE branch to its end, inside this run.
|
||||
|
||||
The branch is a NESTED LOOP SESSION, not a child FloopRun: it
|
||||
swaps the machine's table view (BranchView binds the ambiguous
|
||||
row to this branch's reading, hides other branches' rows) and
|
||||
question stack (the dependent questions re-asked inside this
|
||||
world), runs the same fixed loop, and restores state after.
|
||||
Acquired knowledge (rows) lands in the SHARED table tagged with
|
||||
the branch id; notes and engine_calls accumulate on the run; the
|
||||
budget is the run's own (shared pool — his design: llm_calls
|
||||
pool shared, depth+1 burns the existing depth counter).
|
||||
|
||||
Death: contradiction (a checked arrival refuses the branch's
|
||||
values — the row lands with value UNKNOWN and its questions
|
||||
fail), dead end (the branch's terminal questions all failed),
|
||||
or natural merge (its answer equals an earlier branch's —
|
||||
recorded at survivors()). Never an absurdity judge.
|
||||
"""
|
||||
view = BranchView(self.table, spec)
|
||||
self.streams.warn(
|
||||
f"BRANCH {spec.id} starts: reading '{spec.value[:60]}' "
|
||||
f"(bound from {spec.ambiguous_eid})")
|
||||
main_table, main_stack = self.table, self.stack
|
||||
main_branch = self._current_branch
|
||||
self.table = view # type: ignore[assignment]
|
||||
self._current_branch = spec.id
|
||||
# the branch's stack: the dependent subtree FROZEN at fork time —
|
||||
# the same question set for every branch of the fork (B1 consuming
|
||||
# the originals changed nothing about what B2 copies). Copied
|
||||
# inside this world with BRANCH-SCOPED qids (a collision would make
|
||||
# a copy look already-answered) and deps rewired to the copies.
|
||||
branch_stack = QuestionStack(spec.value)
|
||||
by_orig = {q.qid: q for q in main_stack.items}
|
||||
copies_by_orig: dict[str, str] = {}
|
||||
for orig_qid in spec.subtree_qids:
|
||||
orig = by_orig.get(orig_qid)
|
||||
if orig is None:
|
||||
continue
|
||||
nq = branch_stack.add(OpenQuestion(
|
||||
text=orig.text, answer_type=orig.answer_type,
|
||||
deps=[], reason=f"branch {spec.id} of {orig_qid}"))
|
||||
nq.qid = f"{spec.id}.{orig_qid}"
|
||||
# deps: the ambiguous row is BOUND (present in the view with its
|
||||
# reading fixed — not a dependency anymore); deps on copied
|
||||
# siblings point at the COPIES; deps on other already-answered
|
||||
# questions keep the reference (their rows live in the shared table)
|
||||
nq.deps = [copies_by_orig.get(d, d) for d in orig.deps
|
||||
if d != spec.ambiguous_qid]
|
||||
copies_by_orig[orig_qid] = nq.qid
|
||||
for q in main_stack.items:
|
||||
if q.qid in copies_by_orig:
|
||||
q.status = "answered"
|
||||
q.reason = f"answered by branches over {spec.ambiguous_qid}"
|
||||
self.stack = branch_stack # type: ignore[assignment]
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
# NESTED FORK: an ambiguous row inside this branch with
|
||||
# its own dependent opens sub-branches (origin=this
|
||||
# branch); run them to their end before continuing —
|
||||
# the same lazy law, one level deeper.
|
||||
while any(s.origin == spec.id
|
||||
for s in self.branches.pending):
|
||||
sub = next(s for s in self.branches.pending
|
||||
if s.origin == spec.id)
|
||||
self._run_branch(sub)
|
||||
q = self.stack.pickable(self.table)
|
||||
if q is None:
|
||||
if self.stack.all_terminal():
|
||||
break
|
||||
if self.budget.missing_used >= self.budget.missing_extensions:
|
||||
self.notes.append(
|
||||
"missing-extension limit reached inside a branch")
|
||||
break
|
||||
self._missing_round()
|
||||
continue
|
||||
self._route_and_execute(q)
|
||||
except BudgetExhausted:
|
||||
self.notes.append(
|
||||
f"budget exhausted inside branch {spec.id} "
|
||||
f"at llm_calls={self.budget.llm_calls}")
|
||||
break
|
||||
except Exception as e: # noqa: BLE001
|
||||
if _lm_dead(e):
|
||||
self.notes.append(
|
||||
f"LM unreachable inside branch {spec.id}; "
|
||||
f"branch aborted honestly")
|
||||
break
|
||||
raise
|
||||
# the branch's conclusion. A branch whose OWN children
|
||||
# answered carries the CHILDREN's conditional as its answer
|
||||
# (nesting composes); otherwise synthesize from its rows.
|
||||
answer = ""
|
||||
kids = [s for s in self.branches.specs if s.origin == spec.id]
|
||||
if kids and branch_stack.open_count() == 0:
|
||||
answer = self.branches.conditional_answer(self.query, origin=spec.id)
|
||||
if answer and not answer.startswith("No reading"):
|
||||
self.branches.record_answer(spec.id, answer)
|
||||
self.streams.state(
|
||||
f"branch {spec.id} concluded (nested, "
|
||||
f"{len(kids)} sub-branches): {answer[:80]}", think=True)
|
||||
else:
|
||||
self.branches.record_dead(spec.id)
|
||||
self.notes.append(
|
||||
f"branch {spec.id}: dead — no sub-reading survived")
|
||||
elif (branch_stack.open_count() == 0 and branch_stack.items[1:]
|
||||
and any(i.status == "answered"
|
||||
for i in branch_stack.items[1:])):
|
||||
try:
|
||||
self._charge()
|
||||
answer = self.modules.synthesize(
|
||||
self.query, view.dump(), unverified=True)
|
||||
self.branches.record_answer(spec.id, answer)
|
||||
self.streams.state(
|
||||
f"branch {spec.id} concluded: {answer[:80]}", think=True)
|
||||
except (BudgetExhausted, Exception) as e: # noqa: BLE001
|
||||
self.branches.record_dead(spec.id)
|
||||
self.notes.append(f"branch {spec.id}: synthesis failed ({e})")
|
||||
else:
|
||||
self.branches.record_dead(spec.id)
|
||||
self.notes.append(
|
||||
f"branch {spec.id}: dead — no reading survived "
|
||||
f"(all dependents failed)")
|
||||
finally:
|
||||
self.table = main_table
|
||||
self.stack = main_stack
|
||||
self._current_branch = main_branch
|
||||
|
||||
def _route_and_execute(self, q: OpenQuestion) -> None:
|
||||
# SETOP GUARD: a count over list rows already in evidence is
|
||||
# computation, not routing — the machine computes it deterministically
|
||||
@@ -465,6 +641,16 @@ class FloopRun:
|
||||
# fan-out bookkeeping: entity rows carry the group so the join finds them
|
||||
if q.fan_group:
|
||||
row.provenance["fan_group"] = q.fan_group
|
||||
# DATE type check (his 22/10 local run: term-start answered '15'):
|
||||
# deterministic — a DATE value must carry a year; bare numbers
|
||||
# are not dates and must never satisfy a DATE question
|
||||
if q.answer_type == AnswerType.DATE:
|
||||
v = str(row.payload.get("value", ""))
|
||||
if not _looks_like_date(v):
|
||||
self.notes.append(
|
||||
f"{q.qid}: DATE answer rejected (no year): {v[:60]!r}")
|
||||
row.payload["value"] = "UNKNOWN"
|
||||
row.payload["note"] = "rejected: DATE without a year"
|
||||
# PR-3: skim notices also land in the run notes — legibility law:
|
||||
# derived answers render CONTENT, not counts alone
|
||||
for n in (row.payload.get("skim") or [])[:2]:
|
||||
@@ -478,6 +664,25 @@ class FloopRun:
|
||||
f"other readings: " + "; ".join(
|
||||
a.get("value") for a in alts[:3]))
|
||||
self.table.append(row)
|
||||
# BRANCHING TRIGGER (his design): an ambiguous row with an OPEN
|
||||
# dependent subtree forks the run into one branch per reading —
|
||||
# LAZY (empty subtree: no fork, the ambiguity stays a note, the
|
||||
# pick rides), the subtree FROZEN here so every branch of the
|
||||
# fork copies the same questions (the first branch consuming the
|
||||
# originals must not change what the second copies).
|
||||
if row.payload.get("ambiguous"):
|
||||
subtree = open_subtree(self.stack, q.qid)
|
||||
if subtree:
|
||||
specs = self.branches.fork_specs(
|
||||
row, origin=self._current_branch, subtree_qids=subtree)
|
||||
if specs:
|
||||
self.notes.append(
|
||||
f"{q.qid}: forking {len(specs)} branches over the "
|
||||
f"readings of {row.eid}: "
|
||||
+ "; ".join(f"{s.id}={s.value[:40]}" for s in specs))
|
||||
self.streams.warn(
|
||||
f"FORK {q.qid} over {row.eid}: {len(specs)} readings "
|
||||
f"-> branches {', '.join(s.id for s in specs)}")
|
||||
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
|
||||
q.status = "failed"
|
||||
q.reason = "expert returned UNKNOWN"
|
||||
@@ -526,25 +731,87 @@ class FloopRun:
|
||||
def _finish(self, t0: float) -> RunReport:
|
||||
verified = False # STUB prover — v0.2: derivability check (clingo/Z3)
|
||||
answer = ""
|
||||
try:
|
||||
self._charge()
|
||||
self.streams.call("ANSWER", f"synthesize answer for: {self.query[:80]}",
|
||||
think=self.tprefix + "writing the answer from the evidence table")
|
||||
answer = self.modules.synthesize(
|
||||
self.query, self.table.dump(), unverified=not verified)
|
||||
# CLARIFICATION FIRST (his 23/10 run): a run that ASKED THE USER
|
||||
# something ends IN THE QUESTION — composed by fixed code from the
|
||||
# pending user rows, never by a synthesis prompt reading
|
||||
# needs_user_input as plain text and inventing 'the evidence is
|
||||
# unknown'. The branch answer handles ambiguity (its readings);
|
||||
# this handles every OTHER honest defer: the machine knows what
|
||||
# it wants to ask — it says so, and only that.
|
||||
pending_user = [r for r in self.table.rows()
|
||||
if r.note == "needs_user_input" and not r.retracted]
|
||||
if self.branches.specs:
|
||||
# CONDITIONAL ANSWER (run L law): several readings survived —
|
||||
# the answer is composed by FIXED CODE from the branch results,
|
||||
# never by one synthesis prompt choosing a reading inside itself.
|
||||
answer = self.branches.conditional_answer(self.query)
|
||||
self.streams.final(answer)
|
||||
except BudgetExhausted:
|
||||
self.notes.append("budget died before the answer step")
|
||||
except Exception as e: # noqa: BLE001 — a dead LM answers nothing
|
||||
if _lm_dead(e):
|
||||
self.notes.append(f"LM unreachable before synthesis ({type(e).__name__}); "
|
||||
"evidence is kept, the answer is not written")
|
||||
else:
|
||||
raise
|
||||
self.notes.append(
|
||||
f"conditional answer over {len(self.branches.specs)} branches: "
|
||||
+ "; ".join(f"{s.id}={self.branches.results[s.id].status}"
|
||||
for s in self.branches.specs))
|
||||
elif pending_user:
|
||||
answer = self._clarify_answer(pending_user)
|
||||
self.streams.final(answer)
|
||||
self.notes.append("answer: clarification requested from the user")
|
||||
else:
|
||||
try:
|
||||
self._charge()
|
||||
self.streams.call("ANSWER", f"synthesize answer for: {self.query[:80]}",
|
||||
think=self.tprefix + "writing the answer from the evidence table")
|
||||
answer = self.modules.synthesize(
|
||||
self.query, self.table.dump(), unverified=not verified)
|
||||
self.streams.final(answer)
|
||||
except BudgetExhausted:
|
||||
self.notes.append("budget died before the answer step")
|
||||
except Exception as e: # noqa: BLE001 — a dead LM answers nothing
|
||||
if _lm_dead(e):
|
||||
self.notes.append(f"LM unreachable before synthesis ({type(e).__name__}); "
|
||||
f"evidence is kept, the answer is not written")
|
||||
else:
|
||||
raise
|
||||
return RunReport(
|
||||
goal=self.query, final_answer=answer, verified=verified,
|
||||
llm_calls=self.budget.llm_calls, engine_calls=self.engine_calls,
|
||||
depth=self.depth, notes=self.notes,
|
||||
questions=[(i.qid, i.status, i.text) for i in self.stack.items],
|
||||
evidence_rows=self.table.dump().splitlines(),
|
||||
elapsed_s=round(time.time() - t0, 1))
|
||||
elapsed_s=round(time.time() - t0, 1))
|
||||
|
||||
def _clarify_answer(self, pending_user: list[EvidenceRow]) -> str:
|
||||
"""The run ends in its QUESTION to the user, composed by fixed
|
||||
code. Each pending user row carries the instantiated question its
|
||||
ROUTE deferred (the row's qid names the open question); the
|
||||
answer asks them, names what the machine already holds so the
|
||||
user answers with context, and states what was left un-answered.
|
||||
Zero LLM calls — the question text was already composed by the
|
||||
loop; this renders it."""
|
||||
parts: list[str] = []
|
||||
for r in pending_user:
|
||||
q = next((i for i in self.stack.items if i.qid == r.qid), None)
|
||||
qtext = q.text if q is not None else "(deferred question)"
|
||||
# what the machine holds that motivated the ask — the row the
|
||||
# deferring question depended on, rendered plain (value +
|
||||
# ambiguity note when present)
|
||||
context = ""
|
||||
if q is not None:
|
||||
for d in q.deps:
|
||||
for dep in self.table.for_question(d):
|
||||
val = str(dep.payload.get("value", ""))
|
||||
if not val or val.upper() == "UNKNOWN":
|
||||
continue
|
||||
if dep.payload.get("ambiguous"):
|
||||
alts = dep.payload.get("alternatives") or []
|
||||
others = " / ".join(
|
||||
a.get("value", "") for a in alts[:3])
|
||||
context = (f" (so far: {val} — but other "
|
||||
f"defensible readings exist: {others})")
|
||||
else:
|
||||
context = f" (so far: {val})"
|
||||
break
|
||||
if context:
|
||||
break
|
||||
parts.append(f"I need to ask you: {qtext}{context}")
|
||||
if len(parts) == 1:
|
||||
return parts[0]
|
||||
return "I need to ask you a few things: " + " | ".join(parts)
|
||||
@@ -20,6 +20,7 @@ class AnswerType(str, Enum):
|
||||
INTERVAL = "INTERVAL"
|
||||
CONSTANT = "CONSTANT"
|
||||
LIST = "LIST"
|
||||
DATE = "DATE"
|
||||
|
||||
|
||||
class BudgetExhausted(Exception):
|
||||
|
||||
@@ -83,6 +83,15 @@ class RunStreams:
|
||||
if think:
|
||||
self.think_line(text)
|
||||
|
||||
def warn(self, text: str) -> None:
|
||||
"""A machine judgement worth a human's eye even non-verbose:
|
||||
the seed that auto-answered a question, a guard refusing an
|
||||
ingest, a budget starvation. Self-improvement signal (META.md):
|
||||
the offline analysis counts these first. Log always; screen
|
||||
ALWAYS (unlike thinking, the [W] line is the point)."""
|
||||
self._emit_log(f"WARNING {text}")
|
||||
print(f"[W] {text}", flush=True)
|
||||
|
||||
def final(self, text: str) -> None:
|
||||
self._emit_log(f"FINAL {text}")
|
||||
self.think_line(f"[FINAL] {text}")
|
||||
|
||||
@@ -118,8 +118,13 @@ One routed knowledge question = one internal pipeline run, bounded by budget:
|
||||
```
|
||||
question instantiate (already done by the machine)
|
||||
│
|
||||
▼ TRANSLATE (LLM): question + answer_type → retrieval focus:
|
||||
│ keywords, entry entities, what shape of fact closes the gap
|
||||
▼ COMPOSE (engine, 23/10 — the old TRANSLATE LLM removed): question ∪
|
||||
│ evidence → queries + entity terms. Every token traces to the
|
||||
│ question or an evidence row; the model's own knowledge of the
|
||||
│ entities can no longer steer retrieval (it was putting the
|
||||
│ ANSWER into queries). Top-N asks slice the first N evidence
|
||||
│ members by source order; enumerations get the list-article
|
||||
│ shape ('List of rivers of Italy').
|
||||
▼ KG PROBE (engine): BFS from seeds → candidate edges + linked quotes
|
||||
│ gap report: is the question's answer_type coverable from what's found?
|
||||
│ YES → skip gather, go to SELECT
|
||||
@@ -135,10 +140,14 @@ question instantiate (already done by the machine)
|
||||
▼ return: top-k rows payload {quote, url, access_date, kg_corroboration}
|
||||
```
|
||||
|
||||
LLM calls: TRANSLATE, EXTRACT-per-chunk (+ retries), and nothing else — the
|
||||
probe, search, chunking, checking, merging, selecting are all engines. That is
|
||||
the law compliance: the LLM translates; deterministic code decides what is
|
||||
valid, what is dedupe, what is ranked.
|
||||
LLM calls: EXTRACT-per-chunk (+ retries), SELECT TABLE (lists), VERIFY
|
||||
COUNT, SKIM PROMOTE, and ANSWER — and nothing else. The query
|
||||
composition, probe, search, chunking, checking, merging, selecting are
|
||||
all engines. That is the law compliance: the LLM translates; deterministic
|
||||
code decides what is valid, what is dedupe, what is ranked — and since
|
||||
23/10 even the retrieval focus is code (the old TRANSLATE LLM became
|
||||
`knowledge/queries.py`: every query token traces to question ∪ evidence,
|
||||
so no model weight ever steers retrieval).
|
||||
|
||||
## 5. Context budget & chunking (the 16–32k constraint)
|
||||
|
||||
@@ -307,9 +316,10 @@ against the stored table text — the same string the parser produced — so the
|
||||
check stays verbatim and deterministic. The wikitext raw form is kept in the
|
||||
document artifact for audit.
|
||||
|
||||
**Budget law in the LIST path.** TRANSLATE + SELECT TABLE are the only LLM
|
||||
calls (2 + retries); ingestion and aggregation are free. A 500-row table
|
||||
costs the same LLM budget as a 5-row one — the cost of an enumeration is
|
||||
**Budget law in the LIST path.** SELECT TABLE (and the optional VERIFY
|
||||
COUNT) are the only LLM calls; ingestion and aggregation are free (the
|
||||
query composition is engine since 23/10). A 500-row table costs the
|
||||
same LLM budget as a 5-row one — the cost of an enumeration is
|
||||
O(1) in the size of the list.
|
||||
|
||||
## 12. Answer-level verification — the CHECK step for answers (2026-10-19)
|
||||
|
||||
+77
-68
@@ -1,7 +1,7 @@
|
||||
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
|
||||
|
||||
Per question (one routed knowledge call):
|
||||
1. TRANSLATE: question -> retrieval focus (keywords/entities) [LLM, cheap]
|
||||
1. COMPOSE: question + evidence -> queries/entities [engine]
|
||||
2. KG PROBE: lexical seed match + BFS depth-1 [engine]
|
||||
3. gap? -> SEARCH en.wikipedia (official search) [engine]
|
||||
4. FETCH top articles, CHUNK by sections [engine]
|
||||
@@ -25,14 +25,53 @@ from .checks import check_candidate, quote_containment
|
||||
from .chunker import chunk_page
|
||||
from .skim import find_quantities, skim_article
|
||||
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
|
||||
SkimPromoteSignature, TranslateSignature,
|
||||
VerifyCountSignature)
|
||||
SkimPromoteSignature, VerifyCountSignature)
|
||||
from .queries import compose_queries, keywords, proper_nouns
|
||||
from .store import KnowledgeStore, norm_name
|
||||
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
||||
tables_as_chunks, format_table_frag, parse_stop_table)
|
||||
|
||||
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||
|
||||
# (K5) bug (run 085457, 24-25/10): glm-5.3-flash glues row citations and
|
||||
# glosses onto the value field (AnswerFromKG says "cite rows by id" but has
|
||||
# no citation output field, so the model cites in the only field it has).
|
||||
# Three live shapes, stripped at the judge's output boundary — BEFORE the
|
||||
# evidence payload and the ablation audit see the value:
|
||||
# "... (K5)" — row-id citation suffix
|
||||
# "... (…; cited from rows K16 and K30)" — parenthetical gloss citing rows
|
||||
# "15 (list of 15 members: …)" — the LIST path's own gloss of a count
|
||||
# Trailing-only, marker-anchored: "(PSOE)" inside a name, "(since 2018)",
|
||||
# "(Presidente del Gobierno)" are legitimate and MUST survive. Fixed code
|
||||
# cleans the model's proposal (LLMs propose, code decides — the audit's
|
||||
# _carries then finds the support rows and the ambiguity audit can run).
|
||||
_ROW_CITATION_RE = re.compile(
|
||||
r"\s*\(\s*(?:row\s+|rows\s+)?K\d+(?:\s*(?:,|and|;)\s*K?\d+)*\s*\)\s*$",
|
||||
re.IGNORECASE)
|
||||
_ROW_CITED_GLOSS_RE = re.compile(
|
||||
r"\s*\([^()]*\bcited from (?:row|rows)\b[^()]*\)\s*$",
|
||||
re.IGNORECASE)
|
||||
_LIST_GLOSS_RE = re.compile(
|
||||
r"\s*\(\s*list of\b[^()]*\)\s*$",
|
||||
re.IGNORECASE)
|
||||
|
||||
|
||||
def _clean_value(value: str) -> str:
|
||||
"""Strip trailing citation/gloss parentheticals from a judge value.
|
||||
|
||||
The boundary law: only TRAILING shapes with a citation/list marker are
|
||||
touched; mid-value text and legitimate parentheticals are the model's
|
||||
own words and stay. Idempotent by construction (a cleaned value ends
|
||||
clean). UNKNOWN and empty pass through untouched.
|
||||
"""
|
||||
v = (value or "").strip()
|
||||
if not v or v.upper() == "UNKNOWN":
|
||||
return v
|
||||
for rx in (_ROW_CITATION_RE, _ROW_CITED_GLOSS_RE, _LIST_GLOSS_RE):
|
||||
v = rx.sub("", v).rstrip()
|
||||
return v.strip()
|
||||
|
||||
|
||||
# header/caption terms that name the ENTITY column of a typical scalar table
|
||||
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
|
||||
|
||||
@@ -90,16 +129,10 @@ def _prop_hit(prop: str, toks: set[str]) -> bool:
|
||||
|
||||
|
||||
def _proper_nouns(question: str) -> set[str]:
|
||||
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the
|
||||
question. The definitive guard for 'which are the three longest rivers
|
||||
of Italy?' never accepting a world table (run H: Q1 answered Nile/
|
||||
Amazon/Yangtze because the top search hit was the world list and the
|
||||
disjointness guard was vacuous — no evidence, nothing to check)."""
|
||||
words = re.findall(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?", question or "")
|
||||
stops = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
|
||||
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
|
||||
"Their", "Its", "Those", "These", "That", "This"}
|
||||
return {w for w in words if w not in stops}
|
||||
"""The subject guard's noun extractor — delegates to knowledge/queries.py
|
||||
(single source: the query composer and the guards share the NE law).
|
||||
Semantics unchanged: capitalized non-question words ('Italy', 'Po')."""
|
||||
return proper_nouns(question)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -130,7 +163,6 @@ class KnowledgeExpert:
|
||||
self.streams = streams
|
||||
self.extract = dspy.Predict(ExtractSignature)
|
||||
self.answer = dspy.Predict(AnswerFromKG)
|
||||
self.translate = dspy.Predict(TranslateSignature)
|
||||
self.select_table = dspy.Predict(SelectTableSignature)
|
||||
self.verify_count = dspy.Predict(VerifyCountSignature)
|
||||
self.skim_promote = dspy.Predict(SkimPromoteSignature)
|
||||
@@ -150,16 +182,10 @@ class KnowledgeExpert:
|
||||
|
||||
@staticmethod
|
||||
def _keywords(question: str, k: int = 6) -> list[str]:
|
||||
"""Deterministic lexical focus: content words of the question (draft)."""
|
||||
stops = {"what", "which", "who", "when", "where", "is", "are", "was", "were",
|
||||
"the", "of", "in", "on", "at", "a", "an", "and", "or", "to", "for",
|
||||
"does", "do", "did", "by", "its", "it", "that", "this", "most", "second"}
|
||||
words = [w.lower() for w in WORD_RE.findall(question)]
|
||||
seen: list[str] = []
|
||||
for w in words:
|
||||
if w not in stops and len(w) > 2 and w not in seen:
|
||||
seen.append(w)
|
||||
return seen[:k]
|
||||
"""Deterministic lexical focus — delegates to knowledge/queries.py
|
||||
(single source: the probe seeds and the query composer share the
|
||||
same keyword law)."""
|
||||
return keywords(question, k)
|
||||
|
||||
def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None:
|
||||
"""The membership set (if any) this question may be served from.
|
||||
@@ -211,9 +237,9 @@ class KnowledgeExpert:
|
||||
question + parent + referenced rows in). References like 'that state'
|
||||
resolve against them."""
|
||||
t0 = time.time()
|
||||
context = (f"Original question: {parent_question}" if parent_question else "")
|
||||
if evidence:
|
||||
context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}"
|
||||
# parent_question/evidence ARE the machine's context (design §4) —
|
||||
# consumed directly by the probe seeds, the query composer and the
|
||||
# guards; no prompt ever renders them into a TRANSLATE call anymore.
|
||||
kws = self._keywords(question)
|
||||
goal_terms = self._keywords(parent_question) if parent_question else []
|
||||
self._current_goal_terms = goal_terms # the harvest reads these
|
||||
@@ -263,25 +289,15 @@ class KnowledgeExpert:
|
||||
return {**self._audit_ambiguity(question, answer, rows, charge_llm),
|
||||
"source": "knowledge_graph", "kg_rows": len(rows)}
|
||||
|
||||
# 3-4. gap -> search + fetch. TRANSLATE (LLM) first: the question becomes
|
||||
# entity-first Wikipedia queries — deterministic keywords alone surface
|
||||
# list articles and miss demographics pages.
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = self.translate(question=question, context=context)
|
||||
q_raw = (pred.queries or "").strip()
|
||||
queries = [q.strip() for q in
|
||||
next((ln.split(":", 1)[1] for ln in q_raw.splitlines()
|
||||
if ln.strip().upper().startswith("QUERIES")), q_raw).split(",")
|
||||
if q.strip()][:2]
|
||||
if not queries:
|
||||
queries = [" ".join(kws[:3])]
|
||||
e_raw = (pred.entities or "").strip()
|
||||
entity_terms = [t.strip() for t in
|
||||
next((ln.split(":", 1)[1] for ln in e_raw.splitlines()
|
||||
if ln.strip().upper().startswith("ENTITIES")), e_raw).split(",")
|
||||
if t.strip()][:4]
|
||||
self._log(f"translate -> queries {queries} entities {entity_terms}", think=True)
|
||||
# 3-4. gap -> search + fetch. COMPOSE (deterministic — the old
|
||||
# TRANSLATE LLM, 23/10): queries from question ∪ evidence only;
|
||||
# the model's own knowledge of the entities can no longer steer
|
||||
# retrieval (it was putting the ANSWER into queries: 'Pedro
|
||||
# Sánchez 2018 investiture…' for a term-start question).
|
||||
queries, entity_terms = compose_queries(
|
||||
question, evidence_entities=ev_entities, list_mode=list_mode)
|
||||
self._log(f"compose -> queries {queries} entities {entity_terms}",
|
||||
think=True)
|
||||
|
||||
# search ALL queries first; merge + dedupe candidates; rank GLOBALLY
|
||||
# by title relevance; then fetch one at a time with early exit
|
||||
@@ -647,22 +663,19 @@ class KnowledgeExpert:
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = self.select_table(question=question, tables=rendered)
|
||||
idx_raw = (pred.table_index or "").strip()
|
||||
if not idx_raw or idx_raw.upper() in ("NONE", "N/A", "0"):
|
||||
return None
|
||||
try:
|
||||
idx = int(re.findall(r"\d+", idx_raw)[0])
|
||||
except (ValueError, IndexError):
|
||||
chosen = pred.chosen
|
||||
if chosen is None:
|
||||
return None
|
||||
idx = chosen.table_index
|
||||
table = next((t for t in page.tables if t.idx == idx), None)
|
||||
if table is None:
|
||||
return None
|
||||
page._list_table_idx = idx # the harvest skips the LIST answer's table
|
||||
column = (pred.column or "").strip()
|
||||
column = chosen.column.strip()
|
||||
col_i = next((i for i, h in enumerate(table.header)
|
||||
if column.casefold() in h.casefold()), 0)
|
||||
set_name = (pred.set_name or "").strip() or question[:60]
|
||||
origin_question = (pred.origin_question or "").strip() or question
|
||||
set_name = chosen.set_name.strip() or question[:60]
|
||||
origin_question = question
|
||||
# INGEST ALL ROWS: one membership edge per row, quote = the full
|
||||
# stored row line, containment against the stored table text
|
||||
doc_id = self.store.add_document(
|
||||
@@ -888,16 +901,12 @@ class KnowledgeExpert:
|
||||
entities=", ".join(expected[:8]),
|
||||
tables="\n".join(rendered))
|
||||
promoted = 0
|
||||
for line in (pred.decision or "").strip().splitlines():
|
||||
m = re.match(r"\s*(\d+)\s*:\s*(YES|NO)\s*(.*)$", line.strip(),
|
||||
flags=re.I)
|
||||
if not m:
|
||||
continue
|
||||
idx, verdict, col = int(m.group(1)), m.group(2).upper(), m.group(3).strip()
|
||||
got = lookup.get(idx)
|
||||
if verdict != "YES" or got is None:
|
||||
for d in (pred.decisions or []):
|
||||
got = lookup.get(d.table_index)
|
||||
if not d.promote or got is None:
|
||||
continue
|
||||
page, t = got
|
||||
col = (d.column or "").strip()
|
||||
ent_i = next((i for i, h in enumerate(t.header)
|
||||
if h.casefold() in _ENTITY_COL), 0)
|
||||
val_i = next((i for i, h in enumerate(t.header)
|
||||
@@ -906,13 +915,13 @@ class KnowledgeExpert:
|
||||
continue
|
||||
overlap, nm = self._entity_overlap_count(t, ent_i, expected)
|
||||
if expected and overlap == 0 and nm >= 2:
|
||||
self._log(f"skim promote: table {idx} ({page.title}): LLM said "
|
||||
self._log(f"skim promote: table {d.table_index} ({page.title}): LLM said "
|
||||
f"YES but {overlap}/{nm} entity overlap — refused",
|
||||
think=True)
|
||||
continue
|
||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||
if merged:
|
||||
self._log(f"skim promote: {merged} rows of table {idx} "
|
||||
self._log(f"skim promote: {merged} rows of table {d.table_index} "
|
||||
f"({page.title}) ingested (LLM-proposed)", think=True)
|
||||
promoted += 1
|
||||
self._skim_leads = [] # consumed: bounded, never re-asked
|
||||
@@ -1003,7 +1012,7 @@ class KnowledgeExpert:
|
||||
charge_llm()
|
||||
heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})"
|
||||
raw = self.extract(question=question, heading=heading, text=text)
|
||||
if raw.stop:
|
||||
if raw.stop_table:
|
||||
stopped.add(frag["table_idx"])
|
||||
self._log(f"extractor STOP_TABLE: table {frag['table_idx']} "
|
||||
f"({frag['caption'][:40]!r}) not relevant — "
|
||||
@@ -1049,9 +1058,9 @@ class KnowledgeExpert:
|
||||
for i, r in enumerate(rows))
|
||||
pred = self.answer(question=question, rows=rendered)
|
||||
return {
|
||||
"value": pred.value.strip(),
|
||||
"value": _clean_value(pred.value),
|
||||
"quote": pred.quote.strip(),
|
||||
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
|
||||
and r.quote.strip() in pred.quote.strip()), rows[0].url),
|
||||
"confidence": pred.confidence.strip().lower(),
|
||||
"confidence": str(pred.confidence.value),
|
||||
}
|
||||
+37
-27
@@ -6,10 +6,19 @@ the FULL document text — so chunking can never fake a quote.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Confidence(str, Enum):
|
||||
"""Honest self-assessment of an answer drawn from KG rows."""
|
||||
HIGH = "high"
|
||||
MEDIUM = "medium"
|
||||
LOW = "low"
|
||||
|
||||
|
||||
class Fact(BaseModel):
|
||||
"""One fact extracted from a text, with its verbatim supporting quote."""
|
||||
subject: str = dspy.OutputField(desc="the fact's subject entity")
|
||||
@@ -19,19 +28,6 @@ class Fact(BaseModel):
|
||||
desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)")
|
||||
|
||||
|
||||
class TranslateSignature(dspy.Signature):
|
||||
"""You are the TRANSLATE step of a knowledge machine. Turn the question
|
||||
into Wikipedia search queries AND resolved entity terms. Resolve
|
||||
references ('that state', 'the same river') using the context: the original
|
||||
question and the evidence rows already gathered. Output two lines:
|
||||
QUERIES: 1-2 wikipedia search queries, comma separated.
|
||||
ENTITIES: the resolved entity names the answer is about, comma separated."""
|
||||
question: str = dspy.InputField()
|
||||
context: str = dspy.InputField(desc="the original question + evidence rows with answers already found; resolve pronouns from here; may be empty")
|
||||
queries: str = dspy.OutputField(desc="line starting with QUERIES: 1-2 comma-separated wikipedia search queries")
|
||||
entities: str = dspy.OutputField(desc="line starting with ENTITIES: comma-separated resolved entity names, e.g. ENTITIES: France, longest river")
|
||||
|
||||
|
||||
class ExtractSignature(dspy.Signature):
|
||||
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
||||
extract the facts that help answer the question. Each fact carries its
|
||||
@@ -39,7 +35,7 @@ class ExtractSignature(dspy.Signature):
|
||||
copied exactly (at least 10 characters). Only facts the text states;
|
||||
no inference.
|
||||
If the text is a fragment of a larger TABLE whose caption/headers show
|
||||
its subject is wrong for the question, set stop=True with no facts.
|
||||
its subject is wrong for the question, set stop_table=True with no facts.
|
||||
Do NOT stop for text that is merely hard — only when the table's
|
||||
subject is wrong."""
|
||||
question: str = dspy.InputField()
|
||||
@@ -47,7 +43,7 @@ class ExtractSignature(dspy.Signature):
|
||||
text: str = dspy.InputField()
|
||||
facts: list[Fact] = dspy.OutputField(
|
||||
desc="the extracted facts; empty list if none")
|
||||
stop: bool = dspy.OutputField(
|
||||
stop_table: bool = dspy.OutputField(
|
||||
desc="True when this table fragment's subject is wrong for the question")
|
||||
|
||||
|
||||
@@ -57,9 +53,11 @@ class AnswerFromKG(dspy.Signature):
|
||||
rows by id. If the rows do not answer it, say UNKNOWN."""
|
||||
question: str = dspy.InputField()
|
||||
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
|
||||
value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
|
||||
value: str = dspy.OutputField(
|
||||
desc="the answer, or UNKNOWN — the value ONLY, no row citations, no parenthetical explanations")
|
||||
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
|
||||
confidence: str = dspy.OutputField(desc="high medium low")
|
||||
confidence: Confidence = dspy.OutputField(
|
||||
desc="high: rows settle it; medium: plausible but partial; low: weak support")
|
||||
|
||||
|
||||
class VerifyCountSignature(dspy.Signature):
|
||||
@@ -81,18 +79,31 @@ class VerifyCountSignature(dspy.Signature):
|
||||
quote: str = dspy.OutputField(desc="verbatim sentence stating the count, or NOQUOTE")
|
||||
|
||||
|
||||
class TableChoice(BaseModel):
|
||||
"""The table chosen as the answer's enumeration, if any."""
|
||||
table_index: int = dspy.OutputField(desc="the chosen table's index")
|
||||
column: str = dspy.OutputField(desc="header name of the column holding the answer elements")
|
||||
set_name: str = dspy.OutputField(desc="short name of the set this table enumerates")
|
||||
|
||||
|
||||
class SelectTableSignature(dspy.Signature):
|
||||
"""You are the SELECT TABLE step of a knowledge machine. Given a question
|
||||
and the tables found in an article (index, caption, header columns, row
|
||||
count — NOT the rows), decide: does one of these tables enumerate the
|
||||
answer? Output the table index and the column holding the answer
|
||||
elements, or NONE."""
|
||||
answer?"""
|
||||
question: str = dspy.InputField()
|
||||
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N'")
|
||||
table_index: str = dspy.OutputField(desc="the chosen table index (e.g. '2'), or NONE")
|
||||
column: str = dspy.OutputField(desc="header name of the column holding the answer elements; empty if NONE")
|
||||
set_name: str = dspy.OutputField(desc="short name of the set this table enumerates, e.g. 'sovereign states in Europe'; empty if NONE")
|
||||
origin_question: str = dspy.OutputField(desc="the question verbatim, for provenance; empty if NONE")
|
||||
chosen: TableChoice | None = dspy.OutputField(
|
||||
desc="the chosen table and its answer column; null when NO table enumerates the answer")
|
||||
|
||||
|
||||
class PromotionDecision(BaseModel):
|
||||
"""One table's promotion verdict."""
|
||||
table_index: int = dspy.OutputField(desc="the table's index from the list")
|
||||
promote: bool = dspy.OutputField(
|
||||
desc="True when this table holds data about those entities for the goal")
|
||||
column: str = dspy.OutputField(
|
||||
desc="when promoted: the header holding the goal's values; empty otherwise")
|
||||
|
||||
|
||||
class SkimPromoteSignature(dspy.Signature):
|
||||
@@ -102,13 +113,12 @@ class SkimPromoteSignature(dspy.Signature):
|
||||
and the table's words may differ — 'water flow' vs 'Flow at the mouth').
|
||||
Given the run's goal, the entities it is about, and the tables' identity
|
||||
(caption, headers, row count, quantity signals — NOT the rows), decide
|
||||
per table whether it holds data about those entities for the goal.
|
||||
Output one line per table: 'idx: YES <column>' or 'idx: NO' — the column
|
||||
is the header holding the goal's values."""
|
||||
per table whether it holds data about those entities for the goal."""
|
||||
goal: str = dspy.InputField(desc="the run's overall goal question")
|
||||
entities: str = dspy.InputField(desc="the entities the goal is about, comma separated; may be empty")
|
||||
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N | quantities: x, y'")
|
||||
decision: str = dspy.OutputField(desc="one line per table: 'idx: YES <column>' or 'idx: NO'")
|
||||
decisions: list[PromotionDecision] = dspy.OutputField(
|
||||
desc="one verdict per table in the list")
|
||||
|
||||
|
||||
def parse_facts(raw: str) -> list[dict]:
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Deterministic query composition — the old TRANSLATE step as fixed code.
|
||||
|
||||
His 23/10 weights-tightness call: the TRANSLATE LLM was composing search
|
||||
queries from its OWN knowledge of the entities — 'Pedro Sánchez 2018
|
||||
investiture President of the Government of Spain' (the '2018' IS the
|
||||
answer to that term-start question, steered into retrieval from
|
||||
weights), 'Po, Adige, Tiber' proposed for a question that named only
|
||||
Italy. Probed against real Wikipedia over every logged TRANSLATE call of
|
||||
runs 22-23/10: queries composed from the question's named entities and
|
||||
keywords (+ the evidence's resolved entities) put the decisive article at
|
||||
top-1/2 in 8 of 9 cases — the LLM's world knowledge was never the
|
||||
load-bearing part; the search engine's own relevance was. So the step
|
||||
becomes code.
|
||||
|
||||
Laws:
|
||||
- Material: question ∪ evidence only. Every token of every query traces
|
||||
to the question or an evidence row — the weights-tightness law, now
|
||||
structural instead of prompted.
|
||||
- Deterministic: same inputs -> same queries, same order, every time.
|
||||
- Never empty: a question with no NEs still gets its keyword join.
|
||||
- Top-N over a list row in evidence slices the FIRST N members by source
|
||||
order (the ranked-list law) — never dumps all members into one query
|
||||
('Ranked Italy Maira K1 K2' retrieved nothing when a naive composer
|
||||
tried exactly that).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||
_CAP_RE = re.compile(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?")
|
||||
|
||||
# capitalized words that are question machinery, not subjects
|
||||
_CAP_STOPS = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
|
||||
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
|
||||
"Their", "Its", "Those", "These", "That", "This"}
|
||||
|
||||
# content-word stoplist (single source: probe seeds and composer share it)
|
||||
_KW_STOPS = {"what", "which", "who", "when", "where", "is", "are", "was",
|
||||
"were", "the", "of", "in", "on", "at", "a", "an", "and", "or",
|
||||
"to", "for", "does", "do", "did", "by", "its", "it", "that",
|
||||
"this", "most", "second"}
|
||||
|
||||
_N_WORDS = {"two": 2, "three": 3, "four": 4, "five": 5, "six": 6,
|
||||
"seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11,
|
||||
"twelve": 12}
|
||||
|
||||
|
||||
def _caps_in_order(question: str) -> list[str]:
|
||||
"""Capitalized words in question order, deduped."""
|
||||
return list(dict.fromkeys(_CAP_RE.findall(question or "")))
|
||||
|
||||
|
||||
def proper_nouns(question: str) -> set[str]:
|
||||
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the
|
||||
question. The definitive guard for 'which are the three longest rivers
|
||||
of Italy?' never accepting a world table (run H: Q1 answered Nile/
|
||||
Amazon/Yangtze because the top search hit was the world list and the
|
||||
disjointness guard was vacuous — no evidence, nothing to check)."""
|
||||
return {w for w in _caps_in_order(question) if w not in _CAP_STOPS}
|
||||
|
||||
|
||||
def _subjects(question: str) -> list[str]:
|
||||
"""NEs in question order. The SENTENCE-INITIAL word is dropped when
|
||||
other NEs exist: it is capitalized by sentence rules, not because it
|
||||
names an entity ('During what years…', 'Ranked by length…'). When it
|
||||
is the ONLY capitalized word it is kept — it may be the subject
|
||||
('Po length?')."""
|
||||
ne_set = proper_nouns(question)
|
||||
nes = [w for w in _caps_in_order(question) if w in ne_set]
|
||||
first = (question or "").strip().split(" ")[0] if question else ""
|
||||
if len(nes) > 1 and nes and nes[0] == first:
|
||||
nes = nes[1:]
|
||||
return nes
|
||||
|
||||
|
||||
def keywords(question: str, k: int = 6) -> list[str]:
|
||||
"""Deterministic lexical focus: content words of the question."""
|
||||
words = [w.lower() for w in WORD_RE.findall(question)]
|
||||
seen: list[str] = []
|
||||
for w in words:
|
||||
if w not in _KW_STOPS and len(w) > 2 and w not in seen:
|
||||
seen.append(w)
|
||||
return seen[:k]
|
||||
|
||||
|
||||
def _plural_head(kws: list[str]) -> str:
|
||||
"""The enumeration's head noun: first plural content word ('rivers',
|
||||
'countries'). Questions with no plural get no list variant."""
|
||||
return next((w for w in kws if w.endswith("s") and len(w) > 4), "")
|
||||
|
||||
|
||||
def _top_n(question: str) -> int | None:
|
||||
"""The N of a top-N ask ('which three of these…', 'top 5 …'), if any.
|
||||
Only meaningful when the evidence names a list to slice."""
|
||||
for w in WORD_RE.findall(question.casefold()):
|
||||
if w in _N_WORDS:
|
||||
return _N_WORDS[w]
|
||||
if w.isdigit() and 1 <= int(w) <= 12:
|
||||
return int(w)
|
||||
return None
|
||||
|
||||
|
||||
def compose_queries(question: str,
|
||||
evidence_entities: list[str] | None = None,
|
||||
list_mode: bool = False) -> tuple[list[str], list[str]]:
|
||||
"""Wikipedia search queries + entity terms from question ∪ evidence.
|
||||
|
||||
Returns (queries, entities), both deterministic. Queries (≤ 2, the
|
||||
per-gather search cost of the LLM step this replaces):
|
||||
[0] top-N ask over evidence members -> the FIRST N by source order
|
||||
('Po Adige Tiber' — the members themselves retrieve their
|
||||
articles); enumeration with a subject NE -> subject + head
|
||||
noun ('Italy rivers'); multi-NE -> the join ('Pedro Sanchez
|
||||
President'); single NE -> NE + salient keywords ('Po length');
|
||||
no NE but evidence -> the evidence's entities ('that state' +
|
||||
E1:France -> 'France'); else keyword join
|
||||
[1] enumeration with exactly ONE subject NE -> the Wikipedia
|
||||
list-article shape ('List of rivers of Italy'); else the
|
||||
attribute variant ('Pedro term begin'). A second NE makes the
|
||||
list shape ambiguous ('List of countries of Union') — skipped.
|
||||
entities: sliced evidence members (top-N) or question NEs, then the
|
||||
rest of the evidence entities, question order first.
|
||||
|
||||
Every token of every query traces to the question or the evidence.
|
||||
"""
|
||||
nes = _subjects(question)
|
||||
kws = keywords(question)
|
||||
ev = [e for e in (evidence_entities or []) if e]
|
||||
ne_lower = {n.casefold() for n in nes}
|
||||
salient = [w for w in kws if w not in ne_lower]
|
||||
n_ask = _top_n(question)
|
||||
|
||||
queries: list[str] = []
|
||||
if ev and n_ask:
|
||||
# top-N over a list row in evidence: the first N members by source
|
||||
# order carry the query (a ranked list ranks; unranked order is
|
||||
# still the source's own). Never all members at once.
|
||||
queries.append(" ".join(ev[:n_ask]))
|
||||
elif list_mode and nes and (plural := _plural_head(kws)):
|
||||
queries.append(" ".join(nes[:2] + [plural]))
|
||||
elif len(nes) >= 2:
|
||||
queries.append(" ".join(nes[:3]))
|
||||
elif nes and salient:
|
||||
queries.append(" ".join([nes[0], *salient[:2]]))
|
||||
elif nes:
|
||||
queries.append(nes[0])
|
||||
elif ev:
|
||||
queries.append(" ".join(ev[:3]))
|
||||
elif kws:
|
||||
queries.append(" ".join(kws[:3]))
|
||||
else:
|
||||
queries.append(question.strip()[:60] or "wikipedia")
|
||||
|
||||
variant = ""
|
||||
if list_mode and len(nes) == 1 and (plural := _plural_head(kws)):
|
||||
variant = f"List of {plural} of {nes[0]}"
|
||||
if not variant and salient:
|
||||
base = nes[0] if nes else (ev[0] if ev else "")
|
||||
if base and base.casefold() not in [q.casefold() for q in queries]:
|
||||
variant = " ".join([base, *salient[:2]])
|
||||
if variant and variant not in queries:
|
||||
queries.append(variant)
|
||||
|
||||
entities = list(dict.fromkeys((ev[:n_ask] if ev and n_ask else [])
|
||||
+ nes + ev))[:8]
|
||||
return queries[:2], entities
|
||||
@@ -13,6 +13,7 @@ from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
|
||||
from knowledge.wiki import WikiPage, parse_tables
|
||||
from knowledge.extract import TableChoice
|
||||
from knowledge.expert import (KnowledgeExpert, KnowledgeConfig,
|
||||
_tokens, _term_hits, _proper_nouns)
|
||||
from knowledge.store import KnowledgeStore
|
||||
@@ -118,10 +119,8 @@ def test_subject_guard_list():
|
||||
e2 = make_expert(KnowledgeStore(f"{tmp2}/kg.sqlite"))
|
||||
|
||||
class Pred:
|
||||
table_index = "1"
|
||||
column = "River"
|
||||
set_name = "longest rivers of Italy"
|
||||
origin_question = q
|
||||
chosen = TableChoice(table_index=1, column="River",
|
||||
set_name="longest rivers of Italy")
|
||||
|
||||
e2.select_table = lambda **kw: Pred()
|
||||
ans2 = e2._list_from_page(italy_page(), q, None)
|
||||
|
||||
@@ -13,6 +13,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||
|
||||
from knowledge.wiki import WikiPage, WikiTable, parse_tables
|
||||
from knowledge.store import KnowledgeStore
|
||||
from knowledge.extract import PromotionDecision
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
|
||||
|
||||
@@ -32,15 +33,15 @@ def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||
|
||||
|
||||
class FakePromote:
|
||||
"""Scripted skim_promote (dspy module shape): returns fixed decision."""
|
||||
def __init__(self, decision: str):
|
||||
self.decision_text = decision
|
||||
"""Scripted skim_promote (dspy module shape): returns typed decisions."""
|
||||
def __init__(self, decisions):
|
||||
self.decisions = decisions
|
||||
self.calls = 0
|
||||
|
||||
def __call__(self, **kw):
|
||||
self.calls += 1
|
||||
obj = type("P", (), {})()
|
||||
obj.decision = self.decision_text
|
||||
obj.decisions = self.decisions
|
||||
return obj
|
||||
|
||||
|
||||
@@ -81,7 +82,8 @@ def test_promotion_ingests_goal_table():
|
||||
n = e._harvest_side_tables(lead_page(), None, "q", EVIDENCE)
|
||||
assert n == 0 and len(e._skim_leads) == 1, "queued as lead, not ingested"
|
||||
# bounded promotion: LLM says YES (column Mean discharge)
|
||||
e.skim_promote = FakePromote("1: YES Mean discharge")
|
||||
e.skim_promote = FakePromote([PromotionDecision(
|
||||
table_index=1, promote=True, column="Mean discharge")])
|
||||
charged = []
|
||||
p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
|
||||
assert p == 1, "promoted table ingested"
|
||||
@@ -100,7 +102,8 @@ def test_promotion_refuses_world_table():
|
||||
e._current_goal_terms = ["total"] # no overlap with caption/header
|
||||
n = e._harvest_side_tables(world_page(), None, "q", EVIDENCE)
|
||||
assert n == 0 and len(e._skim_leads) == 1
|
||||
e.skim_promote = FakePromote("1: YES Mean discharge") # LLM WRONG
|
||||
e.skim_promote = FakePromote([PromotionDecision(
|
||||
table_index=1, promote=True, column="Mean discharge")]) # LLM WRONG
|
||||
p = e._promote_leads(EVIDENCE, lambda: None)
|
||||
assert p == 0, "code disposes: zero entity overlap -> refused"
|
||||
assert all(r.src != "amazon" for r in store.probe(["discharge"])), \
|
||||
@@ -110,7 +113,7 @@ def test_promotion_refuses_world_table():
|
||||
|
||||
def test_no_leads_no_call():
|
||||
e = make_expert(KnowledgeStore(":memory:"))
|
||||
e.skim_promote = FakePromote("1: YES x")
|
||||
e.skim_promote = FakePromote([])
|
||||
charged = []
|
||||
p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
|
||||
assert p == 0 and e.skim_promote.calls == 0 and not charged, \
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Deterministic query composition (the old TRANSLATE LLM, removed 23/10).
|
||||
|
||||
Laws under test (his weights-tightness call):
|
||||
1. Every token of every query traces to the question or the evidence —
|
||||
the model's own knowledge of the entities can no longer steer
|
||||
retrieval. The 22/10 logs caught the LLM putting the ANSWER into
|
||||
queries ('Pedro Sánchez 2018 investiture…' for a term-start question).
|
||||
2. Deterministic: same inputs -> same queries, same order, every time.
|
||||
3. Never empty: a question with no entities still gets its keyword join.
|
||||
4. Top-N over a list row in evidence slices the FIRST N members by source
|
||||
order — never dumps all members into one query.
|
||||
5. The subject NE + plural head noun surface the Wikipedia list article
|
||||
('List of rivers of Italy'), the source enumerations actually live in.
|
||||
|
||||
No network, no LLM. Run: uv run python knowledge/tests/queries.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) # repo root
|
||||
|
||||
from knowledge.queries import compose_queries, keywords, proper_nouns
|
||||
|
||||
|
||||
def test_single_entity_with_attribute():
|
||||
q, e = compose_queries("What is the length of Po?")
|
||||
assert q == ["Po length"], q
|
||||
assert e == ["Po"], e
|
||||
print("ok single entity: NE + salient keywords ('Po length')")
|
||||
|
||||
|
||||
def test_multi_entity_join():
|
||||
q, e = compose_queries("What is the discharge of the Po, Adige and Tiber?")
|
||||
assert q[0].startswith("Po"), q
|
||||
assert "Adige" in q[0] and "Tiber" in q[0], q
|
||||
print("ok multi-NE join:", q)
|
||||
|
||||
|
||||
def test_enumeration_list_variant():
|
||||
q, e = compose_queries("What are the three longest rivers of Italy?",
|
||||
list_mode=True)
|
||||
assert q == ["Italy rivers", "List of rivers of Italy"], q
|
||||
print("ok enumeration: subject + plural, then the list-article shape")
|
||||
|
||||
|
||||
def test_evidence_entities_carry_reference_resolution():
|
||||
# 'that state' + E1: France — the evidence resolves the reference,
|
||||
# not the model's knowledge of anything
|
||||
q, e = compose_queries("What is the longest river in that state?",
|
||||
evidence_entities=["France"])
|
||||
assert q == ["France"], q
|
||||
assert e == ["France"], e
|
||||
print("ok reference resolution from evidence, zero weights")
|
||||
|
||||
|
||||
def test_top_n_slices_evidence_by_source_order():
|
||||
# the case the LLM 'helped' with by guessing Po/Adige/Tiber from its
|
||||
# weights — the members are now sliced from the evidence row itself
|
||||
ev = ["Po", "Adige", "Tiber", "Dora", "Reno", "Ticino"]
|
||||
q, e = compose_queries(
|
||||
"Ranked by length, which three of these rivers are the longest in Italy?",
|
||||
evidence_entities=ev)
|
||||
assert q[0] == "Po Adige Tiber", q
|
||||
assert e[:3] == ["Po", "Adige", "Tiber"], e
|
||||
assert len(e) <= 8, e
|
||||
print("ok top-N ask: first N evidence members by source order")
|
||||
|
||||
|
||||
def test_top_n_never_dumps_all_members():
|
||||
ev = [f"R{i}" for i in range(22)]
|
||||
q, e = compose_queries("which three of these rivers are longest?",
|
||||
evidence_entities=ev)
|
||||
assert q[0].split() == ["R0", "R1", "R2"], q
|
||||
print("ok 22-member list: query carries only the sliced 3")
|
||||
|
||||
|
||||
def test_two_subject_ne_gets_no_list_shape():
|
||||
# 'List of countries of Union' would be garbage — with 2+ NEs the
|
||||
# list-article shape is skipped
|
||||
q, e = compose_queries(
|
||||
"Which countries in the continent of Europe are not members of the European Union?",
|
||||
list_mode=True)
|
||||
assert not any(x.startswith("List of") for x in q), q
|
||||
print("ok two subject NEs: no ambiguous list shape:", q)
|
||||
|
||||
|
||||
def test_no_entities_keyword_join():
|
||||
q, e = compose_queries("What is the speed of light?")
|
||||
assert q == ["speed light"], q
|
||||
assert e == [], e
|
||||
print("ok no NEs: keyword join, never empty")
|
||||
|
||||
|
||||
def test_sentence_initial_capital_not_a_subject():
|
||||
# 'During'/'Ranked' are capitalized by sentence rules; with other NEs
|
||||
# present they must not steer the query
|
||||
q, e = compose_queries("During what years did Pedro Sanchez serve as President?")
|
||||
assert q[0].startswith("Pedro"), q
|
||||
assert "During" not in q[0], q
|
||||
print("ok sentence-initial capital dropped when other NEs exist:", q)
|
||||
|
||||
|
||||
def test_weights_never_enter_queries():
|
||||
# the regression the audit found: model knowledge injected into
|
||||
# retrieval ('2018 investiture', 'Prime Minister of Spain' for a
|
||||
# question that says neither). Compose the same logged questions and
|
||||
# assert every query token traces to question ∪ evidence.
|
||||
cases = [
|
||||
("When did Pedro Sanchez's term as President begin (the start date of their presidency)?", []),
|
||||
("Which country's government does Pedro Sanchez lead as President?", []),
|
||||
("What are the three longest rivers of Italy?", []),
|
||||
("What is the length of Po?", []),
|
||||
]
|
||||
for question, ev in cases:
|
||||
qs, _ = compose_queries(question, evidence_entities=ev)
|
||||
material = set(keywords(question)) | {
|
||||
w.casefold() for w in
|
||||
__import__("re").findall(r"[A-Za-zÀ-ÿ0-9']+", question)} | {
|
||||
w.casefold() for w in ev}
|
||||
for query in qs:
|
||||
for tok in __import__("re").findall(r"[A-Za-zÀ-ÿ0-9']+", query):
|
||||
assert tok.casefold() in material, \
|
||||
f"untraceable token {tok!r} in {query!r} for {question!r}"
|
||||
print("ok every query token traces to question ∪ evidence (logged cases)")
|
||||
|
||||
|
||||
def test_deterministic():
|
||||
args = ("What are the three longest rivers of Italy?", None, True)
|
||||
r1 = compose_queries(*args)
|
||||
r2 = compose_queries(*args)
|
||||
assert r1 == r2
|
||||
print("ok same inputs -> same outputs")
|
||||
|
||||
|
||||
def test_proper_nouns_unchanged():
|
||||
# the guards depend on these exact semantics (guards.py contract)
|
||||
assert proper_nouns("Which are the three longest rivers of Italy?") == {"Italy"}
|
||||
assert proper_nouns("What is the discharge of the Po, Adige and Tiber?") == {"Po", "Adige", "Tiber"}
|
||||
assert keywords("Which are the three longest rivers of Italy?") == \
|
||||
["three", "longest", "rivers", "italy"]
|
||||
print("ok proper_nouns/keywords semantics unchanged for the guards")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_single_entity_with_attribute()
|
||||
test_multi_entity_join()
|
||||
test_enumeration_list_variant()
|
||||
test_evidence_entities_carry_reference_resolution()
|
||||
test_top_n_slices_evidence_by_source_order()
|
||||
test_top_n_never_dumps_all_members()
|
||||
test_two_subject_ne_gets_no_list_shape()
|
||||
test_no_entities_keyword_join()
|
||||
test_sentence_initial_capital_not_a_subject()
|
||||
test_weights_never_enter_queries()
|
||||
test_deterministic()
|
||||
test_proper_nouns_unchanged()
|
||||
print("\nqueries tests passed")
|
||||
@@ -11,6 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) # repo r
|
||||
|
||||
from knowledge.checks import check_candidate, quote_containment, trusted_source
|
||||
from knowledge.chunker import chunk_page
|
||||
from knowledge.extract import TableChoice
|
||||
from knowledge.store import KnowledgeStore
|
||||
|
||||
|
||||
@@ -225,10 +226,8 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
|
||||
def __call__(self, **kw):
|
||||
class P: pass
|
||||
p = P()
|
||||
p.table_index = "1"
|
||||
p.column = "Country"
|
||||
p.set_name = "sovereign states in Europe"
|
||||
p.origin_question = kw.get("question", "")
|
||||
p.chosen = TableChoice(table_index=1, column="Country",
|
||||
set_name="sovereign states in Europe")
|
||||
return p
|
||||
|
||||
class FakeStore:
|
||||
@@ -286,10 +285,7 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
|
||||
def __call__(self, **kw):
|
||||
class P: pass
|
||||
p = P()
|
||||
p.table_index = "NONE"
|
||||
p.column = ""
|
||||
p.set_name = ""
|
||||
p.origin_question = ""
|
||||
p.chosen = None
|
||||
return p
|
||||
ke.select_table = FakeNonePicker()
|
||||
assert ke._list_from_page(page, "irrelevant", None) is None
|
||||
|
||||
@@ -92,18 +92,18 @@ def test_process_page_fragments():
|
||||
wikitext=WIKITEXT_2TABLES)
|
||||
page.tables = parse_tables(WIKITEXT_2TABLES)
|
||||
|
||||
# scripted extractor: world-table parts -> stop=True; Italy table -> one Fact
|
||||
# scripted extractor: world-table parts -> stop_table=True; Italy table -> one Fact
|
||||
calls = []
|
||||
|
||||
class FakeOut:
|
||||
def __init__(self, facts, stop=False):
|
||||
def __init__(self, facts, stop_table=False):
|
||||
self.facts = facts
|
||||
self.stop = stop
|
||||
self.stop_table = stop_table
|
||||
|
||||
def fake_extract(question, heading, text, _calls=calls):
|
||||
_calls.append((question, heading, text))
|
||||
if "World rivers" in text:
|
||||
return FakeOut([], stop=True)
|
||||
return FakeOut([], stop_table=True)
|
||||
if "Rivers of Italy" in text:
|
||||
# quote = the full rendered row context (header + row), verbatim
|
||||
# from the fragment the extractor saw
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Judge value cleanup tests (the (K5) bug, run 085457 / 24-25/10 session).
|
||||
|
||||
glm-5.3-flash glues row citations and glosses onto the value field because
|
||||
AnswerFromKG says "cite rows by id" but has no citation output field. Three
|
||||
live shapes, verbatim from the runs:
|
||||
|
||||
"Socialist International (K5)" — row id
|
||||
"2018 (Pedro Sánchez has been Prime Minister of Spain — i.e., ...)" — parenthetical gloss
|
||||
"15 (list of 15 members: 17 november 2023, ...)" — LIST gloss
|
||||
|
||||
Laws under test:
|
||||
1. Trailing citation shapes are STRIPPED from the value, at the judge's
|
||||
output boundary (_clean_value), BEFORE the payload and the audit see it.
|
||||
2. Legitimate parentheticals SURVIVE: "(PSOE)" inside a name,
|
||||
"(Presidente del Gobierno)" inside an office title.
|
||||
3. A cleaned value lets the ablation audit RUN where the raw value killed
|
||||
it silently ("the judge invented it: nothing to ablate").
|
||||
4. The clean is idempotent and does not touch UNKNOWN/empty.
|
||||
|
||||
No network. No LLM: the cleaner is fixed code; the tests call it directly
|
||||
plus one scripted-judge pass through _answer_from_rows.
|
||||
Run: .venv/bin/python knowledge/tests/value_clean.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||
|
||||
from knowledge.expert import KnowledgeExpert, _clean_value
|
||||
|
||||
|
||||
def test_row_id_suffix_stripped():
|
||||
assert _clean_value("Socialist International (K5)") == "Socialist International"
|
||||
assert _clean_value("Rajoy (K12)") == "Rajoy"
|
||||
print("ok: row-id citation suffix stripped")
|
||||
|
||||
|
||||
def test_cited_from_rows_gloss_stripped():
|
||||
v = ("2018 (Pedro Sánchez has been Prime Minister of Spain — i.e., "
|
||||
"President of the Government — since 2018; cited from rows K16 and K30)")
|
||||
assert _clean_value(v) == "2018", _clean_value(v)
|
||||
print("ok: 'cited from rows' parenthetical stripped, year kept")
|
||||
|
||||
|
||||
def test_list_gloss_stripped():
|
||||
v = "15 (list of 15 members: 17 november 2023, 28 november 2023, 24 september 2024)"
|
||||
assert _clean_value(v) == "15", _clean_value(v)
|
||||
print("ok: LIST-members gloss stripped, count kept")
|
||||
|
||||
|
||||
def test_legitimate_parentheticals_survive():
|
||||
assert _clean_value("Spanish Socialist Workers' Party (PSOE)") == \
|
||||
"Spanish Socialist Workers' Party (PSOE)"
|
||||
assert _clean_value("Prime Minister of Spain (Presidente del Gobierno)") == \
|
||||
"Prime Minister of Spain (Presidente del Gobierno)"
|
||||
# a parenthetical that merely mentions a number is NOT a citation
|
||||
assert _clean_value("Prime Minister of Spain (since 2018)") == \
|
||||
"Prime Minister of Spain (since 2018)"
|
||||
print("ok: legitimate parentheticals untouched")
|
||||
|
||||
|
||||
def test_unknown_and_empty_untouched():
|
||||
assert _clean_value("UNKNOWN") == "UNKNOWN"
|
||||
assert _clean_value("") == ""
|
||||
assert _clean_value(" Spain ") == "Spain"
|
||||
print("ok: UNKNOWN/empty/whitespace handled")
|
||||
|
||||
|
||||
def test_idempotent_and_mid_value_citations():
|
||||
v = _clean_value("Socialist International (K5)")
|
||||
assert _clean_value(v) == v
|
||||
# a citation in the MIDDLE is not the live bug shape — leave it (no
|
||||
# aggressive surgery on the judge's sentence), the boundary law strips
|
||||
# only the TRAILING gloss
|
||||
assert _clean_value("Per (K2) the answer is Spain") == \
|
||||
"Per (K2) the answer is Spain"
|
||||
print("ok: idempotent; mid-value text untouched (boundary law: trailing only)")
|
||||
|
||||
|
||||
def test_answer_from_rows_boundary():
|
||||
"""The hook: _answer_from_rows cleans pred.value before the payload is
|
||||
built. Scripted dspy-style Predict object; no network."""
|
||||
e = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||
e.cfg = __import__("knowledge.expert", fromlist=["KnowledgeConfig"]).KnowledgeConfig()
|
||||
e._log = lambda *a, **k: None
|
||||
|
||||
class Pred:
|
||||
value = "Socialist International (K5)"
|
||||
quote = "ninth president of Socialist International since 2022"
|
||||
class confidence:
|
||||
value = "high"
|
||||
|
||||
class Row:
|
||||
src = rel = dst = quote = url = "u"
|
||||
conflict = False
|
||||
|
||||
e.answer = lambda question, rows: Pred()
|
||||
out = e._answer_from_rows("which office?", [Row()])
|
||||
assert out["value"] == "Socialist International", out["value"]
|
||||
print("ok: _answer_from_rows boundary cleans the value")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_row_id_suffix_stripped()
|
||||
test_cited_from_rows_gloss_stripped()
|
||||
test_list_gloss_stripped()
|
||||
test_legitimate_parentheticals_survive()
|
||||
test_unknown_and_empty_untouched()
|
||||
test_idempotent_and_mid_value_citations()
|
||||
test_answer_from_rows_boundary()
|
||||
print("\nvalue_clean: 7/7 ok")
|
||||
@@ -191,7 +191,7 @@ def part_of(frag: dict) -> str:
|
||||
|
||||
def parse_stop_table(out_text: str) -> bool:
|
||||
"""LEGACY textual STOP_TABLE detector — kept only for tests. Production
|
||||
code reads the typed `stop: bool` field of ExtractSignature."""
|
||||
code reads the typed `stop_table: bool` field of ExtractSignature."""
|
||||
return "STOP_TABLE" in (out_text or "").upper()[:80]
|
||||
|
||||
|
||||
|
||||
+36
-3
@@ -4,6 +4,7 @@
|
||||
uv run run_app.py "Per què el cel és blau?" # log only
|
||||
uv run run_app.py --verbose "Per què el cel és blau?" # + thinking on screen
|
||||
uv run run_app.py --baseline "Per què el cel és blau?" # raw LLM, one call (A/B comparison)
|
||||
uv run run_app.py --no-cache "..." # dspy response cache OFF for this run
|
||||
FLOOP_LM=ollama-cloud uv run run_app.py "..."
|
||||
|
||||
Always: runs/<ts>-<slug>/run.log written with flush -> `tail -f` it from another
|
||||
@@ -42,27 +43,59 @@ def run_baseline(question: str, streams: RunStreams) -> str:
|
||||
return answer
|
||||
|
||||
|
||||
def _assert_local_imports(code_dir: Path) -> None:
|
||||
"""Abort loudly if floop/knowledge resolve OUTSIDE this repo's tree.
|
||||
|
||||
The shared venv carries an editable-install .pth pointing at another
|
||||
checkout, and a poisoned PYTHONPATH (shim importing knowledge.* first)
|
||||
pins SUBMODULES to another tree even when the package __path__ lists
|
||||
this one — a namespace package recomputes __path__ dynamically, so
|
||||
checking the package proves nothing (run 085457, 25/10: main's pipeline
|
||||
ran inside the branch worktree with zero signal). Check the FILES the
|
||||
run actually executes. A wrong import tree invalidates the run; refuse
|
||||
it, don't log it.
|
||||
"""
|
||||
root = str(code_dir.resolve())
|
||||
for name, relpath in (("floop", "machine.py"), ("floop", "llm.py"),
|
||||
("knowledge", "expert.py"), ("knowledge", "store.py")):
|
||||
try:
|
||||
mod = __import__(f"{name}.{relpath[:-3]}", fromlist=[""])
|
||||
except ImportError as e: # pragma: no cover — broken install, abort anyway
|
||||
raise SystemExit(f"ABORT: cannot import {name}.{relpath[:-3]}: {e}")
|
||||
loaded = str(Path(mod.__file__).resolve())
|
||||
if not loaded.startswith(root):
|
||||
raise SystemExit(
|
||||
f"ABORT: module '{name}.{relpath[:-3]}' resolved outside this repo\n"
|
||||
f" repo: {root}\n"
|
||||
f" loaded: {loaded}\n"
|
||||
"The venv's editable .pth or PYTHONPATH shadows this tree — "
|
||||
"the run would test the WRONG code. Fix sys.path and retry.")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = sys.argv[1:]
|
||||
verbose = "--verbose" in args
|
||||
baseline = "--baseline" in args
|
||||
args = [a for a in args if a not in ("--verbose", "--baseline")]
|
||||
no_cache = "--no-cache" in args
|
||||
args = [a for a in args if a not in ("--verbose", "--baseline", "--no-cache")]
|
||||
if not args:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
question = " ".join(args)
|
||||
|
||||
code_dir = Path(__file__).resolve().parent
|
||||
_assert_local_imports(code_dir) # the editable-pth trap: wrong tree = invalid run
|
||||
cfg = yaml.safe_load((code_dir / "config.yaml").read_text())
|
||||
b = cfg["budget"]
|
||||
budget = Budget(max_llm_calls=b["max_llm_calls"], max_depth=b["max_depth"],
|
||||
max_retries=b["max_retries"], missing_extensions=b["missing_extensions"],
|
||||
min_child_budget=b["min_child_budget"])
|
||||
|
||||
lm_info = configure_lm()
|
||||
lm_info = configure_lm(no_cache=no_cache)
|
||||
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
|
||||
install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt
|
||||
streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} baseline={baseline}")
|
||||
streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} "
|
||||
f"baseline={baseline} no_cache={no_cache}")
|
||||
|
||||
if baseline:
|
||||
answer = run_baseline(question, streams)
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Query anonymization tests (his design, 22/10): INIT must decompose the
|
||||
question's SHAPE, not lean on its knowledge of the named people in it.
|
||||
|
||||
Laws under test:
|
||||
1. MASK proposes entities; apply_mask/restore_mask are DETERMINISTIC —
|
||||
longer names first, one mask per surface text, typed placeholders.
|
||||
2. init_decompose masks before INIT and restores in the subquestions.
|
||||
3. No entities found -> the question reaches INIT unchanged.
|
||||
4. MASK dying (AdapterParseError) -> passthrough, never a dead run.
|
||||
|
||||
No network; RawEngine returns raw text (DummyLM bypasses the adapter).
|
||||
Run: .venv/bin/python tests/anonymize.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
|
||||
from floop.dspy_modules import FloopModules
|
||||
from floop.anonymize import NamedEntity, apply_mask, identity_answer, restore_mask
|
||||
|
||||
|
||||
def _lm(script: list[str]) -> None:
|
||||
"""An engine replaying a script: one raw response per LM call."""
|
||||
class RawEngine:
|
||||
def __init__(self):
|
||||
self.i = 0
|
||||
def complete(self, request):
|
||||
raw = script[min(self.i, len(script) - 1)]
|
||||
self.i += 1
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
|
||||
|
||||
|
||||
Q = "Who was the President before Pedro Sanchez?"
|
||||
_MASKED_ENTS = '''[[ ## entities ## ]]
|
||||
[{"name": "Pedro Sanchez", "kind": "PERSON"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_TWO_SUBS = '''[[ ## subquestions ## ]]
|
||||
[{"text": "Which office does PERSON_1 hold as President?", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that same office before PERSON_1 took office?", "depends_on": [1], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
|
||||
|
||||
def test_apply_restore_deterministic():
|
||||
ents = [NamedEntity(name="Pedro Sanchez", kind="PERSON")]
|
||||
masked, restore = apply_mask(Q, ents)
|
||||
assert masked == "Who was the President before PERSON_1?", masked
|
||||
assert restore == {"PERSON_1": "Pedro Sanchez"}
|
||||
# longer first: a full name is never half-masked by a shorter one
|
||||
ents2 = [NamedEntity(name="Pedro Sanchez", kind="PERSON"),
|
||||
NamedEntity(name="Pedro", kind="PERSON")]
|
||||
m2, r2 = apply_mask("Pedro Sanchez and Pedro", ents2)
|
||||
assert m2 == "PERSON_1 and PERSON_2", m2
|
||||
assert restore_mask(m2, r2) == "Pedro Sanchez and Pedro"
|
||||
# restore order: PERSON_10 before PERSON_1
|
||||
r3 = {f"PERSON_{i}": f"name{i}" for i in range(1, 11)}
|
||||
assert "name10" in restore_mask("PERSON_10", r3)
|
||||
print("ok: apply/restore deterministic (longest-first, typed, reorder-safe)")
|
||||
|
||||
|
||||
def test_init_decompose_masks_and_restores():
|
||||
# script: first call = MASK, second = INIT
|
||||
_lm([_MASKED_ENTS, _TWO_SUBS])
|
||||
subs, raw = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 2, subs
|
||||
assert "Pedro Sanchez" in subs[0]["text"] and "PERSON_1" not in subs[0]["text"], subs[0]
|
||||
assert subs[1]["deps"] == [1]
|
||||
print("ok: INIT sees the masked query; subquestions come back restored")
|
||||
|
||||
|
||||
def test_no_entities_passthrough():
|
||||
_lm(['''[[ ## entities ## ]]
|
||||
[]
|
||||
|
||||
[[ ## completed ## ]]''', _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
|
||||
subs, _ = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 2 and "Pedro Sanchez" in subs[0]["text"]
|
||||
print("ok: no entities found -> question reaches INIT unchanged")
|
||||
|
||||
|
||||
_TWO_SUBS_ID = '''[[ ## subquestions ## ]]
|
||||
[{"text": "Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Which office does PERSON_1 hold as President?", "depends_on": [1], "answer_type": "OPEN"},
|
||||
{"text": "Who held that office before PERSON_1?", "depends_on": [2], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
|
||||
|
||||
def test_identity_subquestion_seeded():
|
||||
# the live PR-16 shape: subquestion 1 asks who PERSON_1 is — the mask
|
||||
# map already knows. It must come back marked known_answer, never routed.
|
||||
_lm([_MASKED_ENTS, _TWO_SUBS_ID])
|
||||
subs, _ = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 3, subs
|
||||
assert subs[0].get("known_answer") == "Pedro Sanchez", subs[0]
|
||||
assert not subs[1].get("known_answer") and not subs[2].get("known_answer")
|
||||
print("ok: identity subquestion carries known_answer (never routed)")
|
||||
|
||||
|
||||
def test_identity_detection_conservative():
|
||||
# 'who is PERSON_1's predecessor' is NOT an identity question
|
||||
r = {"PERSON_1": "Pedro Sanchez"}
|
||||
assert identity_answer("Who is PERSON_1?", r) == "Pedro Sanchez"
|
||||
assert identity_answer("What is ORGANIZATION_1?", {"ORGANIZATION_1": "PSOE"}) == "PSOE"
|
||||
assert identity_answer("Which specific individual does the placeholder refer to?", r) is None
|
||||
assert identity_answer("Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", r) == "Pedro Sanchez"
|
||||
assert identity_answer("Who is PERSON_1's predecessor?", r) is None
|
||||
assert identity_answer("Who was PERSON_1's predecessor?", r) is None
|
||||
assert identity_answer("What office does PERSON_1 hold?", r) is None
|
||||
assert identity_answer("Who is PERSON_1 compared to PERSON_2?", {**r, "PERSON_2": "x"}) is None
|
||||
# his 23/10 false positive: 'refer to' about the TITLE, not the
|
||||
# placeholder — the hidden-precondition INIT phrasing. Strict law:
|
||||
# 'refer(s) to' fires only with the placeholder as its REFERENT.
|
||||
assert identity_answer(
|
||||
'What country, organization, or office does the title "President" '
|
||||
'refer to in relation to PERSON_1?', r) is None
|
||||
# and the strict mechanism shapes still fire
|
||||
assert identity_answer("What does the placeholder PERSON_1 refer to?", r) == "Pedro Sanchez"
|
||||
assert identity_answer("the term PERSON_1 refers to in the question", r) == "Pedro Sanchez"
|
||||
print("ok: identity detection conservative (possessives/comparatives/title-refer not eaten)")
|
||||
|
||||
|
||||
def test_mask_death_passthrough():
|
||||
# MASK response violates the schema -> AdapterParseError -> passthrough
|
||||
_lm(["garbage", _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
|
||||
subs, _ = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 2 and "Pedro Sanchez" in subs[0]["text"]
|
||||
print("ok: MASK death -> passthrough, never a dead run")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_apply_restore_deterministic()
|
||||
test_init_decompose_masks_and_restores()
|
||||
test_no_entities_passthrough()
|
||||
test_identity_subquestion_seeded()
|
||||
test_identity_detection_conservative()
|
||||
test_mask_death_passthrough()
|
||||
print("\nanonymization tests passed")
|
||||
@@ -0,0 +1,372 @@
|
||||
"""Execution branches over ambiguous rows (his design, 22-23/10).
|
||||
|
||||
Laws under test:
|
||||
1. LAZY: an ambiguous row with NO dependent never forks (the pick rides,
|
||||
the ambiguity stays a note).
|
||||
2. FORK: an ambiguous row WITH a dependent opens one branch per reading;
|
||||
each branch binds the row to its reading through a VIEW (the shared
|
||||
table is never mutated — the store-unchanged law of the ablation mask).
|
||||
3. SHARED: a branch's acquired rows land in the ONE shared table, tagged
|
||||
with the branch id; another branch's view hides them until they merge.
|
||||
4. The dependent's question runs INSIDE each branch world (its reference
|
||||
resolves from the bound reading — 'that office' means what THIS branch
|
||||
bound, never re-guessed).
|
||||
5. CONDITIONAL ANSWER: the final answer is composed by FIXED CODE over
|
||||
the surviving branches — 'if you meant X -> A | if you meant Y -> B';
|
||||
never one reading chosen inside a synthesis prompt (run L law).
|
||||
6. DEATH: a branch whose dependents all fail dies honestly (recorded
|
||||
'dead', its clause never rendered).
|
||||
7. MERGE: two branches concluding the same value render once.
|
||||
8. NESTED: an ambiguous row inside a branch nests sub-branches under it;
|
||||
the branch carries its children's conditional as its answer.
|
||||
|
||||
No network; FakeModules scripts the LLM; a monkeypatched engine injects
|
||||
the ambiguous knowledge row (the real detector is exercised in
|
||||
knowledge/tests/ablation.py — here we test the MACHINE's fork).
|
||||
Run: uv run python tests/branches.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.machine import FloopRun
|
||||
from floop.state import AnswerType, Budget, EvidenceRow, EvidenceTable
|
||||
from floop.stream import RunStreams
|
||||
|
||||
|
||||
def budget(n: int = 40, depth: int = 2) -> Budget:
|
||||
return Budget(max_llm_calls=n, max_depth=depth, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
|
||||
class FakeModules:
|
||||
"""Scripted LLM: INIT returns the fixed subs; ROUTE always knowledge;
|
||||
synthesis returns the evidence dump marker (so we can see WHICH rows
|
||||
each branch synthesized from)."""
|
||||
|
||||
def __init__(self, init_subs, route_fn):
|
||||
self.init_subs = init_subs
|
||||
self.route_fn = route_fn
|
||||
self.synth_calls: list[str] = []
|
||||
self.calls: list[str] = []
|
||||
|
||||
def init_decompose(self, question):
|
||||
self.calls.append("init")
|
||||
return list(self.init_subs), ""
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
self.calls.append("missing")
|
||||
return []
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
self.calls.append("route")
|
||||
return self.route_fn(question), "fake"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
self.calls.append(f"engine:{question[:40]}")
|
||||
return {"value": "stub", "source_quote": "", "confidence": "low"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
self.synth_calls.append(evidence)
|
||||
# branch synthesis reads the branch's OWN rows: the answer names
|
||||
# the values it was given (the fork's worlds differ in the
|
||||
# predecessor row their EXPERT produced, scripted per question)
|
||||
vals = [ln for ln in evidence.splitlines() if "Rajoy" in ln or "Papandreou" in ln]
|
||||
if vals:
|
||||
return f"The predecessor was {('Rajoy' if 'Rajoy' in evidence else 'Papandreou')}"
|
||||
return f"SYNTH<{len(evidence)} chars>"
|
||||
|
||||
|
||||
def make_ambiguous_engine(value: str, alts: list[dict]):
|
||||
"""A knowledge engine returning ONE ambiguous scalar row: the Pedro
|
||||
shape (one person, several offices — the picked reading + named
|
||||
alternatives with their own quotes)."""
|
||||
class AmbigEngine:
|
||||
name = "knowledge"
|
||||
def __init__(self, modules, charge, expert_kind):
|
||||
self.charge = charge
|
||||
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||
self.charge()
|
||||
row = EvidenceRow(
|
||||
qid=qid, answer_type=AnswerType.OPEN,
|
||||
payload={"value": value, "ambiguous": True,
|
||||
"axis": "office held as President",
|
||||
"alternatives": alts,
|
||||
"quote": f"quote for {value}", "url": "http://x"},
|
||||
engine="knowledge", trace=[], provenance={"source": "knowledge_graph"},
|
||||
verified=False, note="")
|
||||
if streams is not None:
|
||||
streams.output("EXPERT", f"{qid} -> ANSWER value={value} AMBIGUOUS")
|
||||
return row
|
||||
return AmbigEngine
|
||||
|
||||
|
||||
def branch_answer_engine(answers: dict):
|
||||
"""A knowledge engine answering by BRANCH: the branch-bound reading
|
||||
decides what the predecessor was (the fork's worlds genuinely differ —
|
||||
PM of Spain -> Rajoy; Socialist International -> Papandreou)."""
|
||||
class BranchAnswerEngine:
|
||||
name = "knowledge"
|
||||
def __init__(self, modules, charge, expert_kind):
|
||||
self.charge = charge
|
||||
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||
self.charge()
|
||||
# what reading is bound in this world? the bound row is the
|
||||
# one answering the AMBIGUOUS question — read it from the table
|
||||
bound = ""
|
||||
for r in table.rows():
|
||||
if r.payload.get("ambiguous") or r.payload.get("branch_binding"):
|
||||
bound = str(r.payload.get("value", ""))
|
||||
break
|
||||
val = "UNKNOWN"
|
||||
for key, ans in answers.items():
|
||||
if key.casefold() in bound.casefold():
|
||||
val = ans
|
||||
break
|
||||
if streams is not None:
|
||||
streams.output("EXPERT", f"{qid} -> ANSWER value={val}")
|
||||
return EvidenceRow(
|
||||
qid=qid, answer_type=AnswerType.OPEN,
|
||||
payload={"value": val,
|
||||
"quote": f"quote for {val}"},
|
||||
engine="knowledge", trace=[], provenance={}, verified=False,
|
||||
note="" if val != "UNKNOWN" else "miss")
|
||||
return BranchAnswerEngine
|
||||
|
||||
|
||||
def plain_engine(value: str):
|
||||
class PlainEngine:
|
||||
name = "knowledge"
|
||||
def __init__(self, modules, charge, expert_kind):
|
||||
self.charge = charge
|
||||
self.seen_questions: list[str] = []
|
||||
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||
self.charge()
|
||||
self.seen_questions.append(question)
|
||||
if streams is not None:
|
||||
streams.output("EXPERT", f"{qid} -> ANSWER value={value}")
|
||||
return EvidenceRow(
|
||||
qid=qid, answer_type=AnswerType.OPEN,
|
||||
payload={"value": value, "quote": f"quote for {value}"},
|
||||
engine="knowledge", trace=[], provenance={"source": "knowledge_graph"},
|
||||
verified=False, note="")
|
||||
return PlainEngine
|
||||
|
||||
|
||||
def _run_machine(fm, streams, engine_classes: dict):
|
||||
"""Run the machine with per-question engines keyed by question text."""
|
||||
import floop.machine as M
|
||||
q_text_to_engine = {k: cls for k, cls in engine_classes.items()}
|
||||
captured = {}
|
||||
|
||||
class DispatchEngine:
|
||||
name = "knowledge"
|
||||
def __init__(self, modules, charge, expert_kind):
|
||||
self.charge = charge
|
||||
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||
for key, cls in q_text_to_engine.items():
|
||||
if key in question:
|
||||
eng = cls(None, self.charge, "knowledge")
|
||||
captured.setdefault(key, eng)
|
||||
return eng.run(qid, question, parent_question, table,
|
||||
answer_type, streams=streams)
|
||||
# default: plain 'UNKNOWN' — the run must stay honest
|
||||
self.charge()
|
||||
return EvidenceRow(
|
||||
qid=qid, answer_type=AnswerType.OPEN,
|
||||
payload={"value": "UNKNOWN"}, engine="knowledge",
|
||||
trace=[], provenance={}, verified=False, note="no engine")
|
||||
|
||||
real = M.LLMExpertEngine
|
||||
M.LLMExpertEngine = DispatchEngine
|
||||
try:
|
||||
run = FloopRun("Who was the President before Pedro Sanchez?",
|
||||
budget(), modules=fm, streams=streams)
|
||||
rep = run.run()
|
||||
return run, rep
|
||||
finally:
|
||||
M.LLMExpertEngine = real
|
||||
|
||||
|
||||
def test_ambiguous_row_with_dependent_forks_and_renders_conditionally():
|
||||
streams = RunStreams("fork test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
fm = FakeModules(
|
||||
init_subs=[
|
||||
{"text": "Which office does Pedro Sanchez hold as President?",
|
||||
"deps": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that office immediately before Pedro Sanchez?",
|
||||
"deps": [1], "answer_type": "OPEN"},
|
||||
],
|
||||
route_fn=lambda q: "knowledge")
|
||||
# Q1 (the office question) -> AMBIGUOUS: PM of Spain (picked) + SI (alt).
|
||||
# Q2 (inside each branch world) -> the answer the BOUND reading implies:
|
||||
# PM of Spain -> Rajoy; Socialist International -> Papandreou.
|
||||
run, rep = _run_machine(fm, streams, {
|
||||
"Which office": make_ambiguous_engine(
|
||||
"Prime Minister of Spain",
|
||||
[{"value": "President of Socialist International",
|
||||
"quote": "quote for SI", "url": "http://y"}]),
|
||||
"Who held that office": branch_answer_engine({
|
||||
"Prime Minister of Spain": "Mariano Rajoy",
|
||||
"Socialist International": "George Papandreou",
|
||||
}),
|
||||
})
|
||||
# FORK fired: two branches over the two readings
|
||||
assert len(run.branches.specs) == 2, run.branches.specs
|
||||
# the shared table: Q1's ambiguous row + 2 branch rows (one per branch)
|
||||
br_rows = [r for r in run.table.rows() if r.provenance.get("branch")]
|
||||
assert len(br_rows) == 2, [r.eid for r in run.table.rows()]
|
||||
assert sorted(r.provenance["branch"] for r in br_rows) == ["B1", "B2"]
|
||||
# the CONDITIONAL answer, composed by fixed code: both readings
|
||||
assert "if you meant" in rep.final_answer, rep.final_answer
|
||||
assert "Rajoy" in rep.final_answer, rep.final_answer
|
||||
assert "the picked reading" in rep.final_answer, rep.final_answer
|
||||
# store-unchanged law: the original ambiguous row keeps BOTH readings
|
||||
q1_rows = [r for r in run.table.rows() if r.qid == "Q1"]
|
||||
assert len(q1_rows) == 1 and q1_rows[0].payload.get("alternatives"), q1_rows
|
||||
print("ok: ambiguous row + dependent -> 2 branches, conditional answer")
|
||||
|
||||
|
||||
def test_ambiguous_row_without_dependent_does_not_fork():
|
||||
streams = RunStreams("no fork test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
fm = FakeModules(
|
||||
init_subs=[
|
||||
{"text": "Which office does Pedro Sanchez hold as President?",
|
||||
"deps": [], "answer_type": "OPEN"},
|
||||
],
|
||||
route_fn=lambda q: "knowledge")
|
||||
run, rep = _run_machine(fm, streams, {
|
||||
"Which office": make_ambiguous_engine(
|
||||
"Prime Minister of Spain",
|
||||
[{"value": "President of Socialist International",
|
||||
"quote": "q", "url": "u"}]),
|
||||
})
|
||||
# LAZY: no dependent -> no fork; the ambiguity is a note, the pick rides
|
||||
assert not run.branches.specs, run.branches.specs
|
||||
assert any("AMBIGUOUS" in n for n in rep.notes)
|
||||
assert "if you meant" not in rep.final_answer
|
||||
print("ok: ambiguous row with no dependent -> no fork (lazy law)")
|
||||
|
||||
|
||||
def test_dead_branch_renders_nothing():
|
||||
streams = RunStreams("dead branch test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
fm = FakeModules(
|
||||
init_subs=[
|
||||
{"text": "Which office does Pedro Sanchez hold as President?",
|
||||
"deps": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that office immediately before Pedro Sanchez?",
|
||||
"deps": [1], "answer_type": "OPEN"},
|
||||
],
|
||||
route_fn=lambda q: "knowledge")
|
||||
# Q2 answers UNKNOWN in EVERY branch world -> both branches die honestly
|
||||
run, rep = _run_machine(fm, streams, {
|
||||
"Which office": make_ambiguous_engine(
|
||||
"Prime Minister of Spain",
|
||||
[{"value": "President of Socialist International",
|
||||
"quote": "q", "url": "u"}]),
|
||||
"Who held that office": plain_engine("UNKNOWN"),
|
||||
})
|
||||
assert len(run.branches.specs) == 2, run.branches.specs
|
||||
assert all(run.branches.results[s.id].status == "dead"
|
||||
for s in run.branches.specs)
|
||||
assert rep.final_answer and "No reading" in rep.final_answer, rep.final_answer
|
||||
print("ok: dead branches render an honest empty, never a clause")
|
||||
|
||||
|
||||
def test_natural_merge_renders_once():
|
||||
streams = RunStreams("merge test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
fm = FakeModules(
|
||||
init_subs=[
|
||||
{"text": "Which office does Pedro Sanchez hold as President?",
|
||||
"deps": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that office immediately before Pedro Sanchez?",
|
||||
"deps": [1], "answer_type": "OPEN"},
|
||||
],
|
||||
route_fn=lambda q: "knowledge")
|
||||
# both branch worlds conclude the SAME answer (the synthesis script is
|
||||
# shared) -> one clause, the second merge-recorded
|
||||
class SameAnswerEngine:
|
||||
name = "knowledge"
|
||||
def __init__(self, modules, charge, expert_kind):
|
||||
self.charge = charge
|
||||
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||
self.charge()
|
||||
return EvidenceRow(
|
||||
qid=qid, answer_type=AnswerType.OPEN,
|
||||
payload={"value": "Mariano Rajoy", "quote": "q"},
|
||||
engine="knowledge", trace=[], provenance={}, verified=False, note="")
|
||||
|
||||
import floop.machine as M
|
||||
real = M.LLMExpertEngine
|
||||
M.LLMExpertEngine = SameAnswerEngine
|
||||
fm_synth = fm
|
||||
orig_synth = fm.synthesize
|
||||
try:
|
||||
run = FloopRun("Who was the President before Pedro Sanchez?",
|
||||
budget(), modules=fm, streams=streams)
|
||||
rep = run.run()
|
||||
finally:
|
||||
M.LLMExpertEngine = real
|
||||
# both branches answered 'Rajoy' (their synthesis sees the same table
|
||||
# shape) -> natural merge: one clause
|
||||
statuses = {s.id: run.branches.results[s.id].status
|
||||
for s in run.branches.specs}
|
||||
assert set(statuses.values()) <= {"answered", "merged"}, statuses
|
||||
if len(run.branches.specs) == 2:
|
||||
merged = [s for s, st in statuses.items() if st == "merged"]
|
||||
assert len(merged) <= 1, statuses
|
||||
print("ok: convergent branches merge; the answer renders once")
|
||||
|
||||
|
||||
def test_nested_ambiguity_forks_subbranches():
|
||||
"""An ambiguous row answered INSIDE a branch (its own dependent) opens
|
||||
sub-branches under it; the branch carries its children's conditional
|
||||
as its answer — nesting composes."""
|
||||
streams = RunStreams("nested test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
fm = FakeModules(
|
||||
init_subs=[
|
||||
{"text": "Which office does Pedro Sanchez hold as President?",
|
||||
"deps": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that office immediately before Pedro Sanchez?",
|
||||
"deps": [1], "answer_type": "OPEN"},
|
||||
{"text": "In what year did that predecessor leave office?",
|
||||
"deps": [2], "answer_type": "OPEN"},
|
||||
],
|
||||
route_fn=lambda q: "knowledge")
|
||||
# Q1 ambiguous (PM/SI); the predecessor question ALSO answers ambiguously
|
||||
# (Rajoy | Papandreou) INSIDE every branch — and Q3 depends on it, so the
|
||||
# inner ambiguity has its own dependent: sub-branches open under B1/B2.
|
||||
run, rep = _run_machine(fm, streams, {
|
||||
"Which office": make_ambiguous_engine(
|
||||
"Prime Minister of Spain",
|
||||
[{"value": "President of Socialist International",
|
||||
"quote": "q", "url": "u"}]),
|
||||
"Who held that office": make_ambiguous_engine(
|
||||
"Mariano Rajoy",
|
||||
[{"value": "George Papandreou", "quote": "q2", "url": "u2"}]),
|
||||
"In what year": branch_answer_engine({
|
||||
"Mariano Rajoy": "2018",
|
||||
"George Papandreou": "2015",
|
||||
}),
|
||||
})
|
||||
outer = [s for s in run.branches.specs if not s.origin]
|
||||
inner = [s for s in run.branches.specs if s.origin]
|
||||
assert len(outer) == 2, [s.id for s in run.branches.specs]
|
||||
assert inner, "nested ambiguity must open sub-branches"
|
||||
for s in inner:
|
||||
assert s.origin in {o.id for o in outer}, s
|
||||
assert rep.final_answer and "if you meant" in rep.final_answer, rep.final_answer
|
||||
print(f"ok: nested ambiguity -> {len(inner)} sub-branches under {len(outer)} parents")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_ambiguous_row_with_dependent_forks_and_renders_conditionally()
|
||||
test_ambiguous_row_without_dependent_does_not_fork()
|
||||
test_dead_branch_renders_nothing()
|
||||
test_natural_merge_renders_once()
|
||||
test_nested_ambiguity_forks_subbranches()
|
||||
print("\nbranching tests passed")
|
||||
@@ -0,0 +1,106 @@
|
||||
"""DATE answer type tests (his 22/10 local run: term-start answered '15').
|
||||
|
||||
Laws under test:
|
||||
1. AnswerType.DATE exists; INIT's enum desc mentions it (the schema the
|
||||
model sees carries the date guidance).
|
||||
2. _looks_like_date is deterministic and strict: a plausible YEAR is the
|
||||
admission bar — '15' alone, a month name alone, garbage: NOT dates.
|
||||
3. The machine refuses a DATE answer without a year: the row becomes
|
||||
UNKNOWN and the question fails (re-buttable honestly, never a silent
|
||||
wrong type flowing downstream into dependents).
|
||||
|
||||
No network. Run: .venv/bin/python tests/date_type.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.machine import _looks_like_date
|
||||
from floop.state import AnswerType, Budget, EvidenceRow, OpenQuestion
|
||||
from floop.machine import FloopRun
|
||||
|
||||
|
||||
def test_date_in_enum_and_desc():
|
||||
assert AnswerType.DATE.value == "DATE"
|
||||
from floop.dspy_modules import Subquestion
|
||||
import json
|
||||
schema = json.dumps(Subquestion.model_json_schema(), default=str)
|
||||
assert "DATE for a specific date" in schema, "desc must carry the date guidance"
|
||||
print("ok: AnswerType.DATE exists; the model-visible desc carries it")
|
||||
|
||||
|
||||
def test_looks_like_date():
|
||||
# admission: a plausible year
|
||||
for good in ("2 June 2018", "June 2018", "2018", "17 November 2023",
|
||||
"6–29 December 2023", "sworn in on 1 June 2018"):
|
||||
assert _looks_like_date(good), good
|
||||
# refusal: no year — the exact '15' shape from his run
|
||||
for bad in ("15", "June", "fifteen", "", "the fifteenth",
|
||||
"15 June", "239", "30000"):
|
||||
assert not _looks_like_date(bad), bad
|
||||
print("ok: _looks_like_date deterministic (year required; '15' refused)")
|
||||
|
||||
|
||||
def test_machine_rejects_bare_number_date():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
class DateModules:
|
||||
def init_decompose(self, question):
|
||||
return [{"text": "When did the term begin?",
|
||||
"deps": [], "answer_type": "DATE"}], ""
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return []
|
||||
def route_question(self, question, catalog, evidence):
|
||||
return "knowledge", "date lookup"
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "15", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "synthesized"
|
||||
|
||||
run = FloopRun("Who was the President before X?", b, modules=DateModules())
|
||||
run._init_decompose() # creates Q1 (DATE) from init_decompose
|
||||
q1 = next(q for q in run.stack.items if q.text == "When did the term begin?")
|
||||
run._route_and_execute(q1)
|
||||
# the expert's '15' must NOT satisfy the DATE question
|
||||
assert q1.status == "failed", q1.status
|
||||
assert any("DATE answer rejected" in n for n in run.notes), run.notes
|
||||
print("ok: '15' rejected for a DATE question — row UNKNOWN, question failed")
|
||||
|
||||
|
||||
def test_machine_accepts_real_date():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
class DateModules:
|
||||
def init_decompose(self, question):
|
||||
return [{"text": "When did the term begin?",
|
||||
"deps": [], "answer_type": "DATE"}], ""
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return []
|
||||
def route_question(self, question, catalog, evidence):
|
||||
return "knowledge", "date lookup"
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "2 June 2018", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "synthesized"
|
||||
|
||||
run = FloopRun("Who was the President before X?", b, modules=DateModules())
|
||||
run._init_decompose()
|
||||
q1 = next(q for q in run.stack.items if q.text == "When did the term begin?")
|
||||
run._route_and_execute(q1)
|
||||
assert q1.status == "answered", q1.status
|
||||
print("ok: '2 June 2018' accepted for a DATE question")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_date_in_enum_and_desc()
|
||||
test_looks_like_date()
|
||||
test_machine_rejects_bare_number_date()
|
||||
test_machine_accepts_real_date()
|
||||
print("\nDATE type tests passed")
|
||||
+94
-1
@@ -70,7 +70,11 @@ def test_user_expert_fails_question():
|
||||
rep = FloopRun("goal?", budget(), modules=fm).run()
|
||||
assert rep.questions[1][1] == "failed"
|
||||
assert any("needs_user_input" in e for e in rep.evidence_rows)
|
||||
assert rep.final_answer == "ANSWER(goal?)" # synthesis still happens, honestly
|
||||
# the 23/10 law: a run that ASKED ends IN THE QUESTION (fixed code),
|
||||
# never a synthesis prompt swallowing the ask — 'the evidence does
|
||||
# not identify...' is the rejected behaviour
|
||||
assert rep.final_answer.startswith("I need to ask you:"), rep.final_answer
|
||||
assert any("clarification requested" in n for n in rep.notes)
|
||||
|
||||
|
||||
def test_recursion_depth_cap():
|
||||
@@ -264,6 +268,95 @@ def test_fanout_respects_top_n_slice():
|
||||
print("ok test_fanout_respects_top_n_slice")
|
||||
|
||||
|
||||
def test_seed_warning_is_emitted():
|
||||
"""The mask seed auto-answering a question must WARN (his 23/10 ask):
|
||||
on the log as WARNING, on screen even non-verbose — self-improvement
|
||||
signal, not silent evidence."""
|
||||
import tempfile
|
||||
from floop.stream import RunStreams
|
||||
streams = RunStreams("seed warn test", verbose=False,
|
||||
runs_dir=tempfile.mkdtemp())
|
||||
fm = FakeModules(
|
||||
init_subs=[
|
||||
{"text": "Who is Pedro Sanchez?", "deps": [],
|
||||
"answer_type": "OPEN", "known_answer": "Pedro Sanchez"},
|
||||
{"text": "What office did Pedro Sanchez hold?", "deps": [1],
|
||||
"answer_type": "OPEN"},
|
||||
],
|
||||
route_fn=lambda q: "knowledge", expert_value="President")
|
||||
run = FloopRun("Who is Pedro Sanchez and what office does he hold?",
|
||||
budget(), modules=fm, streams=streams)
|
||||
run.run()
|
||||
log = streams.log_path.read_text(encoding="utf-8")
|
||||
assert "WARNING SEED auto-answered Q1" in log, log[-400:]
|
||||
assert "mask map; zero expert calls" in log
|
||||
assert any("seeded from anonymization" in n for n in run.notes)
|
||||
print("ok: seed WARNING lands in run.log (auto-answer is loud)")
|
||||
|
||||
|
||||
def test_route_to_user_ends_in_the_question():
|
||||
"""His 23/10 run: ROUTE deferred a subquestion to the user (the
|
||||
evidence only flagged ambiguity) — and the final ANSWER prompt
|
||||
swallowed the ask, inventing 'the evidence does not identify...'.
|
||||
A run that ASKED ends IN THE QUESTION, composed by fixed code: the
|
||||
instantiated question, what the machine holds as context, zero
|
||||
synthesis calls. (The ambiguity+dependent shape now forks branches —
|
||||
tested in branches.py; this covers every OTHER honest defer.)"""
|
||||
import tempfile
|
||||
from floop.stream import RunStreams
|
||||
from floop.state import AnswerType, EvidenceRow
|
||||
streams = RunStreams("clarify test", verbose=False,
|
||||
runs_dir=tempfile.mkdtemp())
|
||||
|
||||
class PlainEngine:
|
||||
def __init__(self, modules, charge, expert_kind):
|
||||
self.charge = charge
|
||||
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||
self.charge()
|
||||
return EvidenceRow(
|
||||
qid=qid, answer_type=AnswerType.OPEN,
|
||||
payload={"value": "Paris", "quote": "q"},
|
||||
engine="knowledge", trace=[], provenance={},
|
||||
verified=False, note="")
|
||||
|
||||
import floop.machine as M
|
||||
real = M.LLMExpertEngine
|
||||
M.LLMExpertEngine = PlainEngine
|
||||
try:
|
||||
# FakeModules.route_question returns (route_fn(question), "fake") —
|
||||
# our route must return the ATTENDANT string alone, not a tuple
|
||||
def route(q):
|
||||
if "district" in q:
|
||||
return "user"
|
||||
return "knowledge"
|
||||
|
||||
fm = FakeModules(
|
||||
init_subs=[
|
||||
{"text": "What is the capital of France?", "deps": [],
|
||||
"answer_type": "OPEN"},
|
||||
{"text": "Which specific district of that capital does the user mean?",
|
||||
"deps": [1], "answer_type": "OPEN"},
|
||||
],
|
||||
route_fn=route)
|
||||
# the generic FakeModules.missing_decompose would inject a fallback
|
||||
# question after the defer, reopening the loop and reaching a plain
|
||||
# synthesis — this test isolates the defer path (missing adds nothing)
|
||||
fm.missing_decompose = lambda goal, evidence: []
|
||||
run = FloopRun("What is the capital of France and which district do you mean?",
|
||||
budget(), modules=fm, streams=streams)
|
||||
rep = run.run()
|
||||
finally:
|
||||
M.LLMExpertEngine = real
|
||||
# the run ends IN THE QUESTION to the user, by fixed code
|
||||
assert rep.final_answer.startswith("I need to ask you:"), rep.final_answer
|
||||
assert "district" in rep.final_answer, rep.final_answer
|
||||
assert "(so far: Paris)" in rep.final_answer, rep.final_answer
|
||||
# the synthesis NEVER ran: the ask is not invented from the table
|
||||
assert "synthesize" not in fm.calls, fm.calls
|
||||
assert any("clarification requested" in n for n in rep.notes), rep.notes
|
||||
print("ok: a run that asks ends in the question (fixed code, no synthesis)")
|
||||
|
||||
|
||||
# keep a handle to restore the real engine after monkeypatching
|
||||
from floop.engine import LLMExpertEngine as _restore_llm_engine
|
||||
|
||||
|
||||
+144
-128
@@ -1,20 +1,24 @@
|
||||
"""PR-6 tests: INIT parsing robustness + the raw-response log (run I).
|
||||
"""PR-10b tests: typed INIT via dspy native structured output.
|
||||
|
||||
Run I: asked 'Who was the President before Pedro Sanchez?' the INIT LM
|
||||
answered with its own line numbers as an extra pipe field
|
||||
('1 | Who was Pedro Sanchez? | none | OPEN'), the naive parse took '1'
|
||||
and '2' as the subquestion texts, ROUTE classified Q1='1' as numeric and
|
||||
the machine burned 4 calls on garbage before luck produced the answer.
|
||||
Run I taught the pipe parser every defensive trick (line-number shifting,
|
||||
bare-number dropping). The typed migration removes the string contract
|
||||
entirely: dspy renders the Subquestion schema (enum answer_type,
|
||||
list[int] depends_on) into the prompt and parses responses back into
|
||||
typed objects — no Python string parsing on the production path.
|
||||
|
||||
Three laws under test:
|
||||
1. parse_subquestions shifts the numbered form and never accepts a bare
|
||||
number as a subquestion text.
|
||||
2. The machine degrades to the ORIGINAL question as one OPEN
|
||||
subquestion when nothing parses (a routable question is text).
|
||||
3. The prompt log appends the RAW LM response to the prompt file — the
|
||||
parsed OUTPUT line can lie by omission.
|
||||
Laws under test:
|
||||
1. The typed path E2E: a model response (raw text, through a REAL
|
||||
dspy.LM engine) parses into typed Subquestions; the machine dicts
|
||||
carry text, depends_on ints, and the AnswerType enum.
|
||||
2. Bare-number texts are still dropped (run-I law, now in
|
||||
_subs_from_typed).
|
||||
3. A schema-violating response (AdapterParseError, even after dspy's
|
||||
own JSON re-ask) becomes the degrade signal: (subs=[], raw) — the
|
||||
machine routes the ORIGINAL question, never garbage.
|
||||
4. The atomic case (empty subquestions list) stays atomic.
|
||||
|
||||
No network, no real LLM. Run: .venv/bin/python tests/robust_init.py
|
||||
No network. The engine returns raw text — DummyLM would bypass the
|
||||
adapter and test nothing. Run: .venv/bin/python tests/robust_init.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -23,151 +27,163 @@ from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.dspy_modules import parse_subquestions
|
||||
import dspy
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from floop.dspy_modules import FloopModules, Subquestion
|
||||
from floop.state import AnswerType, Budget
|
||||
from floop.machine import FloopRun
|
||||
|
||||
import tempfile as tf
|
||||
from floop.stream import RunStreams
|
||||
from floop.llm import PromptLogCallback, install_prompt_log
|
||||
|
||||
# --- 1) the parser -----------------------------------------------------------
|
||||
|
||||
def test_parse_numbered_lines():
|
||||
# the exact run-I shape: model line numbers as an extra first field
|
||||
raw = ("1 | Who was the President of Spain before Pedro Sanchez? | none | OPEN\n"
|
||||
"2 | When did that president's term end? | 1 | OPEN")
|
||||
subs = parse_subquestions(raw)
|
||||
def _lm(scripted_raw: str) -> None:
|
||||
"""A dspy.LM whose engine returns raw text — the REAL wire shape.
|
||||
cache=False: dspy persists responses to disk keyed by (model, prompt)
|
||||
and would cross-contaminate tests sharing the fake model name."""
|
||||
class RawEngine:
|
||||
def complete(self, request):
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=scripted_raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(),
|
||||
cache=False))
|
||||
|
||||
|
||||
# a canonical typed response, markers and all
|
||||
_GOOD = '''[[ ## subquestions ## ]]
|
||||
[{"text": "Which presidency does Pedro Sanchez hold?", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that same office before him?", "depends_on": [1], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
|
||||
|
||||
def test_typed_init_e2e():
|
||||
_lm(_GOOD)
|
||||
subs, raw = FloopModules().init_decompose(
|
||||
"Who was the President before Pedro Sanchez?")
|
||||
assert len(subs) == 2, subs
|
||||
assert subs[0]["text"] == "Who was the President of Spain before Pedro Sanchez?"
|
||||
assert subs[0]["deps"] == []
|
||||
assert subs[0]["answer_type"] == AnswerType.OPEN
|
||||
assert subs[1]["deps"] == [1], subs[1]
|
||||
print("ok: numbered-line form shifted (text, deps, type all intact)")
|
||||
|
||||
|
||||
def test_parse_bare_number_lines_dropped():
|
||||
# even if the number survives as text, it must be dropped — never routable
|
||||
raw = "1 | none | OPEN\n2 | none | OPEN"
|
||||
subs = parse_subquestions(raw)
|
||||
assert subs == [], subs
|
||||
print("ok: bare-number texts dropped (nothing routable = '1' or '2')")
|
||||
|
||||
|
||||
def test_parse_enumerator_prefix():
|
||||
# '1. Who was ...' inside the FIRST field — not a separate field
|
||||
raw = ("1. Who was the President before Pedro Sanchez? | none | OPEN\n"
|
||||
"2. When did his term end? | 1 | OPEN")
|
||||
subs = parse_subquestions(raw)
|
||||
assert len(subs) == 2, subs
|
||||
assert subs[0]["text"] == "Who was the President before Pedro Sanchez?"
|
||||
assert subs[0]["text"] == "Which presidency does Pedro Sanchez hold?"
|
||||
assert subs[0]["deps"] == [] and subs[0]["answer_type"] == AnswerType.OPEN
|
||||
assert subs[1]["deps"] == [1]
|
||||
print("ok: enumerator prefixes stripped from the text field")
|
||||
print("ok: typed INIT parses through the real adapter path (E2E)")
|
||||
|
||||
|
||||
def test_parse_happy_path_unchanged():
|
||||
# the old well-formed cases keep working (regression guard)
|
||||
subs = parse_subquestions(
|
||||
"1. How many qubits are needed? | none | FUNCTION\n"
|
||||
"2. What is the clock speed? | 1 | INTERVAL\n")
|
||||
assert subs[0]["text"].endswith("needed?") and subs[0]["deps"] == []
|
||||
assert subs[1]["deps"] == [1] and subs[1]["answer_type"] == AnswerType.INTERVAL
|
||||
assert parse_subquestions("") == []
|
||||
assert parse_subquestions("|||\n1 | none | OPEN") == []
|
||||
print("ok: well-formed lines parse exactly as before")
|
||||
def test_bare_number_text_dropped():
|
||||
raw = '''[[ ## subquestions ## ]]
|
||||
[{"text": "1", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that office before?", "depends_on": [], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
subs, _ = FloopModules().init_decompose("Who was the President before?")
|
||||
assert [s["text"] for s in subs] == ["Who held that office before?"], subs
|
||||
print("ok: bare-number texts dropped (run-I law survives typing)")
|
||||
|
||||
|
||||
# --- 2) the INIT degrade -----------------------------------------------------
|
||||
|
||||
class GarbageInitModules:
|
||||
"""INIT returns zero parseable subquestions (the run-I transcript)."""
|
||||
|
||||
def init_decompose(self, question):
|
||||
# (subs, raw): nothing parses, but the model DID write — degrade
|
||||
return (parse_subquestions("1 | none | OPEN\n2 | 1 | OPEN"),
|
||||
"1 | none | OPEN\n2 | 1 | OPEN")
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return [{"text": "fallback question?", "deps": [], "answer_type": "OPEN"}]
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
assert not question.strip().isdigit(), f"garbage routed: {question!r}"
|
||||
return "knowledge", "text question"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "Mariano Rajoy", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "Mariano Rajoy"
|
||||
def test_garbage_degrades():
|
||||
# run-I shape: the model wrote its own line numbers, none parse to a
|
||||
# valid schema — after dspy's re-ask the AdapterParseError carries the
|
||||
# garbage; init_decompose must signal (subs=[], raw non-empty)
|
||||
garbage = "1\n2"
|
||||
_lm(garbage)
|
||||
subs, raw = FloopModules().init_decompose("Who was the President before?")
|
||||
assert subs == [] and raw and raw.strip(), (subs, raw)
|
||||
print(f"ok: schema-violating garbage -> degrade signal (raw: {raw[:20]!r})")
|
||||
|
||||
|
||||
def test_init_degrades_to_original_question():
|
||||
def test_garbage_machine_degrades_to_original():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
fm = GarbageInitModules()
|
||||
run = FloopRun("Who was the President before Pedro Sanchez?", b, modules=fm)
|
||||
|
||||
class GarbageInitModules:
|
||||
"""INIT returns zero parseable subquestions (the run-I transcript)."""
|
||||
|
||||
def init_decompose(self, question):
|
||||
return [], "1\n2" # garbage raw — degrade path
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return [{"text": "fallback question?", "deps": [],
|
||||
"answer_type": "OPEN"}]
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
assert not question.strip().isdigit(), f"garbage routed: {question!r}"
|
||||
return "knowledge", "text question"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "Mariano Rajoy", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "Mariano Rajoy"
|
||||
|
||||
run = FloopRun("Who was the President before Pedro Sanchez?", b,
|
||||
modules=GarbageInitModules())
|
||||
rep = run.run()
|
||||
# the machine must have routed the ORIGINAL question, not '1'/'2'
|
||||
assert rep is not None
|
||||
q1 = rep.questions[0]
|
||||
assert q1[2] and not q1[2].strip().isdigit(), q1 # text, never a bare number
|
||||
assert q1[2] and not q1[2].strip().isdigit(), q1
|
||||
assert "Pedro Sanchez" in q1[2]
|
||||
assert all(not q[2].strip().isdigit() for q in rep.questions), rep.questions
|
||||
print("ok: INIT degrade routes the original question as one OPEN subq")
|
||||
print("ok: INIT degrade routes the ORIGINAL question as one OPEN subq")
|
||||
|
||||
|
||||
# --- 3) the raw-response log --------------------------------------------------
|
||||
def test_empty_stays_atomic():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
def test_prompt_log_captures_raw_response():
|
||||
import dspy
|
||||
from dspy.utils.dummies import DummyLM
|
||||
import tempfile as tf
|
||||
from floop.llm import PromptLogCallback, install_prompt_log
|
||||
from floop.stream import RunStreams
|
||||
class AtomicModules:
|
||||
def init_decompose(self, question):
|
||||
return [], "" # truly empty — atomic
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return []
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
return "knowledge", "text"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "299792458", "source_quote": "", "confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "299792458"
|
||||
|
||||
rep = FloopRun("What is the speed of light?", b,
|
||||
modules=AtomicModules()).run()
|
||||
assert len(rep.questions) == 1, rep.questions
|
||||
assert rep.questions[0][0] == "Q0"
|
||||
assert rep.questions[0][2] == "What is the speed of light?"
|
||||
print("ok: empty raw stays atomic (no fabricated subquestion)")
|
||||
|
||||
|
||||
def test_prompt_log_still_captures_raw():
|
||||
# PR-4/9 law: the RAW LM response is appended to the prompt file — now
|
||||
# for the typed path too (the engine's raw text is what gets logged)
|
||||
dspy.settings.configure(callbacks=[])
|
||||
streams = RunStreams("raw resp test", verbose=False, runs_dir=tf.mkdtemp())
|
||||
cb = PromptLogCallback(streams)
|
||||
dspy.configure(lm=DummyLM([
|
||||
{"subquestions": "1 | Who was Pedro Sanchez? | none | OPEN"}
|
||||
]), callbacks=[cb])
|
||||
|
||||
class Sig(dspy.Signature):
|
||||
question: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField()
|
||||
|
||||
dspy.Predict(Sig)(question="Who was the President before Pedro Sanchez?")
|
||||
_lm(_GOOD)
|
||||
dspy.configure(callbacks=[cb])
|
||||
FloopModules().init_decompose("Who was the President before Pedro Sanchez?")
|
||||
f = next((streams.run_dir / "prompts").glob("01-*.txt"))
|
||||
content = f.read_text()
|
||||
assert "# RAW RESPONSE" in content, content
|
||||
assert "Who was Pedro Sanchez?" in content, content
|
||||
assert "presidency does Pedro Sanchez" in content, content
|
||||
print(f"ok: raw response appended to {f.name}")
|
||||
dspy.settings.configure(callbacks=[])
|
||||
|
||||
|
||||
|
||||
def test_empty_raw_stays_atomic():
|
||||
"""Empty RAW (the model truly returned nothing) keeps the old law: the
|
||||
goal is atomic — stop and synthesize, never fabricate a subquestion."""
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
class AtomicModules(GarbageInitModules):
|
||||
def init_decompose(self, question):
|
||||
return [], ""
|
||||
|
||||
fm = AtomicModules()
|
||||
rep = FloopRun("What is the speed of light?", b, modules=fm).run()
|
||||
# atomic: INIT added no subquestions — only the goal's own Q0 remains
|
||||
assert len(rep.questions) == 1, rep.questions
|
||||
assert rep.questions[0][0] == "Q0", rep.questions
|
||||
assert rep.questions[0][2] == "What is the speed of light?", rep.questions
|
||||
print("ok: empty raw stays atomic (no fabricated subquestion)")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_parse_numbered_lines()
|
||||
test_parse_bare_number_lines_dropped()
|
||||
test_parse_enumerator_prefix()
|
||||
test_parse_happy_path_unchanged()
|
||||
test_init_degrades_to_original_question()
|
||||
test_empty_raw_stays_atomic()
|
||||
test_prompt_log_captures_raw_response()
|
||||
print("\nrobust_init tests passed")
|
||||
test_typed_init_e2e()
|
||||
test_bare_number_text_dropped()
|
||||
test_garbage_degrades()
|
||||
test_garbage_machine_degrades_to_original()
|
||||
test_empty_stays_atomic()
|
||||
test_prompt_log_still_captures_raw()
|
||||
print("\ntyped-INIT tests passed")
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Typed EXPERT + ANSWER tests (the last floop signatures): confidence is
|
||||
a closed enum; unverified is a real bool InputField.
|
||||
|
||||
No network; RawEngine returns raw text (DummyLM bypasses the adapter).
|
||||
Run: .venv/bin/python tests/typed_expert.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
|
||||
from floop.dspy_modules import FloopModules
|
||||
|
||||
|
||||
def _lm(scripted_raw: str) -> None:
|
||||
class RawEngine:
|
||||
def complete(self, request):
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=scripted_raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
|
||||
|
||||
|
||||
def test_expert_confidence_enum():
|
||||
raw = '''[[ ## value ## ]]
|
||||
Mariano Rajoy
|
||||
|
||||
[[ ## source_quote ## ]]
|
||||
his predecessor Mariano Rajoy
|
||||
|
||||
[[ ## confidence ## ]]
|
||||
high
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
out = FloopModules().expert_draft("Who was the President before Pedro Sanchez?",
|
||||
"knowledge", "E1: his predecessor Mariano Rajoy")
|
||||
assert out["value"] == "Mariano Rajoy" and out["confidence"] == "high", out
|
||||
print("ok: typed EXPERT parses confidence enum through the real path")
|
||||
|
||||
|
||||
def test_expert_bad_confidence_raises():
|
||||
raw = '''[[ ## value ## ]]
|
||||
42
|
||||
|
||||
[[ ## source_quote ## ]]
|
||||
|
||||
[[ ## confidence ## ]]
|
||||
certain
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
try:
|
||||
FloopModules().expert_draft("q", "knowledge", "")
|
||||
raise AssertionError("bad confidence parsed — enum broken")
|
||||
except AdapterParseError:
|
||||
print("ok: confidence outside the enum raises AdapterParseError")
|
||||
|
||||
|
||||
def test_answer_bool_input():
|
||||
# the bool InputField renders as a plain value in the prompt and the
|
||||
# string answer parses; synthesize passes a real bool now
|
||||
raw = '''[[ ## final_answer ## ]]
|
||||
Mariano Rajoy (E1).
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
ans = FloopModules().synthesize("Who was the President before Pedro Sanchez?",
|
||||
"E1: Mariano Rajoy", unverified=True)
|
||||
assert ans == "Mariano Rajoy (E1).", ans
|
||||
print("ok: ANSWER takes a bool unverified and parses through the real path")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_expert_confidence_enum()
|
||||
test_expert_bad_confidence_raises()
|
||||
test_answer_bool_input()
|
||||
print("\ntyped EXPERT+ANSWER tests passed")
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Typed ROUTE tests: the attendant is a closed enum — invalid picks are
|
||||
impossible by schema (a response outside the set raises AdapterParseError
|
||||
after dspy's own re-ask).
|
||||
|
||||
No network; the engine returns raw text (DummyLM bypasses the adapter —
|
||||
useless here). Run: .venv/bin/python tests/typed_route.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
|
||||
from floop.dspy_modules import FloopModules
|
||||
|
||||
|
||||
def _lm(scripted_raw: str) -> None:
|
||||
class RawEngine:
|
||||
def complete(self, request):
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=scripted_raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
|
||||
|
||||
|
||||
def test_route_valid_enum():
|
||||
raw = '''[[ ## attendant ## ]]
|
||||
knowledge
|
||||
|
||||
[[ ## reason ## ]]
|
||||
A factual lookup of who held the office before.
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
attendant, reason = FloopModules().route_question(
|
||||
"Who was the President before Pedro Sanchez?", "catalog", "")
|
||||
assert attendant == "knowledge", attendant
|
||||
assert reason.startswith("A factual")
|
||||
print("ok: typed ROUTE parses through the real adapter path")
|
||||
|
||||
|
||||
def test_route_invalid_attendant_raises():
|
||||
# outside the closed set -> schema violation -> AdapterParseError
|
||||
# (dspy's JSON re-ask gets the same bad value back and gives up)
|
||||
raw = '''[[ ## attendant ## ]]
|
||||
wikipedia
|
||||
|
||||
[[ ## reason ## ]]
|
||||
It's an encyclopedia.
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
try:
|
||||
FloopModules().route_question("q", "catalog", "")
|
||||
raise AssertionError("invalid attendant parsed — enum contract broken")
|
||||
except AdapterParseError:
|
||||
print("ok: attendant outside the enum raises AdapterParseError (schema holds)")
|
||||
|
||||
|
||||
def test_route_enum_compatibility():
|
||||
# the machine's comparisons survive typing: Attendant mixes str
|
||||
from floop.machine import EXPERT_ENGINES
|
||||
from floop.dspy_modules import Attendant
|
||||
assert Attendant.FLOOP == "floop"
|
||||
assert Attendant.KNOWLEDGE in EXPERT_ENGINES
|
||||
assert Attendant.USER not in EXPERT_ENGINES
|
||||
print("ok: enum is str-compatible — machine comparisons unchanged")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_route_valid_enum()
|
||||
test_route_invalid_attendant_raises()
|
||||
test_route_enum_compatibility()
|
||||
print("\ntyped-ROUTE tests passed")
|
||||
Reference in New Issue
Block a user