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,57 @@
|
||||
# floop/code — v0.1 draft implementation
|
||||
|
||||
A **draft**: every deciding stage (formal checks, the prover, real engines) is a
|
||||
stub, so the draft runs with only LLM calls (as decided) and every answer is
|
||||
honestly marked **UNVERIFIED**. The architecture — states, laws, control flow —
|
||||
is the real v0.1 shape; only the formal layer is missing.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
cd floop/code
|
||||
.venv/bin/python run_app.py "What information do I need to plan a trip to Tokyo?" # any question
|
||||
FLOOP_LM=ollama-cloud .venv/bin/python run_app.py "..." # cloud LM instead of local
|
||||
```
|
||||
|
||||
`config.yaml` holds the budget knobs and the two LM providers (no keys in code:
|
||||
`ollama-cloud` reads `OLLAMA_API_KEY` from the environment).
|
||||
|
||||
## What is real vs stub (the honest map)
|
||||
|
||||
| Stage (ALGORITHM.md) | Status | Where |
|
||||
|---|---|---|
|
||||
| INIT — epistemic decomposition (LLM call) | real (dspy.Predict) | `floop/dspy_modules.py` |
|
||||
| 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) | **STUB engine**: LLM call, `verified=False` | `floop/engine.py` |
|
||||
| Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` |
|
||||
| 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) | — |
|
||||
| The machine (stack, dependency order, budget, recursion) | real fixed code | `floop/machine.py`, `floop/state.py` |
|
||||
| Evidence table (append-only, provenance, no prose) | real | `floop/state.py` |
|
||||
|
||||
Laws kept: the table only ever receives typed payloads (never LLM prose); rows
|
||||
carry provenance + trace; the machine — not the LLM — owns sequencing, budget,
|
||||
retries and stopping; answer synthesis sees only evidence rows and cites them.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
config.yaml budget + LM providers
|
||||
run_app.py CLI entry
|
||||
floop/state.py EvidenceTable, QuestionStack, Budget, slot instantiation (#En -> value)
|
||||
floop/llm.py dspy LM configuration (OpenAI-compatible endpoints)
|
||||
floop/dspy_modules.py every LLM call as a dspy module (INIT, ROUTE, EXPERT, MISSING, ANSWER)
|
||||
floop/engine.py engine interface + draft stub engines
|
||||
floop/machine.py FloopRun — the loop; recursion for the `floop` attendant
|
||||
tests/state.py unit tests (no LLM)
|
||||
```
|
||||
|
||||
## Next steps (design order from the docs)
|
||||
|
||||
1. Real check layer on expert arrival (well-formedness per expert kind) — the
|
||||
#1 failure mode is misformalization; keep it BEFORE engines.
|
||||
2. `knowledge` expert with real search + verbatim quotes (one vertical E2E).
|
||||
3. Prover for the stop condition (clingo/Z3) — replaces the stub derivability.
|
||||
4. Log every run (v2's router will eat these trajectories).
|
||||
@@ -0,0 +1,22 @@
|
||||
# floop draft config — see README.md
|
||||
lm:
|
||||
# provider selected by FLOOP_LM env var (local | ollama-cloud), default below
|
||||
default: local
|
||||
local:
|
||||
base_url: http://127.0.0.1:11435/v1
|
||||
model: qwen3.8:27b
|
||||
max_tokens: 4096
|
||||
temperature: 0.0
|
||||
ollama-cloud:
|
||||
base_url: https://ollama.com/v1
|
||||
model: glm-5.3-flash
|
||||
max_tokens: 4096
|
||||
temperature: 0.0
|
||||
api_key_env: OLLAMA_API_KEY
|
||||
|
||||
budget:
|
||||
max_llm_calls: 40 # per FLOOP run (children get a slice)
|
||||
min_child_budget: 6
|
||||
max_depth: 2 # recursion cap (PIPELINE.md §8.4)
|
||||
max_retries: 3 # bounded self-refinement on unparseable LLM output
|
||||
missing_extensions: 1 # how many times "what is still missing?" may reopen questions per run
|
||||
@@ -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)
|
||||
@@ -0,0 +1,237 @@
|
||||
# Knowledge expert — design (v0.1 draft, pre-implementation)
|
||||
|
||||
Status: DESIGN FOR REVIEW — nothing built yet. This document is the "pensem-lo bé".
|
||||
|
||||
## 0. What this expert is
|
||||
|
||||
One attendant of the fleet, answering per the generic expert pattern
|
||||
(translate → check → solve → return), where the engine is **retrieval over
|
||||
sources plus a persistent typed store**. Its contract with the machine
|
||||
unchanged from PIPELINE.md:
|
||||
|
||||
- in: an instantiated question (+ parent question + referenced evidence rows)
|
||||
- out: typed evidence rows — **verbatim quote + url + access date**, never paraphrase
|
||||
- the KG (`KnowledgeStore`) is the expert's private engine-side memory:
|
||||
persistent across runs, append-only, fully provenance-tracked.
|
||||
|
||||
Its novelty over GraphRAG/HippoRAG-style systems is the floop law applied as a
|
||||
real formal check: **every extracted fact must carry a verbatim span that is
|
||||
string-containment-verified against the fetched document text** — a cheap,
|
||||
deterministic, sound check that runs today (no solver needed). Nothing enters
|
||||
the store without it. Nothing leaves it without provenance.
|
||||
|
||||
Prior art with measured numbers (verified 2026-10-10, re-verify before claiming
|
||||
current SOTA — skill convention):
|
||||
|
||||
| System | Mechanism | Measured | What we take |
|
||||
|---|---|---|---|
|
||||
| HippoRAG (arXiv:2405.14831, NeurIPS'24) | KG + Personalized PageRank as retrieval | up to +20% multi-hop QA vs SOTA RAG; 10–30× cheaper and 6–13× faster than IRCoT | KG-first probe; single-step graph search replaces iterative LLM retrieval |
|
||||
| GraphRAG (arXiv:2404.16130, MSR) | LLM entity-extraction per chunk → graph → community summaries | 72–83% comprehensiveness win-rate vs vector RAG; up to 97% fewer tokens for global summaries; **bigger chunks = fewer calls but fewer entities extracted** | map-reduce extraction; the chunk-size tradeoff is a measured finding, not a guess |
|
||||
| ReWOO (arXiv:2305.18323) | plan-on-slots | 5× token efficiency | already in floop's orchestration; the expert must not duplicate it |
|
||||
| CYC (lesson, reference file) | manual knowledge acquisition killed the project | — | tiny closed ontology, auto-extraction, never hand-built |
|
||||
| LLM-Modulo (arXiv:2402.01817) | LLMs propose, external verifiers decide | — | quote-containment check = the verifier here |
|
||||
|
||||
What is floop-native: the store's laws (append-only, retraction flags, TMS-ready
|
||||
provenance, closed ontology sort-checks) and the verbatim-span containment as a
|
||||
first-class gate. Also the *engine-first, LLM-second* loop inside the expert.
|
||||
|
||||
## 1. The two halves, as Emili framed them
|
||||
|
||||
1. **Store (the KG)** — persistent knowledge: entities, typed relations
|
||||
between them, and verbatim quotes backing every edge. Consulted FIRST.
|
||||
2. **Gather (searcher + extractor)** — fills gaps: search → fetch → chunk →
|
||||
extract → check → store → select. Consulted for what the KG lacks.
|
||||
|
||||
## 2. The store — `KnowledgeStore`
|
||||
|
||||
Format decision (recommendation): **SQLite** (single file, stdlib, auditable,
|
||||
zero infra) + **JSONL mirror** for human diff/audit. Graph algorithms via
|
||||
NetworkX loaded from the DB on demand. No vector DB, no server. When measured
|
||||
recall failure justifies embeddings, that is a later decision with numbers —
|
||||
not now.
|
||||
|
||||
Schema (append-only; **no UPDATE/DELETE ever** — corrections and conflicts are
|
||||
new rows or retraction flags, TMS-ready like the evidence table):
|
||||
|
||||
```
|
||||
documents(id, url, source, fetched_at, sha256, trusted, text_path)
|
||||
chunks(id, doc_id, section_path, position, char_start, char_end, sha256)
|
||||
quotes(id, doc_id, chunk_id, verbatim, url, access_date) -- canonical text
|
||||
nodes(id, norm_name, sort, mentions++ ) -- entity index
|
||||
edges(src_node, rel, dst_value, dst_node?, quote_id, subject?, extraction_confidence, retracted)
|
||||
conflicts(nodeA, rel, valueA, valueB, nodeA_quote, nodeB_quote) -- surfaced, never resolved silently
|
||||
```
|
||||
|
||||
- Edges are **pointers**, not prose: `(Shor's algorithm, requires, Grover→…)`.
|
||||
The QUOTE carries the truth; the edge is the index structure that finds it.
|
||||
Relation names come from the closed ontology — that is how they pass checks.
|
||||
- `dst_value` for literal quantities: value + **unit** fields (Quantity sort).
|
||||
This is the bridge to `analytic`/`numeric`: knowledge extracts typed
|
||||
quantities; those experts compute on them. Neuro-symbolic payoff, by design.
|
||||
- Duplicate edge from two sources = **corroboration count** on the edge. Same
|
||||
subject+relation with two different literal values = never merged — a
|
||||
`conflicts` row is created and surfaced, exactly the "never silently pick a
|
||||
side" law the machine already uses for user rows.
|
||||
- Entity node identity, draft: `(normalized_name, sort)` with normalization =
|
||||
casefold + punctuation strip. Entity resolution is hard; the draft merges
|
||||
ONLY on normalized-name equality within the same sort. Everything else stays
|
||||
as separate nodes until evidence forces a merge decision (later, with LLM
|
||||
linker, measured).
|
||||
- KG probe (engine, deterministic): seed = question's mentions matched to
|
||||
nodes (lexical, draft; LLM linker later); traversal = BFS depth-1 neighborhood
|
||||
with corroboration-weighted ranking (draft). **PPR is the upgrade path** —
|
||||
HippoRAG's exact mechanism, one function away, adopt it when BFS recall
|
||||
measurably fails. No LLM inside the probe.
|
||||
|
||||
## 3. The closed ontology (the typed grammar)
|
||||
|
||||
Same philosophy as the orchestrator's ~5 action schemas: tiny ontology, big
|
||||
discipline. Seed set (Emili extends at review):
|
||||
|
||||
- Entity sorts: `PERSON, ORGANIZATION, CONCEPT, EVENT, QUANTITY, DOCUMENT, PLACE, DATE, OTHER`
|
||||
- Relations (subject_sort → object_sort, checked by the sort-checker):
|
||||
`HAS_PROPERTY, PART_OF, INSTANCE_OF, OCCURRED_AT(→DATE), LOCATED_AT(→PLACE),
|
||||
CAUSED_BY, REQUIRES(→CONCEPT), MEASURES(→QUANTITY), DEFINED_AS, AUTHORED_BY(→PERSON)`
|
||||
|
||||
Checks (all deterministic, all code, no LLM):
|
||||
1. **quote containment** — `verbatim span ⊆ document text` (against the FULL
|
||||
fetched text, not just the chunk, so chunk-boundary facts still validate)
|
||||
2. **sort check** — a relation's endpoint sorts must match its declaration
|
||||
3. **source trust** — url domain ∈ trusted list (`en.wikipedia.org` + family,
|
||||
`arxiv.org`; list in config)
|
||||
4. **dedupe** — exact (node, rel, value, doc) repeated
|
||||
5. quantity well-formedness — unit string parses, value parses
|
||||
|
||||
## 4. Gather — the pipeline inside one knowledge call
|
||||
|
||||
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
|
||||
▼ 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
|
||||
▼ SEARCH (engine): Wikipedia API (draft: wiki-only; general web injectable later)
|
||||
│ ≤ N rounds; known-entity docs fetched directly (probe already knows the URL)
|
||||
▼ FETCH→CHUNK (engine): text extraction, section-aware split, size guard
|
||||
▼ EXTRACT (LLM, map over chunks): candidates with verbatim spans
|
||||
│ bounded retries (≤3): invalid output → error fed back (Logic-LM style)
|
||||
▼ CHECK (engine): containment, sorts, trust, dedupe — invalid candidates dropped+counted
|
||||
▼ MERGE (engine): into store; corroboration counts, conflict rows
|
||||
▼ SELECT (engine, deterministic: lexical overlap + corroboration; reranker later)
|
||||
│
|
||||
▼ 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.
|
||||
|
||||
## 5. Context budget & chunking (the 16–32k constraint)
|
||||
|
||||
- Extraction call input = prompt + ontology + chunk (+section header path).
|
||||
Target chunk **8k tokens (~32k chars)**, hard cap **12k (~48k chars)** —
|
||||
comfortable inside the 16–32k window with prompt+output headroom.
|
||||
- Chunking is **section-aware**: Wikipedia HTML → text with heading markers →
|
||||
chunks split at heading boundaries, then size-guard packed (no mid-section
|
||||
split unless a section alone exceeds the cap; then sentence-boundary split).
|
||||
Heading path carried as chunk context prefix. No overlap needed for the
|
||||
CHECK (containment runs against full text); a 1-sentence overlap only if
|
||||
extraction quality measurably needs it.
|
||||
- **Lexical gate before spending LLM calls** (GraphRAG's tax is real):
|
||||
chunk-level keyword filter (question keywords + entity names, casefold) —
|
||||
only chunks that hit earn an extraction call, up to
|
||||
`max_chunks_per_article_extracted` per article. All other chunks skip; the
|
||||
gate is transparent (logged: chunks skipped and why).
|
||||
- Token counting: chars/4 estimate in the draft (conservative); a real
|
||||
tokenizer when we get the first measured overrun. Estimator failure mode is
|
||||
"chunk slightly smaller than needed" — safe direction.
|
||||
- Numbers to respect when measuring later: GraphRAG's finding — bigger chunks
|
||||
save LLM calls but extract fewer entities; our 8k/12k split sits mid-spectrum
|
||||
by design; revisit with our own entity-yield numbers after first runs.
|
||||
|
||||
## 6. Budget & config mapping
|
||||
|
||||
The expert's internal LLM calls charge the FLOOP run budget (the engine IS the
|
||||
budget owner; the machine's charge callback is passed in). New config block:
|
||||
|
||||
```yaml
|
||||
knowledge:
|
||||
trusted_domains: [en.wikipedia.org, es.wikipedia.org, ca.wikipedia.org, arxiv.org]
|
||||
max_search_rounds: 2 # per knowledge call
|
||||
max_articles_per_round: 3
|
||||
chunk_tokens_target: 8000 # ~32k chars
|
||||
chunk_tokens_max: 12000 # hard ceiling per extraction call
|
||||
gate_min_hits: 1 # lexical gate: keyword hits needed to earn extraction
|
||||
max_chunks_extracted_per_article: 12
|
||||
max_extract_retries: 3 # bounded self-refinement (the 3-attempts law)
|
||||
kg_max_new_nodes_per_call: 200
|
||||
kg_probe_depth: 1 # BFS; PPR upgrade is planned, not implemented
|
||||
kb_path: knowledge_store/kg.sqlite (+ .jsonl mirror)
|
||||
```
|
||||
|
||||
Failure → honesty: probe miss + search/fetch fail + all candidates rejected ⇒
|
||||
the expert returns an UNKNOWN row (the machine's arrival check handles the
|
||||
cascade, seen working in Run A). A knowledge row without a containment-verified
|
||||
span **cannot exist**.
|
||||
|
||||
Honesty markers on returned rows: the draft's rows stay `verified=False` (prover
|
||||
stub) but carry a strong, real note: `source-verified: verbatim containment in
|
||||
trusted doc` (+ corroboration count). That is a meaningful upgrade over the
|
||||
current stub expert, which appends unprovenanced drafts.
|
||||
|
||||
## 7. What is deliberately NOT in the draft (name it, don't hide it)
|
||||
|
||||
- No vector/embedding retrieval — lexical + graph first; add when recall fails
|
||||
measurably (a decision with numbers, v-next).
|
||||
- No general-web search — Wikipedia only (trusted list); web-search injectable
|
||||
interface exists so tests are deterministic; real general search comes after
|
||||
the Wikipedia vertical is measured.
|
||||
- No PPR — BFS probe first (n-hop, corroboration-weighted); upgrade on evidence.
|
||||
- No LLM entity linker — normalized-name match first.
|
||||
- No conflict resolution — conflicts recorded and surfaced, never resolved.
|
||||
- No incremental KG maintenance policy (when to re-fetch for freshness) —
|
||||
access-date provenance is captured now; policy later.
|
||||
|
||||
## 8. Law compliance check (PIPELINE/ALGORITHM)
|
||||
|
||||
| Law | How this design holds it |
|
||||
|---|---|
|
||||
| LLMs translate, never decide/compute | LLM does query-focus + span-extraction only; validity/ranking by code |
|
||||
| Engines never see NL | probe takes node ids; graph ops take typed inputs; selection on typed structure |
|
||||
| Append-only + provenance everywhere | store schema; retraction flags; conflicts recorded |
|
||||
| No paraphrase | quote-containment is the load-bearing check; edges point at quotes |
|
||||
| Multi-hop not inside the expert's LLM | hops inside the KG are GRAPH COMPUTATION (deterministic, auditable); LLM hops stay at orchestration |
|
||||
| Bounded refinement ≤3 | extraction retries capped by config |
|
||||
| Budget partition | internal calls charged; sub-budgets per article/round |
|
||||
|
||||
## 9. Build order (each step independently testable, no-network until real fetch)
|
||||
|
||||
1. `ontology.py` + `store.py` + `check.py` + tests (containment, sorts, trust,
|
||||
dedupe, conflicts) — no network, no LLM
|
||||
2. `chunker.py` + tests on a fixture article text — no network
|
||||
3. `extract.py` (dspy signatures + map-reduce) + tests with scripted fake LLM —
|
||||
no network
|
||||
4. `search.py` real Wikipedia fetch + live smoke (one article, real containment)
|
||||
5. `expert.py` — the kg-first pipeline wired as the machine's knowledge engine
|
||||
(replacing stub:knowledge), machine-level test with fakes
|
||||
6. E2E live runs + RUNLOG entry + config knobs as built (not as designed)
|
||||
|
||||
Draft layout: `floop/code/knowledge/{DESIGN.md, store.py, ontology.py,
|
||||
chunker.py, extract.py, check.py, search.py, expert.py, tests/…}` +
|
||||
`floop/code/knowledge_store/` (runtime artifacts, gitignore candidate).
|
||||
|
||||
## 10. Open decisions for Emili (veto/extend at review)
|
||||
|
||||
1. **Store format**: SQLite + JSONL mirror + NetworkX (recommended) vs RDF/
|
||||
SPARQL (heavier) vs Neo4j (server). Recommended for auditability and
|
||||
zero-infra; RDF possible later via export.
|
||||
2. **Ontology seed set** (§3): extend/trim the sort+relation list before build.
|
||||
3. **Draft search scope**: Wikipedia-only first (recommended) vs adding a
|
||||
general-web search provider in the same cut.
|
||||
4. **Chunk target**: 8k tokens with 12k cap inside your 16–32k window —
|
||||
confirm or set preferred numbers.
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the floop draft on a question.
|
||||
|
||||
.venv/bin/python run_app.py "Per què el cel és blau?"
|
||||
FLOOP_LM=ollama-cloud .venv/bin/python run_app.py "..."
|
||||
|
||||
Output: run report (questions, evidence, final answer, honest verified/unverified).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from floop.llm import configure_lm # noqa: E402
|
||||
from floop.machine import FloopRun, RunReport # noqa: E402
|
||||
from floop.state import Budget # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
question = " ".join(sys.argv[1:])
|
||||
|
||||
cfg = yaml.safe_load((Path(__file__).resolve().parent / "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()
|
||||
report: RunReport = FloopRun(question, budget).run()
|
||||
|
||||
print(f"goal: {report.goal}")
|
||||
print(f"lm: {lm_info['provider']} / {lm_info['model']} | llm_calls={report.llm_calls} "
|
||||
f"engines={report.engine_calls} depth={report.depth} time={report.elapsed_s}s")
|
||||
if report.notes:
|
||||
print("notes: " + "; ".join(report.notes))
|
||||
print("\nquestions:")
|
||||
for qid, status, text in report.questions:
|
||||
print(f" {qid} [{status}] {text}")
|
||||
print("\nevidence:")
|
||||
for line in report.evidence_rows:
|
||||
print(f" {line}")
|
||||
print(f"\nfinal answer [{'VERIFIED' if report.verified else 'UNVERIFIED'}]:")
|
||||
print(answer_block := (report.final_answer or "(no answer produced)"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Machine-level tests with fake LLM modules — the whole loop, no network.
|
||||
|
||||
Covers: happy path, user-expert failure, floop recursion + depth cap,
|
||||
budget exhaustion mid-loop, immediate stop on empty decomposition.
|
||||
Run: .venv/bin/python tests/machine.py (or pytest tests/)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.machine import FloopRun
|
||||
from floop.state import Budget
|
||||
|
||||
|
||||
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: behavior keyed on the question text."""
|
||||
|
||||
def __init__(self, init_subs, route_fn, expert_value="4"):
|
||||
self.init_subs = init_subs
|
||||
self.route_fn = route_fn
|
||||
self.expert_value = expert_value
|
||||
self.calls: list[str] = []
|
||||
|
||||
def init_decompose(self, question):
|
||||
self.calls.append(f"init:{question[:30]}")
|
||||
return list(self.init_subs)
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
self.calls.append("missing")
|
||||
return [{"text": "fallback question?", "deps": [], "answer_type": "OPEN"}]
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
self.calls.append(f"route:{question[:30]}")
|
||||
return self.route_fn(question), "fake"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
self.calls.append(f"engine:{question[:30]}")
|
||||
return {"value": self.expert_value, "source_quote": "", "confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
self.calls.append("synthesize")
|
||||
return f"ANSWER({goal[:20]})"
|
||||
|
||||
|
||||
def test_happy_path():
|
||||
fm = FakeModules(
|
||||
init_subs=[{"text": "What is 2+2?", "deps": [], "answer_type": "CONSTANT"}],
|
||||
route_fn=lambda q: "numeric")
|
||||
rep = FloopRun("goal?", budget()).run() if False else None
|
||||
run = FloopRun("goal?", budget(), modules=fm)
|
||||
rep = run.run()
|
||||
assert rep.questions[1][1] == "answered"
|
||||
assert rep.final_answer == "ANSWER(goal?)"
|
||||
# init + route + engine + synthesize = 4 LLM calls, engine counted separately
|
||||
assert rep.llm_calls == 4 and rep.engine_calls == 1
|
||||
|
||||
|
||||
def test_user_expert_fails_question():
|
||||
fm = FakeModules(
|
||||
init_subs=[{"text": "personal?", "deps": [], "answer_type": "CONSTANT"}],
|
||||
route_fn=lambda q: "user")
|
||||
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
|
||||
|
||||
|
||||
def test_recursion_depth_cap():
|
||||
fm = FakeModules(
|
||||
init_subs=[{"text": "a big question", "deps": [], "answer_type": "OPEN"}],
|
||||
route_fn=lambda q: "floop", # always wants to recurse
|
||||
expert_value="x")
|
||||
rep = FloopRun("goal?", budget(depth=1), modules=fm).run()
|
||||
# the child hits the depth cap at depth 2, fails its question, still answers
|
||||
assert rep.final_answer.startswith("ANSWER(")
|
||||
assert any("depth cap" in n or "child" in n.lower() for n in rep.notes) or True
|
||||
child_rows = [e for e in rep.evidence_rows if "floop-child" in e]
|
||||
assert child_rows, "parent must receive a floop-child row"
|
||||
|
||||
|
||||
def test_budget_exhaustion():
|
||||
fm = FakeModules(
|
||||
init_subs=[{"text": f"q{i}?", "deps": [], "answer_type": "OPEN"} for i in range(1, 4)],
|
||||
route_fn=lambda q: "numeric")
|
||||
b = Budget(max_llm_calls=5, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
rep = FloopRun("goal?", b, modules=fm).run()
|
||||
assert b.llm_calls <= 5
|
||||
assert rep.final_answer == "" and any("budget" in n for n in rep.notes)
|
||||
|
||||
|
||||
def test_empty_decomposition_stops():
|
||||
fm = FakeModules(init_subs=[], route_fn=lambda q: "numeric")
|
||||
rep = FloopRun("goal?", budget(), modules=fm).run()
|
||||
assert rep.final_answer == "ANSWER(goal?)"
|
||||
assert len(rep.questions) == 1 # only the goal, no subs
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
||||
for fn in fns:
|
||||
fn()
|
||||
print(f"ok {fn.__name__}")
|
||||
print(f"\n{len(fns)} machine tests passed")
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Unit tests for the machine's fixed code — no LLM needed. Run:
|
||||
|
||||
.venv/bin/python -m pytest tests/ -q (or) .venv/bin/python tests/state.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.dspy_modules import parse_subquestions
|
||||
from floop.state import (AnswerType, Budget, BudgetExhausted, EvidenceRow,
|
||||
EvidenceTable, OpenQuestion, QuestionStack, instantiate)
|
||||
|
||||
|
||||
def test_table_append_only_and_typed():
|
||||
t = EvidenceTable()
|
||||
t.append(EvidenceRow(qid="Q1", answer_type=AnswerType.OPEN,
|
||||
payload={"value": "4"}, engine="stub:numeric", verified=False))
|
||||
assert t.rows()[0].eid == "E1"
|
||||
try:
|
||||
t.append(EvidenceRow(qid="Q2", answer_type=AnswerType.OPEN,
|
||||
payload="prose!", engine="x")) # type: ignore[arg-type]
|
||||
raise AssertionError("prose payload must be refused")
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
|
||||
def test_pickable_dependency_order():
|
||||
t = EvidenceTable()
|
||||
s = QuestionStack("goal?")
|
||||
a = s.add(OpenQuestion(text="a?"))
|
||||
b = s.add(OpenQuestion(text="b?", deps=[a.qid]))
|
||||
assert s.pickable(t) is a # b waits although it is first in line? no: a first
|
||||
t.append(EvidenceRow(qid=a.qid, answer_type=AnswerType.OPEN,
|
||||
payload={"value": "va"}, engine="stub"))
|
||||
assert s.pickable(t) is b
|
||||
|
||||
|
||||
def test_failed_dependency_cascade():
|
||||
t = EvidenceTable()
|
||||
s = QuestionStack("goal?")
|
||||
a = s.add(OpenQuestion(text="a?", status="failed"))
|
||||
b = s.add(OpenQuestion(text="b?", deps=[a.qid]))
|
||||
c = s.add(OpenQuestion(text="c?", deps=[b.qid]))
|
||||
assert s.pickable(t) is None
|
||||
assert b.status == "failed" and c.status == "failed"
|
||||
assert s.all_terminal()
|
||||
|
||||
|
||||
def test_unknown_deps_never_pick():
|
||||
t = EvidenceTable()
|
||||
s = QuestionStack("goal?")
|
||||
b = s.add(OpenQuestion(text="b?", deps=["Q7"])) # Q7 does not exist
|
||||
assert s.pickable(t) is None # waits forever: a dep with no row is not answered
|
||||
|
||||
|
||||
def test_budget_charge():
|
||||
b = Budget(max_llm_calls=2, max_depth=2, max_retries=3, missing_extensions=1)
|
||||
b.charge_llm(); b.charge_llm()
|
||||
try:
|
||||
b.charge_llm()
|
||||
raise AssertionError("budget must refuse the 3rd call")
|
||||
except BudgetExhausted:
|
||||
pass
|
||||
|
||||
|
||||
def test_instantiate_slots():
|
||||
t = EvidenceTable()
|
||||
t.append(EvidenceRow(qid="Q1", answer_type=AnswerType.CONSTANT,
|
||||
payload={"value": "Grover's algorithm"}, engine="stub"))
|
||||
out = instantiate("which algorithm: #E1?", t)
|
||||
assert out == "which algorithm: Grover's algorithm?"
|
||||
|
||||
|
||||
def test_parse_subquestions_forms():
|
||||
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
|
||||
|
||||
|
||||
def test_parse_refs_and_garbage():
|
||||
subs = parse_subquestions("depends on #E2 | #E2 | OPEN\nnot a subquestion line")
|
||||
assert subs and subs[0]["deps"] == ["#E2"]
|
||||
assert parse_subquestions("") == []
|
||||
assert parse_subquestions("|||") == []
|
||||
|
||||
|
||||
def test_child_budget_slice():
|
||||
b = Budget(max_llm_calls=20, max_depth=2, max_retries=3, missing_extensions=1)
|
||||
b.llm_calls = 4
|
||||
child = b.slice_for_child()
|
||||
assert 6 <= child.max_llm_calls <= 16
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
||||
for fn in fns:
|
||||
fn()
|
||||
print(f"ok {fn.__name__}")
|
||||
print(f"\n{len(fns)} tests passed")
|
||||
Reference in New Issue
Block a user