274 lines
13 KiB
Python
274 lines
13 KiB
Python
"""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 re
|
||
from enum import Enum
|
||
|
||
import dspy
|
||
from floop.llm import predict
|
||
from pydantic import BaseModel
|
||
|
||
from .state import AnswerType
|
||
|
||
try:
|
||
from dspy.utils.exceptions import AdapterParseError
|
||
except ImportError: # pragma: no cover — dspy <3.x
|
||
AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""})
|
||
|
||
from .anonymize import (NamedEntityRecognitionSignature, apply_mask,
|
||
identity_answer, restore_mask)
|
||
|
||
|
||
class Subquestion(BaseModel):
|
||
"""One open subquestion in the goal's decomposition."""
|
||
text: str = dspy.OutputField(desc="the subquestion, phrased as a question")
|
||
depends_on: list[int] = dspy.OutputField(
|
||
desc="1-based positions of the subquestions whose answers this one needs first; empty when none")
|
||
answer_type: AnswerType = dspy.OutputField(
|
||
desc="OPEN for a single value, FUNCTION for a formula, INTERVAL for a range, "
|
||
"CONSTANT for a universal constant, LIST for an enumeration of things, "
|
||
"DATE for a specific date")
|
||
|
||
|
||
class InitSignature(dspy.Signature):
|
||
"""You are the INIT step of a reasoning machine. Your job is to make the
|
||
final answer a direct lookup. Follow this procedure:
|
||
1. Re-read the question and:
|
||
1.1. List every word or phrase that could refer to more than one
|
||
real thing or moment.
|
||
1.2. Think: what information or knowledge do I need to answer this?
|
||
2. HIDDEN PRECONDITIONS: for every entity, relation, or value that the
|
||
question assumes but does not state and that is required to answer
|
||
it (an implicit owner, role, time window, or intermediate fact),
|
||
write an explicit subquestion that resolves it. NEVER collapse a
|
||
hidden precondition into the final subquestion. Always use the most
|
||
generic term to ask about them.
|
||
3. Write the subquestion that produces the final answer, with
|
||
depends_on pointing at the preconditions it needs.
|
||
Order the subquestions by dependency (1-4 in total).
|
||
Masked entities like PERSON_1 or ORGANIZATION_1 are ALREADY-RESOLVED named
|
||
entities from the question — treat each as a known specific entity; do not
|
||
ask what or who the placeholder is."""
|
||
question: str = dspy.InputField()
|
||
subquestions: list[Subquestion] = dspy.OutputField(
|
||
desc="1-4 subquestions in dependency order; never empty")
|
||
|
||
|
||
class Attendant(str, Enum):
|
||
"""The closed set of attendants the ROUTE step may pick."""
|
||
KNOWLEDGE = "knowledge"
|
||
LOGIC = "logic"
|
||
ANALYTIC = "analytic"
|
||
NUMERIC = "numeric"
|
||
FLOOP = "floop"
|
||
USER = "user"
|
||
|
||
|
||
class RouteSignature(dspy.Signature):
|
||
"""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: Attendant = dspy.OutputField(
|
||
desc="knowledge: factual lookups from trusted sources; logic: deriving conclusions "
|
||
"from provided premises, counting over evidence; analytic: equations/symbolic "
|
||
"relations over provided quantities; numeric: closed arithmetic over provided "
|
||
"numbers; floop: needs a sub-goal; user: nothing else plausibly answers it")
|
||
reason: str = dspy.OutputField(desc="one sentence, for the log")
|
||
|
||
|
||
class Confidence(str, Enum):
|
||
"""The expert's honest self-assessment (baseline draft — no engine
|
||
verifies the expert yet)."""
|
||
HIGH = "high"
|
||
MEDIUM = "medium"
|
||
LOW = "low"
|
||
|
||
|
||
class ExpertSignature(dspy.Signature):
|
||
"""You are an expert attendant answering a small, focused subquestion.
|
||
Use the evidence rows when they answer it; otherwise answer from your own
|
||
knowledge. This is a BASELINE draft: no engine verifies you yet, so state
|
||
your honest confidence. Say UNKNOWN only if you genuinely do not know."""
|
||
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; may be empty")
|
||
value: str = dspy.OutputField(desc="the answer value in its declared type, or 'UNKNOWN'")
|
||
source_quote: str = dspy.OutputField(
|
||
desc="VERBATIM text from the given evidence if the answer comes from it; EMPTY when answering from your own knowledge")
|
||
confidence: Confidence = dspy.OutputField(
|
||
desc="high: the evidence or your knowledge settles it; medium: plausible "
|
||
"but not fully settled; low: a guess you would verify first")
|
||
|
||
|
||
class MissingSignature(dspy.Signature):
|
||
"""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: list[Subquestion] = dspy.OutputField(
|
||
desc="1-3 subquestions that would close the gap; empty when nothing helps")
|
||
|
||
|
||
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, citing them; every
|
||
number or fact carries its row id. State the answer plainly — the system
|
||
marks verification status separately, do not hedge about it."""
|
||
goal: str = dspy.InputField()
|
||
evidence: str = dspy.InputField()
|
||
unverified: bool = dspy.InputField(
|
||
desc="True when the prover could not verify the answer's derivability from the evidence")
|
||
final_answer: str = dspy.OutputField(desc="answer in natural language; cite only given row ids; no outside facts")
|
||
|
||
|
||
class FloopModules:
|
||
"""All LLM entry points of the draft. Each returns a dspy.Prediction."""
|
||
|
||
def __init__(self) -> None:
|
||
self.init = predict(InitSignature)
|
||
self.route = predict(RouteSignature)
|
||
self.expert = predict(ExpertSignature)
|
||
self.missing = predict(MissingSignature)
|
||
self.answer = predict(AnswerSignature)
|
||
self.mask = predict(NamedEntityRecognitionSignature)
|
||
|
||
def init_decompose(self, question: str) -> tuple[list[dict], str]:
|
||
"""(parsed subquestions, raw model output). The machine decides what
|
||
an empty parse means: empty raw = the question is atomic; non-empty
|
||
raw that parses to nothing = model garbage (run I) — degrade.
|
||
|
||
Typed output: a response that violates the Subquestion schema raises
|
||
AdapterParseError AFTER dspy's own JSON re-ask; its lm_response IS
|
||
the raw garbage — hand it back as the degrade signal.
|
||
|
||
ANONYMIZATION (his design): named entities are masked before INIT
|
||
so the model decomposes shape, not identity — restored in the
|
||
returned subquestions, deterministically. Identity questions about
|
||
the placeholders (PR-16 live run: 'who is PERSON_1?') carry a
|
||
KNOWN answer; the machine seeds them as evidence instead of
|
||
routing them to an expert."""
|
||
masked, restore = self.anonymize(question)
|
||
try:
|
||
pred = self.init(question=masked)
|
||
except AdapterParseError as e:
|
||
return [], (e.lm_response or "unparseable response")
|
||
subs = []
|
||
for s in self._subs_from_typed(pred.subquestions):
|
||
# identity detection on the MASKED text (placeholders still
|
||
# present); then restore for the machine's question text
|
||
ans = identity_answer(s["text"], restore)
|
||
text = restore_mask(s["text"], restore)
|
||
if ans is not None:
|
||
s = {**s, "known_answer": ans} # seeded by the machine
|
||
subs.append({**s, "text": text})
|
||
return subs, ""
|
||
|
||
def anonymize(self, question: str) -> tuple[str, dict]:
|
||
"""Mask named entities to typed placeholders. No entity found (or the
|
||
mask call dies) -> the question passes unchanged, mask map empty."""
|
||
try:
|
||
pred = self.mask(text=question)
|
||
entities = pred.entities or []
|
||
except AdapterParseError:
|
||
return question, {}
|
||
masked, restore = apply_mask(question, entities)
|
||
return masked, restore
|
||
|
||
@staticmethod
|
||
def _subs_from_typed(subs) -> list[dict]:
|
||
"""Typed Subquestion objects -> machine dicts. A bare number is a
|
||
line number, never a question (run I law kept)."""
|
||
out = []
|
||
for s in (subs or []):
|
||
text = (s.text or "").strip()
|
||
if not text or text.isdigit():
|
||
continue
|
||
out.append({"text": text, "deps": list(s.depends_on or []),
|
||
"answer_type": s.answer_type})
|
||
return out
|
||
|
||
def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
|
||
try:
|
||
pred = self.missing(goal=goal, evidence=evidence)
|
||
except AdapterParseError:
|
||
return []
|
||
return self._subs_from_typed(pred.subquestions)
|
||
|
||
def route_question(self, question: str, catalog: str, evidence: str) -> tuple[str, str]:
|
||
"""Typed attendant: the enum is the closed contract. A response
|
||
outside the set raises AdapterParseError after dspy's re-ask —
|
||
the machine's invalid-attendant branch stays as a contract guard."""
|
||
pred = self.route(question=question, catalog=catalog, evidence=evidence)
|
||
return str(pred.attendant.value), 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": str(pred.confidence.value),
|
||
}
|
||
|
||
def synthesize(self, goal: str, evidence: str, unverified: bool) -> str:
|
||
pred = self.answer(goal=goal, evidence=evidence,
|
||
unverified=unverified)
|
||
return pred.final_answer.strip()
|
||
|
||
|
||
_LINE_NO = re.compile(r"\d{1,2}[.)]?")
|
||
_ENUM = re.compile(r"^\d{1,2}[.)]?\s*[-–:]?\s+")
|
||
|
||
|
||
def _clean_qtext(t: str) -> str:
|
||
"""Strip a leading enumerator ('1.', '2)', '3 -') from a subquestion."""
|
||
return _ENUM.sub("", t.strip()).strip()
|
||
|
||
|
||
def parse_subquestions(raw: str) -> list[dict]:
|
||
""">> parse the piped lines from INIT/MISSING: text | deps | answer_type.
|
||
|
||
The piped format is the contract; models still decorate it (run I):
|
||
qwen wrote its own line numbers as an extra first pipe field
|
||
('1 | Who was the President before Pedro Sanchez? | none | OPEN') and
|
||
the naive parse took '1' as the text — Q1 routed as 'numeric' on the
|
||
literal question '1'. The parser now shifts the numbered form and
|
||
drops any field that is a bare number: a routable question is text."""
|
||
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("|")]
|
||
# qwen's line-number prefix: an extra first field, bare number
|
||
if len(parts) >= 4 and _LINE_NO.fullmatch(parts[0]):
|
||
parts = parts[1:]
|
||
text = _clean_qtext(parts[0])
|
||
if not text or _LINE_NO.fullmatch(text):
|
||
continue # a number is a line number, never a question
|
||
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
|