floop v0.1: design docs + executable dspy draft
Root: README, PIPELINE, ALGORITHM, GAPS, RUNLOG (design + first executable runs). code/: v0.1 draft on dspy 3.4 (INIT/ROUTE/EXPERT/MISSING/ANSWER as dspy calls, machine as fixed code, stub engines — honest Unverified). knowledge/: DESIGN.md for the KG-first knowledge expert (pre-implementation).
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
"""All LLM calls as dspy modules — v0.1 has only LLM calls; the real engines
|
||||
(check layer, solver/search) are stubs pending v0.2+.
|
||||
|
||||
Laws (ALGORITHM.md §7): LLMs translate and propose; they never decide or compute.
|
||||
Every module's docstring is the draft prompt — kept minimal on purpose.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dspy
|
||||
|
||||
from .state import AnswerType
|
||||
|
||||
|
||||
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."""
|
||||
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)"
|
||||
)
|
||||
|
||||
|
||||
class RouteSignature(dspy.Signature):
|
||||
"""You are the ROUTE step of a reasoning machine. Pick ONE attendant for the
|
||||
question. The user is a last resort when nothing else plausibly answers it."""
|
||||
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")
|
||||
reason: str = dspy.OutputField(desc="one sentence, for the log")
|
||||
|
||||
|
||||
class ExpertSignature(dspy.Signature):
|
||||
"""You are an expert ATTENDANT whose draft answer is checked by a machine.
|
||||
You translate the question into a typed answer payload — you do not compute
|
||||
values and you never invent facts. Use the evidence you are given, plus
|
||||
facts literally stated in the parent question; if the answer is not
|
||||
derivable from them, say so."""
|
||||
question: str = dspy.InputField()
|
||||
parent_question: str = dspy.InputField(
|
||||
desc="the original user question this subquestion serves; facts literally stated there are permitted sources")
|
||||
expert_kind: str = dspy.InputField(desc="knowledge logic analytic numeric")
|
||||
evidence: str = dspy.InputField(desc="evidence rows this question references")
|
||||
value: str = dspy.OutputField(desc="the answer value in its declared type, or 'UNKNOWN'")
|
||||
source_quote: str = dspy.OutputField(desc="VERBATIM supporting text (from evidence or the parent question); empty if none")
|
||||
confidence: str = dspy.OutputField(desc="high medium low")
|
||||
|
||||
|
||||
class MissingSignature(dspy.Signature):
|
||||
"""You are the MISSING step of a reasoning machine. The goal is NOT yet
|
||||
derivable from the evidence. Ask what is still missing: 1-3 new open
|
||||
subquestions that would close the gap. Use only concepts from the goal and
|
||||
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"
|
||||
)
|
||||
|
||||
|
||||
class AnswerSignature(dspy.Signature):
|
||||
"""You are the ANSWER step of a reasoning machine. Write the final natural
|
||||
language answer to the goal using ONLY the evidence rows. Working only from
|
||||
those rows, cite them; every number or fact carries its row id."""
|
||||
goal: str = dspy.InputField()
|
||||
evidence: str = dspy.InputField()
|
||||
unverified: str = dspy.InputField(desc="'true' if the prover could not verify derivability")
|
||||
final_answer: str = dspy.OutputField(desc="answer in natural language; cite only given row ids; no outside facts")
|
||||
|
||||
|
||||
class FloopModules:
|
||||
"""All LLM entry points of the draft. Each returns a dspy.Prediction."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.init = dspy.Predict(InitSignature)
|
||||
self.route = dspy.Predict(RouteSignature)
|
||||
self.expert = dspy.Predict(ExpertSignature)
|
||||
self.missing = dspy.Predict(MissingSignature)
|
||||
self.answer = dspy.Predict(AnswerSignature)
|
||||
|
||||
def init_decompose(self, question: str) -> list[dict]:
|
||||
pred = self.init(question=question)
|
||||
return parse_subquestions(pred.subquestions)
|
||||
|
||||
def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
return parse_subquestions(pred.subquestions)
|
||||
|
||||
def route_question(self, question: str, catalog: str, evidence: str) -> tuple[str, str]:
|
||||
pred = self.route(question=question, catalog=catalog, evidence=evidence)
|
||||
return pred.attendant.strip().lower(), pred.reason.strip()
|
||||
|
||||
def expert_draft(self, question: str, expert_kind: str, evidence: str,
|
||||
parent_question: str = "") -> dict:
|
||||
pred = self.expert(question=question, parent_question=parent_question,
|
||||
expert_kind=expert_kind, evidence=evidence)
|
||||
return {
|
||||
"value": pred.value.strip(),
|
||||
"source_quote": pred.source_quote.strip(),
|
||||
"confidence": pred.confidence.strip().lower(),
|
||||
}
|
||||
|
||||
def synthesize(self, goal: str, evidence: str, unverified: bool) -> str:
|
||||
pred = self.answer(goal=goal, evidence=evidence, unverified="true" if unverified else "false")
|
||||
return pred.final_answer.strip()
|
||||
|
||||
|
||||
def parse_subquestions(raw: str) -> list[dict]:
|
||||
""">> parse the piped lines from INIT/MISSING: text | deps | answer_type."""
|
||||
out: list[dict] = []
|
||||
for line in (raw or "").strip().splitlines():
|
||||
line = line.strip().lstrip("-•* ").strip()
|
||||
if not line or "|" not in line:
|
||||
continue
|
||||
parts = [p.strip() for p in line.split("|")]
|
||||
text = parts[0]
|
||||
if not text:
|
||||
continue
|
||||
deps_raw = parts[1].lower() if len(parts) > 1 else "none"
|
||||
atype_raw = parts[2].upper() if len(parts) > 2 else "OPEN"
|
||||
deps: list = []
|
||||
for tok in deps_raw.replace(",", " ").split():
|
||||
if tok in ("none", "-", "—", ""):
|
||||
continue
|
||||
if tok.startswith("#"):
|
||||
deps.append("#E" + tok.lstrip("#eE"))
|
||||
elif tok.isdigit():
|
||||
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
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Expert engines for the draft: the LLM IS the engine; deterministic engines come later.
|
||||
|
||||
The Engine interface and its laws are already the real ones: the instantiated
|
||||
question in, typed payload out — never free-form rows. Stub engines mark
|
||||
verified=False; the arrival check (in the machine) refuses UNKNOWN.
|
||||
|
||||
Routing (v0.1) — catalogue + one LLM judgement per question. Learned router:
|
||||
v2 (PIPELINE.md §7); logged trajectories train it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Callable, Protocol
|
||||
|
||||
from .state import AnswerType, EvidenceRow, EvidenceTable
|
||||
|
||||
CATALOG = (
|
||||
"knowledge: answer factual questions with verbatim quotes from the evidence and the parent question\n"
|
||||
"logic: derive conclusions validly from provided premises\n"
|
||||
"analytic: solve equations / symbolic relations over provided quantities\n"
|
||||
"numeric: evaluate a closed arithmetic expression over provided numbers\n"
|
||||
"floop: this question is too big for one call — decompose it (recurse)\n"
|
||||
"user: nothing else plausibly covers it — ask the person"
|
||||
)
|
||||
|
||||
NO_ROUTER = ["knowledge", "logic", "analytic", "numeric", "floop", "user"]
|
||||
|
||||
|
||||
class Engine(Protocol):
|
||||
def run(self, qid: str, question: str, parent_question: str,
|
||||
table: EvidenceTable, answer_type: AnswerType) -> EvidenceRow: ...
|
||||
|
||||
|
||||
class LLMExpertEngine:
|
||||
"""Draft engine: the dspy call produces the draft; a stub check layer passes
|
||||
it through with verified=False. Each engine call charges the LLM budget."""
|
||||
|
||||
def __init__(self, modules, charge_llm: Callable[[], None],
|
||||
expert_kind: str = "expert") -> None:
|
||||
self.modules = modules
|
||||
self.charge = charge_llm
|
||||
self.kind = expert_kind
|
||||
self.name = f"stub:{expert_kind}"
|
||||
|
||||
def run(self, qid, question, parent_question, table, answer_type):
|
||||
self.charge() # the engine IS an LLM call in this draft — it costs budget
|
||||
ev = table.dump()
|
||||
draft = self.modules.expert_draft(
|
||||
question, self.kind, ev, parent_question=parent_question)
|
||||
verified = False # v0.2: formal check layer (sorts/units/consistency) BEFORE engine
|
||||
payload: dict = {"value": draft["value"]}
|
||||
if draft["source_quote"]:
|
||||
payload["quote"] = draft["source_quote"]
|
||||
prov = {"expert": self.kind, "note": "draft v0.1 — no real engine, no check layer"}
|
||||
if parent_question:
|
||||
prov["parent_question"] = parent_question
|
||||
return EvidenceRow(
|
||||
qid=qid,
|
||||
answer_type=answer_type,
|
||||
payload=payload,
|
||||
engine=self.name,
|
||||
trace=[f"llm draft: value={draft['value']} confidence={draft['confidence']}"],
|
||||
provenance=prov,
|
||||
verified=verified,
|
||||
note="" if str(draft["value"]).upper() != "UNKNOWN" else "expert reported UNKNOWN",
|
||||
)
|
||||
|
||||
|
||||
class UserRequestEngine:
|
||||
"""v0.1: the user expert is not wired (no chat channel); returns an explicit failure row."""
|
||||
|
||||
def __init__(self, modules) -> None:
|
||||
self.modules = modules
|
||||
self.name = "stub:user"
|
||||
|
||||
def run(self, qid, question, parent_question, table, answer_type):
|
||||
prov = {"expert": "user"}
|
||||
if parent_question:
|
||||
prov["parent_question"] = parent_question
|
||||
return EvidenceRow(
|
||||
qid=qid,
|
||||
answer_type=answer_type,
|
||||
payload={"value": "UNKNOWN"},
|
||||
engine=self.name,
|
||||
trace=["user expert not wired in draft"],
|
||||
provenance=prov,
|
||||
verified=False,
|
||||
note="needs_user_input",
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""LM configuration: dspy.LM over OpenAI-compatible endpoints (no API keys in code).
|
||||
|
||||
dspy 3.x routes through litellm, so model ids carry the provider prefix —
|
||||
"openai/<model>" for any OpenAI-compatible endpoint (local ollama or ollama-cloud).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import dspy
|
||||
import yaml
|
||||
|
||||
|
||||
def _load_yaml() -> dict:
|
||||
cfg = Path(__file__).resolve().parent.parent / "config.yaml"
|
||||
return yaml.safe_load(cfg.read_text())
|
||||
|
||||
|
||||
def configure_lm() -> dict:
|
||||
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
|
||||
|
||||
Returns the active provider settings (for provenance logs).
|
||||
"""
|
||||
cfg = _load_yaml()["lm"]
|
||||
provider = os.environ.get("FLOOP_LM", cfg["default"])
|
||||
if provider not in cfg:
|
||||
raise ValueError(f"unknown FLOOP_LM provider {provider!r}; options: {list(cfg)[1:]}")
|
||||
p = cfg[provider]
|
||||
|
||||
kwargs: dict = {
|
||||
"model": f"openai/{p['model']}",
|
||||
"base_url": p["base_url"],
|
||||
"api_base": p["base_url"],
|
||||
"max_tokens": p["max_tokens"],
|
||||
"temperature": p["temperature"],
|
||||
"api_key": os.environ.get(p.get("api_key_env", ""), "empty"),
|
||||
}
|
||||
lm = dspy.LM(**kwargs)
|
||||
dspy.configure(lm=lm)
|
||||
return {"provider": provider, "model": p["model"], "base_url": p["base_url"]}
|
||||
@@ -0,0 +1,207 @@
|
||||
"""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 time
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .engine import CATALOG, LLMExpertEngine, UserRequestEngine
|
||||
from .dspy_modules import FloopModules
|
||||
from .state import (Budget, BudgetExhausted, EvidenceRow, EvidenceTable,
|
||||
OpenQuestion, QuestionStack, instantiate)
|
||||
|
||||
EXPERT_ENGINES = ("knowledge", "logic", "analytic", "numeric")
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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 = "") -> None:
|
||||
self.query = question
|
||||
self.budget = budget
|
||||
self.depth = depth
|
||||
self.parent_goal = parent_goal
|
||||
self.modules = modules or FloopModules()
|
||||
self.table = EvidenceTable()
|
||||
self.stack = QuestionStack(question)
|
||||
self.user_engine = UserRequestEngine(self.modules)
|
||||
self.notes: list[str] = []
|
||||
self.engine_calls = 0
|
||||
|
||||
# ---- budget -----------------------------------------------------------
|
||||
|
||||
def _charge(self) -> None:
|
||||
self.budget.charge_llm()
|
||||
|
||||
# ---- 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
|
||||
return self._finish(t0)
|
||||
|
||||
# ---- steps -------------------------------------------------------------
|
||||
|
||||
def _init_decompose(self) -> None:
|
||||
self._charge()
|
||||
subs = self.modules.init_decompose(self.query)
|
||||
self._add_questions(subs, reason="init")
|
||||
|
||||
def _missing_round(self) -> None:
|
||||
self._charge()
|
||||
self.budget.missing_used += 1
|
||||
subs = self.modules.missing_decompose(self.query, self.table.dump())
|
||||
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
|
||||
|
||||
def _route_and_execute(self, q: OpenQuestion) -> None:
|
||||
self._charge()
|
||||
attendant, why = self.modules.route_question(q.text, CATALOG, self._context(q))
|
||||
|
||||
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:
|
||||
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
|
||||
row = engine.run(q.qid, instantiate(q.text, self.table),
|
||||
self.query, self.table, q.answer_type)
|
||||
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)
|
||||
report = child.run()
|
||||
self.budget.llm_calls += child_budget.llm_calls
|
||||
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."""
|
||||
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:
|
||||
lines = []
|
||||
for d in q.deps:
|
||||
rows = self.table.for_question(d)
|
||||
for r in rows:
|
||||
lines.append(f"{r.eid}: {r.payload.get('value', r.payload.get('quote', ''))}")
|
||||
return "\n".join(lines)
|
||||
|
||||
# ---- answer ------------------------------------------------------------
|
||||
|
||||
def _finish(self, t0: float) -> RunReport:
|
||||
verified = False # STUB prover — v0.2: derivability check (clingo/Z3)
|
||||
answer = ""
|
||||
try:
|
||||
self._charge()
|
||||
answer = self.modules.synthesize(
|
||||
self.query, self.table.dump(), unverified=not verified)
|
||||
except BudgetExhausted:
|
||||
self.notes.append("budget died before the answer step")
|
||||
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))
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Shared state: evidence table, open questions, budget. The machine's data structures.
|
||||
|
||||
Laws enforced here (PIPELINE.md §5):
|
||||
- the table is append-only; retraction is a flag, never a deletion
|
||||
- every row carries provenance and a trace
|
||||
- prose is never stored: payload is a typed dict; verbatim quotes live in payload["quote"]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class AnswerType(str, Enum):
|
||||
OPEN = "OPEN"
|
||||
FUNCTION = "FUNCTION"
|
||||
INTERVAL = "INTERVAL"
|
||||
CONSTANT = "CONSTANT"
|
||||
|
||||
|
||||
class BudgetExhausted(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class OpenQuestion:
|
||||
text: str
|
||||
answer_type: AnswerType = AnswerType.OPEN
|
||||
deps: list[str] = field(default_factory=list) # qids this question waits on
|
||||
parent_goal: bool = False
|
||||
reason: str = "" # init | missing | child-goal
|
||||
qid: str = "" # assigned by QuestionStack
|
||||
status: str = "open" # open | answered | failed
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvidenceRow:
|
||||
answer_type: AnswerType
|
||||
payload: dict # typed fields; for knowledge: {"quote": ..., "url": ...} verbatim only
|
||||
engine: str # e.g. "stub:knowledge", "floop-child"
|
||||
eid: str = "" # assigned by EvidenceTable.append
|
||||
qid: str = ""
|
||||
trace: list[str] = field(default_factory=list)
|
||||
provenance: dict = field(default_factory=dict) # expert, llm_calls, ts, cost
|
||||
verified: bool = False
|
||||
note: str = "" # type mismatches, failures — never prose claims
|
||||
retracted: bool = False
|
||||
|
||||
|
||||
class EvidenceTable:
|
||||
def __init__(self) -> None:
|
||||
self._rows: list[EvidenceRow] = []
|
||||
self._next = 1
|
||||
|
||||
def append(self, row: EvidenceRow) -> EvidenceRow:
|
||||
if row.payload is None or not isinstance(row.payload, dict):
|
||||
raise ValueError("payload must be a typed dict — no free-form prose (table law 4)")
|
||||
row.eid = f"E{self._next}"
|
||||
self._next += 1
|
||||
self._rows.append(row) # append-only
|
||||
return row
|
||||
|
||||
def row(self, eid: str) -> EvidenceRow | None:
|
||||
return next((r for r in self._rows if r.eid == eid), None)
|
||||
|
||||
def rows(self) -> list[EvidenceRow]:
|
||||
return list(self._rows)
|
||||
|
||||
def for_question(self, qid: str) -> list[EvidenceRow]:
|
||||
return [r for r in self._rows if r.qid == qid]
|
||||
|
||||
def dump(self) -> str:
|
||||
out = []
|
||||
for r in self._rows:
|
||||
mark = "verified" if r.verified else "unverified"
|
||||
ret = " RETRACTED" if r.retracted else ""
|
||||
out.append(
|
||||
f"{r.eid} (answers {r.qid}, {r.answer_type.value}, {mark}{ret}) "
|
||||
f"engine={r.engine} payload={json.dumps(r.payload, ensure_ascii=False)}"
|
||||
+ (f" note={r.note}" if r.note else "")
|
||||
)
|
||||
return "\n".join(out) if out else "(empty)"
|
||||
|
||||
|
||||
class QuestionStack:
|
||||
def __init__(self, goal: str) -> None:
|
||||
self.goal = OpenQuestion(text=goal, parent_goal=True, reason="user question")
|
||||
self.goal.qid = "Q0"
|
||||
self.items: list[OpenQuestion] = [self.goal]
|
||||
self._next = 1
|
||||
|
||||
def add(self, q: OpenQuestion) -> OpenQuestion:
|
||||
q.qid = f"Q{self._next}"
|
||||
self._next += 1
|
||||
self.items.append(q)
|
||||
return q
|
||||
|
||||
def pickable(self, table: EvidenceTable) -> OpenQuestion | None:
|
||||
"""First open question whose deps are answered. Dependency order IS execution order — no search."""
|
||||
failed_qids = {i.qid for i in self.items if i.status == "failed" and not i.parent_goal}
|
||||
updated = True
|
||||
while updated: # cascade: a failed dependency kills its dependents too
|
||||
updated = False
|
||||
for q in self.items:
|
||||
if q.status != "open" or q.parent_goal:
|
||||
continue
|
||||
if table.for_question(q.qid):
|
||||
continue # already has evidence — never re-picked (loop guard)
|
||||
dead = [d for d in q.deps if d in failed_qids]
|
||||
if dead:
|
||||
q.status = "failed"
|
||||
q.reason = "dependency failed: " + ",".join(dead)
|
||||
failed_qids.add(q.qid)
|
||||
updated = True
|
||||
continue
|
||||
if all(table.for_question(d) for d in q.deps):
|
||||
return q
|
||||
return None
|
||||
|
||||
def open_count(self) -> int:
|
||||
return sum(1 for q in self.items if q.status == "open" and not q.parent_goal)
|
||||
|
||||
def all_terminal(self) -> bool:
|
||||
"""Every subquestion answered or failed — the goal itself is 'answered'
|
||||
by the synthesis step, not by a row (prover stub lives in the machine)."""
|
||||
return all(q.status in ("answered", "failed")
|
||||
for q in self.items if not q.parent_goal)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Budget:
|
||||
max_llm_calls: int
|
||||
max_depth: int
|
||||
max_retries: int
|
||||
missing_extensions: int
|
||||
min_child_budget: int = 6
|
||||
llm_calls: int = 0
|
||||
engine_calls: int = 0
|
||||
missing_used: int = 0
|
||||
|
||||
def charge_llm(self) -> None:
|
||||
if self.llm_calls >= self.max_llm_calls:
|
||||
raise BudgetExhausted(f"llm_calls={self.llm_calls}/{self.max_llm_calls}")
|
||||
self.llm_calls += 1
|
||||
|
||||
def slice_for_child(self) -> "Budget":
|
||||
remaining = self.max_llm_calls - self.llm_calls
|
||||
child = Budget(
|
||||
max_llm_calls=max(self.min_child_budget, remaining // 2),
|
||||
max_depth=self.max_depth,
|
||||
max_retries=self.max_retries,
|
||||
missing_extensions=self.missing_extensions,
|
||||
min_child_budget=self.min_child_budget,
|
||||
)
|
||||
return child
|
||||
|
||||
|
||||
def instantiate(text: str, table: EvidenceTable) -> str:
|
||||
"""ReWOO plan-on-slots: replace #E<n> references with the row's value."""
|
||||
def sub(m: re.Match) -> str:
|
||||
r = table.row(f"E{m.group(1)}")
|
||||
if r is None:
|
||||
return m.group(0)
|
||||
val = r.payload.get("value", r.payload.get("quote", r.payload.get("user_reply")))
|
||||
if val is None:
|
||||
val = json.dumps(r.payload, ensure_ascii=False)
|
||||
return str(val)
|
||||
|
||||
return re.sub(r"#E(\d+)", sub, text)
|
||||
Reference in New Issue
Block a user