Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
109885773c | ||
|
|
5c97fbf50a | ||
|
|
efd539c128 |
@@ -42,6 +42,14 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
(charge happens before the Predict runs), so 08-extract.txt IS the
|
||||
call 8/80 of run G that hung for minutes. Plus size/duration lines in
|
||||
run.log; the exact prompt is in the file, log stays line-based.
|
||||
|
||||
RE-ASK METER (run L): dspy's chat adapter, on a parse failure, re-fires
|
||||
the SAME module's LM call through its JSON fallback — an extra wire call
|
||||
the budget counter never charged (9/80 logged, 10 on the wire, the
|
||||
second burning 340s of GPU). The meter sees them (same module depth in
|
||||
the stack twice), charges the budget via an optional meter hook, and
|
||||
logs the line — dspy's BEHAVIOUR is untouched (his call: the fallback
|
||||
stays; it is future self-improvement signal, not a bug to fix).
|
||||
"""
|
||||
|
||||
def __init__(self, streams) -> None:
|
||||
@@ -50,6 +58,8 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
||||
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
||||
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
|
||||
self.reasks = 0 # LM calls the budget did not charge
|
||||
self.meter = None # callable(str stage) -> None; budget charge
|
||||
|
||||
# -- dspy plumbing -------------------------------------------------------
|
||||
|
||||
@@ -57,6 +67,7 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
sig = getattr(getattr(instance, "signature", None), "__name__", None)
|
||||
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
|
||||
self._stack.append(label)
|
||||
self._fresh_forward = True # this forward's first LM call is not a re-ask
|
||||
|
||||
def on_module_end(self, call_id, outputs, exception):
|
||||
if self._stack:
|
||||
@@ -74,6 +85,26 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
if isinstance(m, dict)
|
||||
)
|
||||
chars = len(text)
|
||||
# RE-ASK METER: a second LM call with NO new module forward between
|
||||
# them is dspy's adapter fallback re-firing inside the same Predict
|
||||
# (ChatAdapter catches AdapterParseError and re-calls via JSONAdapter)
|
||||
# — an extra wire call the budget did not charge. Consecutive SAME-
|
||||
# stage calls from DIFFERENT forwards (the ablation rounds) are NOT
|
||||
# re-asks: each round opens its own module.
|
||||
fresh = getattr(self, "_fresh_forward", False)
|
||||
self._fresh_forward = False
|
||||
self._lm_seen = getattr(self, "_lm_seen", 0) + 1
|
||||
reask = self._lm_seen > 1 and not fresh
|
||||
if reask:
|
||||
self.reasks += 1
|
||||
if streams is not None:
|
||||
streams.log(f"re-ask detected: stage={label} "
|
||||
f"(adapter parse-failure fallback, charged to budget)")
|
||||
if self.meter is not None:
|
||||
try:
|
||||
self.meter(label)
|
||||
except Exception: # noqa: BLE001 — metering must never kill a run
|
||||
pass
|
||||
if streams is not None:
|
||||
n = streams.bump_prompt_seq()
|
||||
fn = f"{n:02d}-{label}.txt"
|
||||
|
||||
@@ -91,6 +91,14 @@ class FloopRun:
|
||||
self.knowledge_engine = knowledge_engine # None -> baseline LLM expert
|
||||
self.notes: list[str] = []
|
||||
self.engine_calls = 0
|
||||
# RE-ASK METER (run L): dspy's adapter fallback fires extra LM calls
|
||||
# the budget never charged. The prompt-log callback sees them; wire
|
||||
# its meter to our budget so the count is honest. The BEHAVIOUR of
|
||||
# dspy stays untouched (his call: the fallback is future
|
||||
# self-improvement signal, not a bug).
|
||||
from .llm import _PROMPT_LOG
|
||||
if _PROMPT_LOG is not None:
|
||||
_PROMPT_LOG.meter = self._meter_reask
|
||||
|
||||
# ---- budget -----------------------------------------------------------
|
||||
|
||||
@@ -99,6 +107,16 @@ class FloopRun:
|
||||
self.streams.log(f"budget llm_calls={self.budget.llm_calls}"
|
||||
f"/{self.budget.max_llm_calls} depth={self.depth}")
|
||||
|
||||
def _meter_reask(self, stage: str) -> None:
|
||||
"""The prompt-log callback detected an adapter re-ask: charge the
|
||||
budget for the extra wire call (a re-ask may hit the ceiling but
|
||||
never kills the run mid-step), and note it for the report."""
|
||||
try:
|
||||
self.budget.charge_llm()
|
||||
except BudgetExhausted:
|
||||
pass # ceiling reached: the call already happened; note only
|
||||
self.notes.append(f"re-ask charged: stage={stage}")
|
||||
|
||||
# ---- the loop (ALGORITHM.md §2) ----------------------------------------
|
||||
|
||||
def run(self) -> RunReport:
|
||||
|
||||
+51
-18
@@ -24,9 +24,9 @@ import dspy
|
||||
from .checks import check_candidate, quote_containment
|
||||
from .chunker import chunk_page
|
||||
from .skim import find_quantities, skim_article
|
||||
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
|
||||
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
|
||||
SkimPromoteSignature, TranslateSignature,
|
||||
VerifyCountSignature, parse_facts)
|
||||
VerifyCountSignature)
|
||||
from .store import KnowledgeStore, norm_name
|
||||
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
||||
tables_as_chunks, format_table_frag, parse_stop_table)
|
||||
@@ -501,14 +501,46 @@ class KnowledgeExpert:
|
||||
if (not value or value.upper() == "UNKNOWN" or not rows):
|
||||
return answer
|
||||
|
||||
# The supporting rows for the PICKED value: those whose dst or quote
|
||||
# carries it. Masked cumulatively each round; the store never
|
||||
# changes — the view handed to the judge shrinks, nothing else.
|
||||
# The supporting rows for the PICKED value. DST-FIRST LAW (run L):
|
||||
# when a row has a meaningful dst it is the VALUE BEARER — quotes
|
||||
# interleave readings in one paragraph ('... Secretary-General ...
|
||||
# president of Socialist International ...' is ONE quote), so
|
||||
# quote-matching over-masks and the audit dies silent at round 1.
|
||||
# The quote is a fallback ONLY for rows whose dst is empty/numeric.
|
||||
_NUMERIC_RE = re.compile(r"^[\d\s.,:+\-/–—%]+$")
|
||||
|
||||
def _dst(r) -> str:
|
||||
return (getattr(r, "dst", "") or "").strip()
|
||||
|
||||
def _dst_meaningful(r) -> bool:
|
||||
d = _dst(r)
|
||||
return bool(d) and not _NUMERIC_RE.match(d)
|
||||
|
||||
def _carries(r) -> bool:
|
||||
dst = (getattr(r, "dst", "") or "").strip().casefold()
|
||||
quote = (getattr(r, "quote", "") or "").strip().casefold()
|
||||
v = value.casefold()
|
||||
return v in dst or v in quote
|
||||
if _dst_meaningful(r):
|
||||
return v in _dst(r).casefold()
|
||||
quote = (getattr(r, "quote", "") or "").strip().casefold()
|
||||
return v in quote
|
||||
|
||||
def _carries_target(r, val: str) -> bool:
|
||||
"""DST-FIRST law, parameterized for a round's surviving value.
|
||||
|
||||
The judge's value may be an OFFICE DESCRIPTION, not the dst
|
||||
entity itself ('prime minister of Spain' vs dst='Spain') —
|
||||
resolve the row by reciprocal token containment: the dst
|
||||
names the entity, the value describes the reading; overlap
|
||||
means this row carried it."""
|
||||
v = val.casefold()
|
||||
if _dst_meaningful(r):
|
||||
d = _dst(r).casefold()
|
||||
if v == d or v in d or d in v:
|
||||
return True
|
||||
vt = set(WORD_RE.findall(v))
|
||||
dt = set(WORD_RE.findall(d))
|
||||
return bool(vt & dt) if vt and dt else False
|
||||
quote = (getattr(r, "quote", "") or "").strip().casefold()
|
||||
return v in quote
|
||||
|
||||
support = [r for r in rows if _carries(r)]
|
||||
if not support:
|
||||
@@ -530,11 +562,9 @@ class KnowledgeExpert:
|
||||
if key in seen:
|
||||
break # same value again: corroboration, not ambiguity
|
||||
seen.add(key)
|
||||
# which surviving row produced this reading? the one whose
|
||||
# dst/quote carries it — for the report and the next mask
|
||||
src_row = next((r for r in view
|
||||
if re_val.casefold() in (r.dst or "").casefold()
|
||||
or re_val.casefold() in (r.quote or "").casefold()), None)
|
||||
# which surviving row produced this reading? DST-FIRST here too
|
||||
# — same law as the pick's mask, for the report and the next mask
|
||||
src_row = next((r for r in view if _carries_target(r, re_val)), None)
|
||||
alternatives.append({
|
||||
"value": re_val,
|
||||
"quote": re_ans.get("quote", ""),
|
||||
@@ -542,8 +572,7 @@ class KnowledgeExpert:
|
||||
else re_ans.get("url", "")),
|
||||
})
|
||||
# mask this reading's own support too — next round hunts a third
|
||||
new_support = [r for r in view if re_val.casefold() in (
|
||||
(r.dst or "").casefold() + " " + (r.quote or "").casefold())]
|
||||
new_support = [r for r in view if _carries_target(r, re_val)]
|
||||
if not new_support:
|
||||
break
|
||||
masked |= set(id(r) for r in new_support)
|
||||
@@ -935,8 +964,10 @@ class KnowledgeExpert:
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
|
||||
for cand in parse_facts(raw.facts):
|
||||
for cand in (raw.facts or []):
|
||||
self._checked += 1
|
||||
cand = {"subject": cand.subject, "relation": cand.relation,
|
||||
"object": cand.object, "quote": cand.quote}
|
||||
ok, reason = check_candidate(cand, page.text)
|
||||
if not ok:
|
||||
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
||||
@@ -972,17 +1003,19 @@ class KnowledgeExpert:
|
||||
charge_llm()
|
||||
heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})"
|
||||
raw = self.extract(question=question, heading=heading, text=text)
|
||||
if parse_stop_table(raw.facts):
|
||||
if raw.stop:
|
||||
stopped.add(frag["table_idx"])
|
||||
self._log(f"extractor STOP_TABLE: table {frag['table_idx']} "
|
||||
f"({frag['caption'][:40]!r}) not relevant — "
|
||||
f"skipping {frag['of'] - frag['part']} remaining parts",
|
||||
think=True)
|
||||
continue
|
||||
for cand in parse_facts(raw.facts):
|
||||
for cand in (raw.facts or []):
|
||||
self._checked += 1
|
||||
# containment against prose + FULL table text: the fragment is
|
||||
# rendered from the same rows, so quotes verify honestly
|
||||
cand = {"subject": cand.subject, "relation": cand.relation,
|
||||
"object": cand.object, "quote": cand.quote}
|
||||
ok, reason = check_candidate(cand, containment)
|
||||
if not ok:
|
||||
self._log(f"frag candidate rejected ({reason}): "
|
||||
|
||||
+23
-14
@@ -7,6 +7,16 @@ the FULL document text — so chunking can never fake a quote.
|
||||
from __future__ import annotations
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Fact(BaseModel):
|
||||
"""One fact extracted from a text, with its verbatim supporting quote."""
|
||||
subject: str = dspy.OutputField(desc="the fact's subject entity")
|
||||
relation: str = dspy.OutputField(desc="the relation between subject and object")
|
||||
object: str = dspy.OutputField(desc="the fact's object / value")
|
||||
quote: str = dspy.OutputField(
|
||||
desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)")
|
||||
|
||||
|
||||
class TranslateSignature(dspy.Signature):
|
||||
@@ -24,21 +34,21 @@ class TranslateSignature(dspy.Signature):
|
||||
|
||||
class ExtractSignature(dspy.Signature):
|
||||
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
||||
extract facts that help answer the question. Each fact is one line:
|
||||
subject | relation | object | verbatim quote from the text.
|
||||
The quote must be the FULL sentence or table ROW that states the fact,
|
||||
extract the facts that help answer the question. Each fact carries its
|
||||
verbatim quote: the FULL sentence or table ROW that states the fact,
|
||||
copied exactly (at least 10 characters). Only facts the text states;
|
||||
no inference.
|
||||
If the text is a fragment of a larger TABLE and you can already tell
|
||||
from its caption/headers that this table cannot contain anything
|
||||
relevant to the question (wrong subject entirely), reply with the
|
||||
single word STOP_TABLE and no facts. Do NOT use STOP_TABLE for text
|
||||
that is merely hard — only when the table's subject is wrong."""
|
||||
If the text is a fragment of a larger TABLE whose caption/headers show
|
||||
its subject is wrong for the question, set stop=True with no facts.
|
||||
Do NOT stop for text that is merely hard — only when the table's
|
||||
subject is wrong."""
|
||||
question: str = dspy.InputField()
|
||||
heading: str = dspy.InputField(desc="section path of this chunk; context only")
|
||||
text: str = dspy.InputField()
|
||||
facts: str = dspy.OutputField(
|
||||
desc="one fact per line: subject | relation | object | verbatim quote; empty if none; or STOP_TABLE if this table fragment's subject is wrong for the question")
|
||||
facts: list[Fact] = dspy.OutputField(
|
||||
desc="the extracted facts; empty list if none")
|
||||
stop: bool = dspy.OutputField(
|
||||
desc="True when this table fragment's subject is wrong for the question")
|
||||
|
||||
|
||||
class AnswerFromKG(dspy.Signature):
|
||||
@@ -102,10 +112,9 @@ class SkimPromoteSignature(dspy.Signature):
|
||||
|
||||
|
||||
def parse_facts(raw: str) -> list[dict]:
|
||||
"""Parse the extractor's piped lines; malformed lines are dropped+counted.
|
||||
|
||||
Split into AT MOST 4 fields — the quote is the last field and may itself
|
||||
contain pipes (table rows like 'France | 68,635,900 | 15.2%')."""
|
||||
"""LEGACY pipe parser — kept ONLY for tests that script extractor
|
||||
responses as text. Production code consumes typed `Fact` objects from
|
||||
dspy directly (see ExtractSignature.facts). Do not use in new code."""
|
||||
out: list[dict] = []
|
||||
for line in (raw or "").strip().splitlines():
|
||||
line = line.strip()
|
||||
|
||||
@@ -256,6 +256,97 @@ def test_engine_and_machine_wiring():
|
||||
print("ok: wiring — audit renamed, role prefixes gone, log/notes/render keep AMBIGUOUS")
|
||||
|
||||
|
||||
def test_interleaved_quotes_flag_all_three():
|
||||
"""RUN-L REGRESSION: one paragraph quote carrying ALL THREE readings
|
||||
(the pick's own quote was the PSOE sentence). The dst-first mask must
|
||||
keep the other rows alive: all three offices flagged, in order."""
|
||||
Q_WHOLE = ("A member of the Spanish Socialist Workers' Party (PSOE), he "
|
||||
"is also Secretary-General of the party since 2017, and is "
|
||||
"the ninth president of Socialist International since 2022.")
|
||||
rows = [
|
||||
R("Pedro Sánchez", "prime minister of Spain since 2018", "Spain",
|
||||
quote=Q_WHOLE),
|
||||
R("Pedro Sánchez", "secretary-general of PSOE since 2017", "PSOE",
|
||||
quote=Q_WHOLE),
|
||||
R("Pedro Sánchez", "president of Socialist International since 2022",
|
||||
"Socialist International", quote=Q_WHOLE),
|
||||
]
|
||||
order = {"Socialist International": 0, "prime minister of Spain": 1,
|
||||
"secretary-general of PSOE": 2}
|
||||
state = {"seen": "Socialist International"}
|
||||
|
||||
def judge(question, rws, charge_llm=None):
|
||||
# picks by priority: SI if visible, else PM, else SG
|
||||
vals = [str(r.dst) for r in rws]
|
||||
if "Socialist International" in vals:
|
||||
return {"value": "Socialist International", "quote": Q_WHOLE,
|
||||
"url": "u"}
|
||||
if "Spain" in vals:
|
||||
return {"value": "prime minister of Spain", "quote": Q_WHOLE,
|
||||
"url": "u"}
|
||||
if "PSOE" in vals:
|
||||
return {"value": "secretary-general of PSOE", "quote": Q_WHOLE,
|
||||
"url": "u"}
|
||||
return {"value": "UNKNOWN", "quote": "", "url": ""}
|
||||
|
||||
e = make_expert(judge=judge)
|
||||
ans = e._audit_ambiguity(Q_PEDRO, {"value": "Socialist International",
|
||||
"quote": Q_WHOLE, "url": "u"}, rows)
|
||||
assert ans.get("ambiguous") is True, ans
|
||||
alts = [a["value"] for a in ans["alternatives"]]
|
||||
assert alts == ["prime minister of Spain",
|
||||
"secretary-general of PSOE"], alts
|
||||
# run-L failure mode: the OLD quote-matching mask killed round 1
|
||||
assert all(a["quote"] == Q_WHOLE for a in ans["alternatives"])
|
||||
print("ok: run-L regression — interleaved one-paragraph quote flags all 3")
|
||||
|
||||
|
||||
def test_office_description_value_resolves_row():
|
||||
"""The judge's round value may be an OFFICE DESCRIPTION ('prime
|
||||
minister of Spain') while the row's dst is the ENTITY ('Spain') —
|
||||
reciprocal token containment must resolve and mask the right row,
|
||||
without eating the unrelated PSOE row (or the loop dies after one
|
||||
alternative). Shape: pick=SI, round 1 returns the PM description."""
|
||||
rows = [R("X", "president of", "Socialist International"),
|
||||
R("X", "prime minister of", "Spain"),
|
||||
R("X", "secretary-general of", "PSOE")]
|
||||
|
||||
def judge(question, rws, charge_llm=None):
|
||||
dsts = {str(r.dst) for r in rws}
|
||||
if "Socialist International" in dsts:
|
||||
return {"value": "Socialist International", "quote": "", "url": "u"}
|
||||
if "Spain" in dsts:
|
||||
# OFFICE DESCRIPTION, not the dst entity
|
||||
return {"value": "prime minister of Spain", "quote": "", "url": "u"}
|
||||
if "PSOE" in dsts:
|
||||
return {"value": "secretary-general of PSOE", "quote": "", "url": "u"}
|
||||
return {"value": "UNKNOWN", "quote": "", "url": ""}
|
||||
|
||||
e = make_expert(judge=judge)
|
||||
ans = e._audit_ambiguity("What is X?", {"value": "Socialist International",
|
||||
"quote": "", "url": "u"}, rows)
|
||||
assert ans.get("ambiguous") is True, ans
|
||||
alts = [a["value"] for a in ans["alternatives"]]
|
||||
# PM's description resolved its Spain row; PSOE survived round 1
|
||||
assert alts == ["prime minister of Spain",
|
||||
"secretary-general of PSOE"], alts
|
||||
print("ok: office-description value resolves its row (token overlap)")
|
||||
|
||||
|
||||
def test_numeric_dst_falls_back_to_quote():
|
||||
"""A date dst is NOT meaningful: the quote carries the value there.
|
||||
The old numeric dsts (dates) must never mask text-bearing rows."""
|
||||
rows = [R("X", "term start", "2 June 2018",
|
||||
quote="took office on 2 June 2018"),
|
||||
R("Y", "population", "48 million")]
|
||||
e = make_expert(judge=lambda *a: {"value": "UNKNOWN"})
|
||||
ans = e._audit_ambiguity("When did X start?", {"value": "2 June 2018",
|
||||
"quote": "", "url": "u"},
|
||||
rows)
|
||||
assert "ambiguous" not in ans, ans
|
||||
print("ok: numeric dst uses the quote fallback, stays silent")
|
||||
|
||||
|
||||
def main():
|
||||
test_pedro_flags()
|
||||
test_counterexamples_silent()
|
||||
@@ -264,6 +355,9 @@ def main():
|
||||
test_single_source_silent()
|
||||
test_rounds_cap()
|
||||
test_engine_and_machine_wiring()
|
||||
test_interleaved_quotes_flag_all_three()
|
||||
test_office_description_value_resolves_row()
|
||||
test_numeric_dst_falls_back_to_quote()
|
||||
print("\nablation ambiguity tests passed")
|
||||
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
from knowledge.wiki import (parse_tables, tables_as_chunks, format_table_frag,
|
||||
parse_stop_table)
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
from knowledge.extract import Fact
|
||||
from knowledge.store import KnowledgeStore
|
||||
from knowledge.wiki import WikiPage
|
||||
|
||||
@@ -91,23 +92,26 @@ def test_process_page_fragments():
|
||||
wikitext=WIKITEXT_2TABLES)
|
||||
page.tables = parse_tables(WIKITEXT_2TABLES)
|
||||
|
||||
# scripted extractor: world-table parts -> STOP_TABLE; Italy table -> one fact
|
||||
# scripted extractor: world-table parts -> stop=True; Italy table -> one Fact
|
||||
calls = []
|
||||
|
||||
class FakeOut:
|
||||
def __init__(self, facts):
|
||||
def __init__(self, facts, stop=False):
|
||||
self.facts = facts
|
||||
self.stop = stop
|
||||
|
||||
def fake_extract(question, heading, text, _calls=calls):
|
||||
_calls.append((question, heading, text))
|
||||
if "World rivers" in text:
|
||||
return FakeOut("STOP_TABLE")
|
||||
return FakeOut([], stop=True)
|
||||
if "Rivers of Italy" in text:
|
||||
# quote = the full rendered row context (header + row), verbatim
|
||||
# from the fragment the extractor saw
|
||||
return FakeOut("Po | Flow at the mouth | 1540 m3/s | "
|
||||
"River | Flow at the mouth Po | 1540")
|
||||
return FakeOut("")
|
||||
return FakeOut([Fact(
|
||||
subject="Po", relation="Flow at the mouth",
|
||||
object="1540 m3/s",
|
||||
quote="River | Flow at the mouth Po | 1540")])
|
||||
return FakeOut([])
|
||||
|
||||
e.extract = fake_extract
|
||||
|
||||
|
||||
@@ -190,10 +190,8 @@ def part_of(frag: dict) -> str:
|
||||
|
||||
|
||||
def parse_stop_table(out_text: str) -> bool:
|
||||
"""True when the extractor's output names this table as not relevant for
|
||||
the question. The extractor may write STOP_TABLE for a fragment's table
|
||||
after seeing its identity (caption/header) — fixed code then skips all
|
||||
remaining fragments of THAT table (never other tables)."""
|
||||
"""LEGACY textual STOP_TABLE detector — kept only for tests. Production
|
||||
code reads the typed `stop: bool` field of ExtractSignature."""
|
||||
return "STOP_TABLE" in (out_text or "").upper()[:80]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Re-ask meter tests (run L): dspy's adapter JSON fallback fires a second
|
||||
LM call inside the SAME module forward — the budget never charged it
|
||||
(9/80 logged, 10 on the wire, the extra burning 340s of GPU).
|
||||
|
||||
Laws under test:
|
||||
1. The meter DETECTS the fallback (marker-less first response) and charges
|
||||
the budget once via the hook; dspy's behaviour is untouched (the second
|
||||
call still runs — his call: the fallback stays, it is future
|
||||
self-improvement signal).
|
||||
2. Separate forwards (the ablation rounds) are NOT re-asks.
|
||||
3. A re-ask at budget ceiling does not kill the run (the call already
|
||||
happened — note only).
|
||||
|
||||
The repro drives dspy's REAL adapter path: a custom engine returning raw
|
||||
text (exactly what the OpenAI-compatible endpoint returns), first response
|
||||
WITHOUT the '[[ ## field ## ]]' marker -> ChatAdapter raises
|
||||
AdapterParseError -> JSONAdapter fallback re-fires the call.
|
||||
|
||||
Run: .venv/bin/python tests/reask_meter.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
|
||||
from floop.llm import PromptLogCallback
|
||||
from floop.stream import RunStreams
|
||||
from floop.state import Budget, BudgetExhausted
|
||||
|
||||
|
||||
class AnswerSig(dspy.Signature):
|
||||
goal: str = dspy.InputField()
|
||||
final_answer: str = dspy.OutputField()
|
||||
|
||||
|
||||
def _resp(text: str) -> Response:
|
||||
return Response(
|
||||
id="x", model="fake",
|
||||
message=Message(role="assistant", parts=(TextPart(text=text),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1))
|
||||
|
||||
|
||||
class FallbackEngine:
|
||||
"""First response lacks the output-field marker: the ChatAdapter parse
|
||||
fails and the JSON-adapter fallback re-fires the call (run-L shape)."""
|
||||
|
||||
def __init__(self):
|
||||
self.i = 0
|
||||
self.responses = [
|
||||
"L'anterior president del Govern d'Espanya va ser Mariano Rajoy.",
|
||||
'{"final_answer": "Mariano Rajoy (JSON retry)"}',
|
||||
]
|
||||
|
||||
def complete(self, request, **kw):
|
||||
i = min(self.i, len(self.responses) - 1)
|
||||
self.i += 1
|
||||
return _resp(self.responses[i])
|
||||
|
||||
|
||||
class CleanEngine:
|
||||
"""Every forward parses cleanly — two separate module forwards, no
|
||||
fallback (the ablation-rounds shape: same stage, fresh forwards)."""
|
||||
|
||||
def __init__(self):
|
||||
self.i = 0
|
||||
|
||||
def complete(self, request, **kw):
|
||||
self.i += 1
|
||||
return _resp(f"[[ ## final_answer ## ]]\nreading {self.i}")
|
||||
|
||||
|
||||
def test_fallback_detected_and_charged():
|
||||
streams = RunStreams("meter test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
cb = PromptLogCallback(streams)
|
||||
dspy.configure(lm=dspy.LM(model="fake", engine=FallbackEngine()),
|
||||
callbacks=[cb])
|
||||
charged = []
|
||||
cb.meter = lambda stage: charged.append(stage)
|
||||
|
||||
out = dspy.Predict(AnswerSig)(goal="who?")
|
||||
files = list((streams.run_dir / "prompts").glob("*.txt"))
|
||||
assert len(files) == 2, f"two wire calls expected: {[f.name for f in files]}"
|
||||
assert cb.reasks == 1, cb.reasks
|
||||
assert charged == ["AnswerSig"], charged
|
||||
assert "JSON retry" in out.final_answer, "dspy behaviour untouched"
|
||||
print("ok: adapter fallback detected — 2 wire calls, 1 re-ask, 1 charge")
|
||||
|
||||
|
||||
def test_separate_forwards_not_flagged():
|
||||
streams = RunStreams("rounds test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
cb = PromptLogCallback(streams)
|
||||
charged = []
|
||||
cb.meter = lambda stage: charged.append(stage)
|
||||
dspy.configure(lm=dspy.LM(model="fake2", engine=CleanEngine()),
|
||||
callbacks=[cb])
|
||||
p = dspy.Predict(AnswerSig)
|
||||
p(goal="q1")
|
||||
p(goal="q2") # second forward: fresh module start, NOT a re-ask
|
||||
assert cb.reasks == 0, f"separate forwards flagged: {cb.reasks}"
|
||||
assert charged == []
|
||||
print("ok: two separate forwards (ablation rounds) NOT flagged")
|
||||
|
||||
|
||||
def test_meter_never_kills_run():
|
||||
"""The meter hook raising (budget ceiling) must not kill the run —
|
||||
the wire call already happened."""
|
||||
from floop.machine import FloopRun
|
||||
b = Budget(max_llm_calls=1, max_depth=1, max_retries=1,
|
||||
missing_extensions=1, min_child_budget=1)
|
||||
# simulate: budget at ceiling, meter fires
|
||||
class FakeModules:
|
||||
pass
|
||||
|
||||
fm = FloopRun.__new__(FloopRun)
|
||||
fm.budget = b
|
||||
fm.notes = []
|
||||
fm.streams = None
|
||||
fm._meter_reask("ANSWER")
|
||||
assert fm.budget.llm_calls == 1, "ceiling charge must not overflow the count"
|
||||
assert any("re-ask charged" in n for n in fm.notes), fm.notes
|
||||
print("ok: meter at ceiling — charged honestly, run survives")
|
||||
|
||||
|
||||
def main():
|
||||
test_fallback_detected_and_charged()
|
||||
test_separate_forwards_not_flagged()
|
||||
test_meter_never_kills_run()
|
||||
print("\nre-ask meter tests passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user