- LIST expert output renders the members (value is just the count; the opaque value=22 hid the actual rivers) - FANOUT line lists the sliced items by name - partial joins name which entity rows are missing
482 lines
23 KiB
Python
482 lines
23 KiB
Python
"""The machine — fixed control code. The LLM proposes; the machine disposes.
|
|
|
|
ALGORITHM.md mapping (v0.1 draft — every STUB is named honestly):
|
|
- INIT/MISSING/ROUTE/ANSWER are dspy LLM calls (dspy_modules.py)
|
|
- the check layer and the prover are STUBS: no formal verification happens,
|
|
so NOTHING is ever marked verified — the honest Unverified fallback
|
|
- expert engines are STUBS: the LLM call itself is the draft engine (engine.py)
|
|
- the stop condition is the question stack going terminal, not a prover check
|
|
- recursion: FLOOP-on-a-question with a budget slice and a depth cap (§4)
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
|
|
from .engine import CATALOG, LLMExpertEngine, UserRequestEngine
|
|
from .setops import detect_setop, setop_row
|
|
from .dspy_modules import FloopModules
|
|
from .state import (AnswerType, Budget, BudgetExhausted, EvidenceRow,
|
|
EvidenceTable, OpenQuestion, QuestionStack, instantiate)
|
|
from .stream import RunStreams
|
|
|
|
EXPERT_ENGINES = ("knowledge", "logic", "analytic", "numeric")
|
|
|
|
|
|
def _fmt_num(x: float) -> str:
|
|
"""Deterministic number formatting for computed rows: integers plain,
|
|
floats trimmed (no trailing .0)."""
|
|
return str(int(x)) if float(x).is_integer() else f"{x:g}"
|
|
|
|
|
|
def _coerce_atype(value) -> "AnswerType":
|
|
from .state import AnswerType as AT
|
|
if isinstance(value, AT):
|
|
return value
|
|
try:
|
|
return AT(str(value).upper())
|
|
except ValueError:
|
|
return AT.OPEN
|
|
|
|
|
|
@dataclass
|
|
class RunReport:
|
|
goal: str
|
|
final_answer: str
|
|
verified: bool
|
|
llm_calls: int
|
|
engine_calls: int
|
|
depth: int
|
|
notes: list[str] = field(default_factory=list)
|
|
questions: list[tuple] = field(default_factory=list) # (qid, status, text)
|
|
evidence_rows: list[str] = field(default_factory=list) # rendered row summaries
|
|
elapsed_s: float = 0.0
|
|
|
|
|
|
def _lm_dead(e: BaseException) -> bool:
|
|
"""Is this exception the LM dying (transport/timeout), not a code bug?
|
|
Walks the cause chain: dspy wraps transport deaths in LM* classes
|
|
(LMTransportError) over raw TimeoutErrors. Code bugs must still crash
|
|
loudly in development."""
|
|
seen: list[BaseException] = []
|
|
cur: BaseException | None = e
|
|
while cur is not None and cur not in seen:
|
|
seen.append(cur)
|
|
if type(cur).__name__.startswith("LM"):
|
|
return True
|
|
if "timed out" in str(cur).lower():
|
|
return True
|
|
cur = cur.__cause__ or cur.__context__
|
|
return False
|
|
|
|
|
|
class FloopRun:
|
|
"""One FLOOP execution over one question (top-level or recursive child)."""
|
|
|
|
def __init__(self, question: str, budget: Budget, depth: int = 0,
|
|
modules: FloopModules | None = None, parent_goal: str = "",
|
|
streams: RunStreams | None = None,
|
|
knowledge_engine=None) -> None:
|
|
self.query = question
|
|
self.budget = budget
|
|
self.depth = depth
|
|
self.parent_goal = parent_goal
|
|
self.modules = modules or FloopModules()
|
|
self.streams = streams or RunStreams(question)
|
|
self.tprefix = ">" * (depth + 1) + " " if depth else "" # depth marker on screen
|
|
self.table = EvidenceTable()
|
|
self.stack = QuestionStack(question)
|
|
self.user_engine = UserRequestEngine(self.modules)
|
|
self.knowledge_engine = knowledge_engine # None -> baseline LLM expert
|
|
self.notes: list[str] = []
|
|
self.engine_calls = 0
|
|
|
|
# ---- budget -----------------------------------------------------------
|
|
|
|
def _charge(self) -> None:
|
|
self.budget.charge_llm()
|
|
self.streams.log(f"budget llm_calls={self.budget.llm_calls}"
|
|
f"/{self.budget.max_llm_calls} depth={self.depth}")
|
|
|
|
# ---- the loop (ALGORITHM.md §2) ----------------------------------------
|
|
|
|
def run(self) -> RunReport:
|
|
t0 = time.time()
|
|
self._init_decompose()
|
|
while True:
|
|
try:
|
|
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; questions may still be open")
|
|
break
|
|
self._missing_round()
|
|
continue
|
|
self._route_and_execute(q)
|
|
except BudgetExhausted:
|
|
self.notes.append(f"budget exhausted at llm_calls={self.budget.llm_calls}")
|
|
break
|
|
except Exception as e: # noqa: BLE001 — LM deaths abort honestly
|
|
if _lm_dead(e):
|
|
self.notes.append(
|
|
f"LM unreachable at llm_calls={self.budget.llm_calls} "
|
|
f"({type(e).__name__}); aborting — no answer beats a made-up one")
|
|
break
|
|
raise
|
|
return self._finish(t0)
|
|
|
|
# ---- steps -------------------------------------------------------------
|
|
|
|
def _init_decompose(self) -> None:
|
|
self._charge()
|
|
self.streams.call("INIT", f"decompose: {self.query[:80]}",
|
|
think=self.tprefix + f"decomposing: {self.query[:100]}")
|
|
subs = self.modules.init_decompose(self.query)
|
|
self.streams.output("INIT", chr(10).join(s["text"] for s in subs) or "(no subquestions)")
|
|
self._add_questions(subs, reason="init")
|
|
|
|
def _missing_round(self) -> None:
|
|
self._charge()
|
|
self.budget.missing_used += 1
|
|
self.streams.call("MISSING", f"goal stuck: {self.query[:80]}",
|
|
think=self.tprefix + "goal not derivable; asking what is missing")
|
|
subs = self.modules.missing_decompose(self.query, self.table.dump())
|
|
self.streams.output("MISSING", chr(10).join(s["text"] for s in subs) or "(no new questions)")
|
|
self._add_questions(subs, reason="missing")
|
|
|
|
def _add_questions(self, subs: list[dict], reason: str) -> None:
|
|
created: list[OpenQuestion] = []
|
|
for s in subs:
|
|
created.append(self.stack.add(OpenQuestion(
|
|
text=s["text"], answer_type=_coerce_atype(s["answer_type"]),
|
|
reason=reason)))
|
|
# resolve deps: sibling line numbers -> sibling qids; #E refs are not
|
|
# dependencies (their rows already exist or never will) — the text keeps
|
|
# the reference and instantiate() substitutes it at pick time.
|
|
for q, s in zip(created, subs):
|
|
resolved = []
|
|
for tok in s["deps"]:
|
|
if isinstance(tok, int) and 1 <= tok <= len(created):
|
|
resolved.append(created[tok - 1].qid)
|
|
q.deps = resolved
|
|
|
|
# ---- fan-out (the planner's expansion; deterministic guard) --------------
|
|
|
|
FANOUT_MARK = re.compile(r"\b(for each|of each|per)\b", re.I)
|
|
_NUMWORDS = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
|
|
"six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10,
|
|
"eleven": 11, "twelve": 12}
|
|
|
|
def _fan_items(self, q: OpenQuestion) -> tuple[str, list[str]] | None:
|
|
"""The list an entity-fan question iterates over: the LIST row in its
|
|
deps, or a scalar comma-list row ('Po, Adige, Tiber'), or the table's
|
|
single list row when the text points with 'those/these'. Deterministic
|
|
— question shape is the machine's business, never the LLM's."""
|
|
for d in q.deps:
|
|
for r in self.table.for_question(d):
|
|
if isinstance(r.payload.get("list_items"), list) and r.payload["list_items"]:
|
|
return r.eid, list(r.payload["list_items"])
|
|
val = str(r.payload.get("value", ""))
|
|
if val.count(",") >= 1 and len(val) <= 80 and not val.replace(",", "").strip().isdigit():
|
|
items = [t.strip() for t in val.split(",") if t.strip()]
|
|
if 2 <= len(items) <= 12:
|
|
return r.eid, items
|
|
if re.search(r"\b(those|these|that)\b", q.text, re.I):
|
|
lists = [r for r in self.table.rows()
|
|
if isinstance(r.payload.get("list_items"), list)
|
|
and r.payload["list_items"] and not r.retracted]
|
|
if len(lists) == 1:
|
|
return lists[0].eid, list(lists[0].payload["list_items"])
|
|
return None
|
|
|
|
def _fan_count(self, qtext: str) -> int:
|
|
"""N when the question bounds the fan: 'those three rivers' -> 3."""
|
|
for w, n in self._NUMWORDS.items():
|
|
if re.search(rf"\b{w}\b", qtext, re.I):
|
|
return n
|
|
m = re.search(r"\b(\d{1,2})\b", qtext)
|
|
return int(m.group(1)) if m else 0
|
|
|
|
def _attribute_of(self, qtext: str) -> str:
|
|
"""'What is the average annual water flow (discharge) for each of
|
|
those rivers?' -> 'average annual water flow (discharge)'."""
|
|
m = re.match(r"(?:What is|What are|Which is|Which are)\s+(?:the\s+)?(.+?)"
|
|
r"\s+(?:for|of)\s+each", qtext, re.I)
|
|
if m:
|
|
return m.group(1).strip()
|
|
t = re.sub(self.FANOUT_MARK, "", qtext, count=1)
|
|
return re.sub(r"\?+$", "", t).strip()[:80]
|
|
|
|
def _detect_fanout(self, q: OpenQuestion) -> tuple[str, list[str]] | None:
|
|
"""A 'for each' subquestion over a known list is N entity questions +
|
|
one join — never one knowledge call over all entities at once."""
|
|
if not self.FANOUT_MARK.search(q.text):
|
|
return None
|
|
return self._fan_items(q)
|
|
|
|
def _expand_fanout(self, q: OpenQuestion, fan: tuple[str, list[str]]) -> None:
|
|
list_eid, items = fan
|
|
# top-N slice: 'for each of those three rivers' over a 22-row ranked
|
|
# table means the TOP 3 by table order (ranked tables rank; the slice
|
|
# is honest and logged, the value-ranked top-N is part (c))
|
|
n = self._fan_count(q.text)
|
|
if n and 0 < n < len(items):
|
|
items = items[:n]
|
|
self.notes.append(f"{q.qid}: fan-out sliced to top {n} of "
|
|
f"{len(fan[1])} by table order (ranked list assumed)")
|
|
attribute = self._attribute_of(q.text)
|
|
self.streams.call("FANOUT", f"expanding {q.qid} into {len(items)} entity questions",
|
|
think=self.tprefix + f"fan-out: {q.qid} over {list_eid}'s "
|
|
f"{len(items)} items ({', '.join(items)}) — one question per item, then a join")
|
|
# 1) one entity question per item (no deps: the list row already exists)
|
|
entity_qids: list[str] = []
|
|
for item in items:
|
|
eq = self.stack.add(OpenQuestion(
|
|
text=f"What is the {attribute} of {item}?",
|
|
answer_type=AnswerType.CONSTANT,
|
|
reason=f"fan-out of {q.qid}", deps=[]))
|
|
eq.fan_group = q.qid
|
|
entity_qids.append(eq.qid)
|
|
# 2) the join: an EXISTING dependent that asks for the sum/total is
|
|
# promoted to join (deterministic sum); otherwise create one
|
|
join_q: OpenQuestion | None = None
|
|
for other in self.stack.items:
|
|
if other is q or other.status != "open" or other.parent_goal:
|
|
continue
|
|
if q.qid in other.deps and re.search(r"\b(sum|total)\b", other.text, re.I):
|
|
join_q = other
|
|
break
|
|
if join_q is None:
|
|
join_q = self.stack.add(OpenQuestion(
|
|
text=re.sub(r"\?+$", "", re.sub(self.FANOUT_MARK, "", q.text, count=1)).strip()
|
|
+ "?",
|
|
answer_type=AnswerType.FUNCTION,
|
|
reason=f"fan-out join of {q.qid}", deps=list(entity_qids)))
|
|
join_q.fan_group = q.qid
|
|
join_q.fan_join = True
|
|
join_q.fan_source = list_eid
|
|
# 3) rewire q's dependents to the entity questions (q answers nothing)
|
|
for other in self.stack.items:
|
|
if other is not q and q.qid in other.deps:
|
|
other.deps = [d for d in other.deps if d != q.qid] + entity_qids
|
|
# 4) q is answered BY the expansion
|
|
q.status = "answered"
|
|
q.reason = f"expanded (fan-out) into {len(entity_qids)} entity questions"
|
|
self.notes.append(f"{q.qid}: {q.reason}")
|
|
self.streams.output("FANOUT", f"{q.qid} -> {len(entity_qids)} entity questions "
|
|
f"+ join {join_q.qid}")
|
|
|
|
def _join_rows(self, q: OpenQuestion) -> EvidenceRow | None:
|
|
"""The join: deterministic sum over the fan group's entity rows.
|
|
Computation is its own proof (verified=True); missing values make a
|
|
PARTIAL sum, named in the note — never a silent one."""
|
|
group = q.fan_group
|
|
entity_rows = [r for r in self.table.rows()
|
|
if r.provenance.get("fan_group") == group and r.eid != q.fan_source]
|
|
nums: list[float] = []
|
|
ids: list[str] = []
|
|
for r in entity_rows:
|
|
m = re.search(r"[-+]?[\d,]*\.?\d+", str(r.payload.get("value", "")))
|
|
if m:
|
|
nums.append(float(m.group().replace(",", "")))
|
|
ids.append(r.eid)
|
|
if not nums:
|
|
return None
|
|
total = sum(nums)
|
|
partial = len(nums) < len(entity_rows)
|
|
self.streams.state(f"join: sum of {len(nums)} entity rows = {total}", think=True)
|
|
if partial:
|
|
missing = [r.eid for r in entity_rows
|
|
if r.eid not in ids]
|
|
self.streams.state(
|
|
f"join partial: {len(nums)} of {len(entity_rows)} values summed; "
|
|
f"missing {', '.join(missing)}", think=True)
|
|
return EvidenceRow(
|
|
qid=q.qid, answer_type=AnswerType.FUNCTION,
|
|
payload={"value": _fmt_num(total), "sum_of": ids,
|
|
"sum_count": len(nums)},
|
|
engine="logic:join",
|
|
trace=[f"deterministic sum over {len(nums)} entity rows: "
|
|
f"{' + '.join(ids)}"],
|
|
provenance={"op": "sum", "operands": ids, "fan_group": group},
|
|
verified=True, # computation is its own proof
|
|
note=(f"partial: {len(nums)} of {len(entity_rows)} values summed"
|
|
if partial else ""))
|
|
|
|
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
|
|
# (logic's first real engine) and never spends the ROUTE call.
|
|
spec = detect_setop(q.text, self.table)
|
|
if spec is not None:
|
|
self.streams.call("LOGIC", f"setop on {q.qid}: {spec['op']} "
|
|
f"({spec['a'].eid}" + (f", {spec['b'].eid}" if spec['b'] else "") + ")",
|
|
think=self.tprefix + f"setop {spec['op']} over list rows; no LLM needed")
|
|
row = setop_row(spec, q.qid, q.answer_type)
|
|
self.table.append(row)
|
|
self.engine_calls += 1
|
|
self.streams.output("LOGIC", f"{spec['op']} = {row.payload['value']} "
|
|
f"({row.payload['list_count']} items) [computed]")
|
|
q.status = "answered"
|
|
q.reason = "setop computed"
|
|
return
|
|
# FAN-OUT GUARD (planner): a subquestion that asks for an attribute
|
|
# 'for each' item of a list row in its deps is N entity questions +
|
|
# 1 join — never ONE knowledge question over all entities at once.
|
|
fan = self._detect_fanout(q)
|
|
if fan is not None:
|
|
self._expand_fanout(q, fan)
|
|
return
|
|
# FAN-OUT JOIN: the join question never routes anywhere — its answer
|
|
# is a deterministic sum over the fan group's entity rows
|
|
if q.fan_join and q.fan_group:
|
|
row = self._join_rows(q)
|
|
if row is not None:
|
|
self.table.append(row)
|
|
self.engine_calls += 1
|
|
self.streams.output("JOIN",
|
|
f"sum = {row.payload['value']} "
|
|
f"({row.payload['sum_count']} values) [computed]")
|
|
q.status = "answered"
|
|
q.reason = "fan-out join computed"
|
|
return
|
|
# no numeric rows yet: leave open — entity rows are still coming
|
|
self.notes.append(f"{q.qid}: join found no numeric rows yet")
|
|
return
|
|
self._charge()
|
|
self.streams.call("ROUTE", f"{q.qid}: {q.text[:80]}",
|
|
think=self.tprefix + f"routing {q.qid}: {q.text[:90]}")
|
|
attendant, why = self.modules.route_question(q.text, CATALOG, self._context(q))
|
|
self.streams.output("ROUTE", f"{attendant} ({why})")
|
|
|
|
if attendant == "floop":
|
|
self._execute_child(q)
|
|
elif attendant == "user":
|
|
row = self.user_engine.run(q.qid, instantiate(q.text, self.table),
|
|
self.query, self.table, q.answer_type)
|
|
self.table.append(row)
|
|
self.engine_calls += 1
|
|
q.status = "failed"
|
|
q.reason = "user expert not wired (draft)"
|
|
elif attendant in EXPERT_ENGINES:
|
|
if attendant == "knowledge" and self.knowledge_engine is not None:
|
|
self.knowledge_engine.charge = self._charge
|
|
self.knowledge_engine.modules = self.modules
|
|
self.streams.call("EXPERT", f"knowledge pipeline on {q.qid}: {q.text[:80]}",
|
|
think=self.tprefix + f"asking knowledge (KG pipeline): {q.text[:90]}")
|
|
row = self.knowledge_engine.run(q.qid, instantiate(q.text, self.table),
|
|
self.query, self.table, q.answer_type,
|
|
streams=self.streams)
|
|
else:
|
|
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
|
|
self.streams.call("EXPERT", f"{attendant} on {q.qid}: {q.text[:80]}",
|
|
think=self.tprefix + f"asking {attendant}: {q.text[:90]}")
|
|
row = engine.run(q.qid, instantiate(q.text, self.table),
|
|
self.query, self.table, q.answer_type, streams=self.streams)
|
|
self.engine_calls += 1
|
|
self._append_checked(row, q)
|
|
else:
|
|
self.notes.append(f"router returned invalid attendant {attendant!r} for {q.qid}")
|
|
self.table.append(EvidenceRow(
|
|
qid=q.qid, answer_type=q.answer_type, payload={"value": "UNKNOWN"},
|
|
engine=f"unrouted:{attendant}", trace=[why], provenance={},
|
|
verified=False, note="route_invalid"))
|
|
q.status = "failed"
|
|
q.reason = "route invalid"
|
|
|
|
def _execute_child(self, q: OpenQuestion) -> None:
|
|
if self.depth + 1 > self.budget.max_depth:
|
|
self.notes.append(f"{q.qid}: depth cap reached; refusing to recurse")
|
|
q.status = "failed"
|
|
q.reason = "depth cap"
|
|
return
|
|
child_budget = self.budget.slice_for_child()
|
|
child = FloopRun(question=instantiate(q.text, self.table),
|
|
budget=child_budget, depth=self.depth + 1,
|
|
modules=self.modules, parent_goal=self.query,
|
|
streams=self.streams,
|
|
knowledge_engine=self.knowledge_engine)
|
|
report = child.run()
|
|
self.budget.llm_calls += child_budget.llm_calls
|
|
self.streams.state(
|
|
f"child run done: llm_calls={report.llm_calls} rows={len(report.evidence_rows)}",
|
|
think=True)
|
|
row = EvidenceRow(
|
|
qid=q.qid, answer_type=q.answer_type,
|
|
payload={"value": report.final_answer},
|
|
engine="floop-child",
|
|
trace=[f"child run: {report.llm_calls} llm calls, {len(report.evidence_rows)} rows"],
|
|
provenance={"depth": self.depth + 1, "llm_calls": report.llm_calls},
|
|
verified=False, # child answers carry no proof in the draft
|
|
note="child answer unverified")
|
|
self.table.append(row)
|
|
self.engine_calls += 1
|
|
q.status = "answered"
|
|
|
|
def _append_checked(self, row: EvidenceRow, q: OpenQuestion) -> None:
|
|
"""STUB arrival check (design: type check + contradiction check). Only the
|
|
trivial refusal fires: an expert that reports UNKNOWN fails its question."""
|
|
# fan-out bookkeeping: entity rows carry the group so the join finds them
|
|
if q.fan_group:
|
|
row.provenance["fan_group"] = q.fan_group
|
|
self.table.append(row)
|
|
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
|
|
q.status = "failed"
|
|
q.reason = "expert returned UNKNOWN"
|
|
else:
|
|
q.status = "answered"
|
|
|
|
def _context(self, q: OpenQuestion) -> str:
|
|
"""What the router sees. A list row renders its ITEMS — 'E1: 50' is
|
|
an ambiguous scalar that routes 'those countries' questions to the
|
|
user; 'E1: list of 50 items: Albania, ...' answers them."""
|
|
def render(r) -> str:
|
|
if isinstance(r.payload.get("list_items"), list):
|
|
return (f"list of {r.payload['list_count']} items: "
|
|
f"{', '.join(r.payload['list_items'][:8])}...")
|
|
return str(r.payload.get("value", r.payload.get("quote", "")))
|
|
|
|
lines = []
|
|
for d in q.deps:
|
|
for r in self.table.for_question(d):
|
|
lines.append(f"{r.eid} (answers {r.qid}): {render(r)}")
|
|
if not lines:
|
|
# no declared deps: the router must still SEE what the machine
|
|
# holds — an empty context routes referential questions to the
|
|
# user, who is a last resort, not a default.
|
|
for r in self.table.rows():
|
|
if r.retracted:
|
|
continue
|
|
lines.append(f"{r.eid} (answers {r.qid}): {render(r)}")
|
|
return "\n".join(lines[:8])
|
|
|
|
# ---- answer ------------------------------------------------------------
|
|
|
|
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)
|
|
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
|
|
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)) |