Compare commits
2
Commits
e594339629
...
4c9c762b91
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c9c762b91 | ||
|
|
985aec2f60 |
+8
-1
@@ -171,9 +171,14 @@ _STAGE_BY_MODULE = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def configure_lm() -> dict:
|
def configure_lm(no_cache: bool = False) -> dict:
|
||||||
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
|
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
|
||||||
|
|
||||||
|
no_cache=True builds the LM with dspy's response cache DISABLED for this
|
||||||
|
process (his ruling 25/10: the cache is caching doing its job — the
|
||||||
|
default stays cache=True; the flag exists for A/B and freshness testing
|
||||||
|
so a repeated question is a real run, not a byte-identical replay).
|
||||||
|
|
||||||
Returns the active provider settings (for provenance logs).
|
Returns the active provider settings (for provenance logs).
|
||||||
"""
|
"""
|
||||||
cfg = _load_yaml()["lm"]
|
cfg = _load_yaml()["lm"]
|
||||||
@@ -190,6 +195,8 @@ def configure_lm() -> dict:
|
|||||||
"temperature": p["temperature"],
|
"temperature": p["temperature"],
|
||||||
"api_key": os.environ.get(p.get("api_key_env", ""), "empty"),
|
"api_key": os.environ.get(p.get("api_key_env", ""), "empty"),
|
||||||
}
|
}
|
||||||
|
if no_cache:
|
||||||
|
kwargs["cache"] = False
|
||||||
lm = dspy.LM(**kwargs)
|
lm = dspy.LM(**kwargs)
|
||||||
global _ACTIVE
|
global _ACTIVE
|
||||||
_ACTIVE = lm
|
_ACTIVE = lm
|
||||||
|
|||||||
@@ -33,6 +33,45 @@ from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
|||||||
|
|
||||||
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||||
|
|
||||||
|
# (K5) bug (run 085457, 24-25/10): glm-5.3-flash glues row citations and
|
||||||
|
# glosses onto the value field (AnswerFromKG says "cite rows by id" but has
|
||||||
|
# no citation output field, so the model cites in the only field it has).
|
||||||
|
# Three live shapes, stripped at the judge's output boundary — BEFORE the
|
||||||
|
# evidence payload and the ablation audit see the value:
|
||||||
|
# "... (K5)" — row-id citation suffix
|
||||||
|
# "... (…; cited from rows K16 and K30)" — parenthetical gloss citing rows
|
||||||
|
# "15 (list of 15 members: …)" — the LIST path's own gloss of a count
|
||||||
|
# Trailing-only, marker-anchored: "(PSOE)" inside a name, "(since 2018)",
|
||||||
|
# "(Presidente del Gobierno)" are legitimate and MUST survive. Fixed code
|
||||||
|
# cleans the model's proposal (LLMs propose, code decides — the audit's
|
||||||
|
# _carries then finds the support rows and the ambiguity audit can run).
|
||||||
|
_ROW_CITATION_RE = re.compile(
|
||||||
|
r"\s*\(\s*(?:row\s+|rows\s+)?K\d+(?:\s*(?:,|and|;)\s*K?\d+)*\s*\)\s*$",
|
||||||
|
re.IGNORECASE)
|
||||||
|
_ROW_CITED_GLOSS_RE = re.compile(
|
||||||
|
r"\s*\([^()]*\bcited from (?:row|rows)\b[^()]*\)\s*$",
|
||||||
|
re.IGNORECASE)
|
||||||
|
_LIST_GLOSS_RE = re.compile(
|
||||||
|
r"\s*\(\s*list of\b[^()]*\)\s*$",
|
||||||
|
re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_value(value: str) -> str:
|
||||||
|
"""Strip trailing citation/gloss parentheticals from a judge value.
|
||||||
|
|
||||||
|
The boundary law: only TRAILING shapes with a citation/list marker are
|
||||||
|
touched; mid-value text and legitimate parentheticals are the model's
|
||||||
|
own words and stay. Idempotent by construction (a cleaned value ends
|
||||||
|
clean). UNKNOWN and empty pass through untouched.
|
||||||
|
"""
|
||||||
|
v = (value or "").strip()
|
||||||
|
if not v or v.upper() == "UNKNOWN":
|
||||||
|
return v
|
||||||
|
for rx in (_ROW_CITATION_RE, _ROW_CITED_GLOSS_RE, _LIST_GLOSS_RE):
|
||||||
|
v = rx.sub("", v).rstrip()
|
||||||
|
return v.strip()
|
||||||
|
|
||||||
|
|
||||||
# header/caption terms that name the ENTITY column of a typical scalar table
|
# header/caption terms that name the ENTITY column of a typical scalar table
|
||||||
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
|
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
|
||||||
|
|
||||||
@@ -1019,7 +1058,7 @@ class KnowledgeExpert:
|
|||||||
for i, r in enumerate(rows))
|
for i, r in enumerate(rows))
|
||||||
pred = self.answer(question=question, rows=rendered)
|
pred = self.answer(question=question, rows=rendered)
|
||||||
return {
|
return {
|
||||||
"value": pred.value.strip(),
|
"value": _clean_value(pred.value),
|
||||||
"quote": pred.quote.strip(),
|
"quote": pred.quote.strip(),
|
||||||
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
|
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
|
||||||
and r.quote.strip() in pred.quote.strip()), rows[0].url),
|
and r.quote.strip() in pred.quote.strip()), rows[0].url),
|
||||||
|
|||||||
@@ -53,7 +53,8 @@ class AnswerFromKG(dspy.Signature):
|
|||||||
rows by id. If the rows do not answer it, say UNKNOWN."""
|
rows by id. If the rows do not answer it, say UNKNOWN."""
|
||||||
question: str = dspy.InputField()
|
question: str = dspy.InputField()
|
||||||
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
|
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
|
||||||
value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
|
value: str = dspy.OutputField(
|
||||||
|
desc="the answer, or UNKNOWN — the value ONLY, no row citations, no parenthetical explanations")
|
||||||
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
|
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
|
||||||
confidence: Confidence = dspy.OutputField(
|
confidence: Confidence = dspy.OutputField(
|
||||||
desc="high: rows settle it; medium: plausible but partial; low: weak support")
|
desc="high: rows settle it; medium: plausible but partial; low: weak support")
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
"""Judge value cleanup tests (the (K5) bug, run 085457 / 24-25/10 session).
|
||||||
|
|
||||||
|
glm-5.3-flash glues row citations and glosses onto the value field because
|
||||||
|
AnswerFromKG says "cite rows by id" but has no citation output field. Three
|
||||||
|
live shapes, verbatim from the runs:
|
||||||
|
|
||||||
|
"Socialist International (K5)" — row id
|
||||||
|
"2018 (Pedro Sánchez has been Prime Minister of Spain — i.e., ...)" — parenthetical gloss
|
||||||
|
"15 (list of 15 members: 17 november 2023, ...)" — LIST gloss
|
||||||
|
|
||||||
|
Laws under test:
|
||||||
|
1. Trailing citation shapes are STRIPPED from the value, at the judge's
|
||||||
|
output boundary (_clean_value), BEFORE the payload and the audit see it.
|
||||||
|
2. Legitimate parentheticals SURVIVE: "(PSOE)" inside a name,
|
||||||
|
"(Presidente del Gobierno)" inside an office title.
|
||||||
|
3. A cleaned value lets the ablation audit RUN where the raw value killed
|
||||||
|
it silently ("the judge invented it: nothing to ablate").
|
||||||
|
4. The clean is idempotent and does not touch UNKNOWN/empty.
|
||||||
|
|
||||||
|
No network. No LLM: the cleaner is fixed code; the tests call it directly
|
||||||
|
plus one scripted-judge pass through _answer_from_rows.
|
||||||
|
Run: .venv/bin/python knowledge/tests/value_clean.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
|
from knowledge.expert import KnowledgeExpert, _clean_value
|
||||||
|
|
||||||
|
|
||||||
|
def test_row_id_suffix_stripped():
|
||||||
|
assert _clean_value("Socialist International (K5)") == "Socialist International"
|
||||||
|
assert _clean_value("Rajoy (K12)") == "Rajoy"
|
||||||
|
print("ok: row-id citation suffix stripped")
|
||||||
|
|
||||||
|
|
||||||
|
def test_cited_from_rows_gloss_stripped():
|
||||||
|
v = ("2018 (Pedro Sánchez has been Prime Minister of Spain — i.e., "
|
||||||
|
"President of the Government — since 2018; cited from rows K16 and K30)")
|
||||||
|
assert _clean_value(v) == "2018", _clean_value(v)
|
||||||
|
print("ok: 'cited from rows' parenthetical stripped, year kept")
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_gloss_stripped():
|
||||||
|
v = "15 (list of 15 members: 17 november 2023, 28 november 2023, 24 september 2024)"
|
||||||
|
assert _clean_value(v) == "15", _clean_value(v)
|
||||||
|
print("ok: LIST-members gloss stripped, count kept")
|
||||||
|
|
||||||
|
|
||||||
|
def test_legitimate_parentheticals_survive():
|
||||||
|
assert _clean_value("Spanish Socialist Workers' Party (PSOE)") == \
|
||||||
|
"Spanish Socialist Workers' Party (PSOE)"
|
||||||
|
assert _clean_value("Prime Minister of Spain (Presidente del Gobierno)") == \
|
||||||
|
"Prime Minister of Spain (Presidente del Gobierno)"
|
||||||
|
# a parenthetical that merely mentions a number is NOT a citation
|
||||||
|
assert _clean_value("Prime Minister of Spain (since 2018)") == \
|
||||||
|
"Prime Minister of Spain (since 2018)"
|
||||||
|
print("ok: legitimate parentheticals untouched")
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_and_empty_untouched():
|
||||||
|
assert _clean_value("UNKNOWN") == "UNKNOWN"
|
||||||
|
assert _clean_value("") == ""
|
||||||
|
assert _clean_value(" Spain ") == "Spain"
|
||||||
|
print("ok: UNKNOWN/empty/whitespace handled")
|
||||||
|
|
||||||
|
|
||||||
|
def test_idempotent_and_mid_value_citations():
|
||||||
|
v = _clean_value("Socialist International (K5)")
|
||||||
|
assert _clean_value(v) == v
|
||||||
|
# a citation in the MIDDLE is not the live bug shape — leave it (no
|
||||||
|
# aggressive surgery on the judge's sentence), the boundary law strips
|
||||||
|
# only the TRAILING gloss
|
||||||
|
assert _clean_value("Per (K2) the answer is Spain") == \
|
||||||
|
"Per (K2) the answer is Spain"
|
||||||
|
print("ok: idempotent; mid-value text untouched (boundary law: trailing only)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_answer_from_rows_boundary():
|
||||||
|
"""The hook: _answer_from_rows cleans pred.value before the payload is
|
||||||
|
built. Scripted dspy-style Predict object; no network."""
|
||||||
|
e = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||||
|
e.cfg = __import__("knowledge.expert", fromlist=["KnowledgeConfig"]).KnowledgeConfig()
|
||||||
|
e._log = lambda *a, **k: None
|
||||||
|
|
||||||
|
class Pred:
|
||||||
|
value = "Socialist International (K5)"
|
||||||
|
quote = "ninth president of Socialist International since 2022"
|
||||||
|
class confidence:
|
||||||
|
value = "high"
|
||||||
|
|
||||||
|
class Row:
|
||||||
|
src = rel = dst = quote = url = "u"
|
||||||
|
conflict = False
|
||||||
|
|
||||||
|
e.answer = lambda question, rows: Pred()
|
||||||
|
out = e._answer_from_rows("which office?", [Row()])
|
||||||
|
assert out["value"] == "Socialist International", out["value"]
|
||||||
|
print("ok: _answer_from_rows boundary cleans the value")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_row_id_suffix_stripped()
|
||||||
|
test_cited_from_rows_gloss_stripped()
|
||||||
|
test_list_gloss_stripped()
|
||||||
|
test_legitimate_parentheticals_survive()
|
||||||
|
test_unknown_and_empty_untouched()
|
||||||
|
test_idempotent_and_mid_value_citations()
|
||||||
|
test_answer_from_rows_boundary()
|
||||||
|
print("\nvalue_clean: 7/7 ok")
|
||||||
+36
-3
@@ -4,6 +4,7 @@
|
|||||||
uv run run_app.py "Per què el cel és blau?" # log only
|
uv run run_app.py "Per què el cel és blau?" # log only
|
||||||
uv run run_app.py --verbose "Per què el cel és blau?" # + thinking on screen
|
uv run run_app.py --verbose "Per què el cel és blau?" # + thinking on screen
|
||||||
uv run run_app.py --baseline "Per què el cel és blau?" # raw LLM, one call (A/B comparison)
|
uv run run_app.py --baseline "Per què el cel és blau?" # raw LLM, one call (A/B comparison)
|
||||||
|
uv run run_app.py --no-cache "..." # dspy response cache OFF for this run
|
||||||
FLOOP_LM=ollama-cloud uv run run_app.py "..."
|
FLOOP_LM=ollama-cloud uv run run_app.py "..."
|
||||||
|
|
||||||
Always: runs/<ts>-<slug>/run.log written with flush -> `tail -f` it from another
|
Always: runs/<ts>-<slug>/run.log written with flush -> `tail -f` it from another
|
||||||
@@ -42,27 +43,59 @@ def run_baseline(question: str, streams: RunStreams) -> str:
|
|||||||
return answer
|
return answer
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_local_imports(code_dir: Path) -> None:
|
||||||
|
"""Abort loudly if floop/knowledge resolve OUTSIDE this repo's tree.
|
||||||
|
|
||||||
|
The shared venv carries an editable-install .pth pointing at another
|
||||||
|
checkout, and a poisoned PYTHONPATH (shim importing knowledge.* first)
|
||||||
|
pins SUBMODULES to another tree even when the package __path__ lists
|
||||||
|
this one — a namespace package recomputes __path__ dynamically, so
|
||||||
|
checking the package proves nothing (run 085457, 25/10: main's pipeline
|
||||||
|
ran inside the branch worktree with zero signal). Check the FILES the
|
||||||
|
run actually executes. A wrong import tree invalidates the run; refuse
|
||||||
|
it, don't log it.
|
||||||
|
"""
|
||||||
|
root = str(code_dir.resolve())
|
||||||
|
for name, relpath in (("floop", "machine.py"), ("floop", "llm.py"),
|
||||||
|
("knowledge", "expert.py"), ("knowledge", "store.py")):
|
||||||
|
try:
|
||||||
|
mod = __import__(f"{name}.{relpath[:-3]}", fromlist=[""])
|
||||||
|
except ImportError as e: # pragma: no cover — broken install, abort anyway
|
||||||
|
raise SystemExit(f"ABORT: cannot import {name}.{relpath[:-3]}: {e}")
|
||||||
|
loaded = str(Path(mod.__file__).resolve())
|
||||||
|
if not loaded.startswith(root):
|
||||||
|
raise SystemExit(
|
||||||
|
f"ABORT: module '{name}.{relpath[:-3]}' resolved outside this repo\n"
|
||||||
|
f" repo: {root}\n"
|
||||||
|
f" loaded: {loaded}\n"
|
||||||
|
"The venv's editable .pth or PYTHONPATH shadows this tree — "
|
||||||
|
"the run would test the WRONG code. Fix sys.path and retry.")
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
args = sys.argv[1:]
|
args = sys.argv[1:]
|
||||||
verbose = "--verbose" in args
|
verbose = "--verbose" in args
|
||||||
baseline = "--baseline" in args
|
baseline = "--baseline" in args
|
||||||
args = [a for a in args if a not in ("--verbose", "--baseline")]
|
no_cache = "--no-cache" in args
|
||||||
|
args = [a for a in args if a not in ("--verbose", "--baseline", "--no-cache")]
|
||||||
if not args:
|
if not args:
|
||||||
print(__doc__)
|
print(__doc__)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
question = " ".join(args)
|
question = " ".join(args)
|
||||||
|
|
||||||
code_dir = Path(__file__).resolve().parent
|
code_dir = Path(__file__).resolve().parent
|
||||||
|
_assert_local_imports(code_dir) # the editable-pth trap: wrong tree = invalid run
|
||||||
cfg = yaml.safe_load((code_dir / "config.yaml").read_text())
|
cfg = yaml.safe_load((code_dir / "config.yaml").read_text())
|
||||||
b = cfg["budget"]
|
b = cfg["budget"]
|
||||||
budget = Budget(max_llm_calls=b["max_llm_calls"], max_depth=b["max_depth"],
|
budget = Budget(max_llm_calls=b["max_llm_calls"], max_depth=b["max_depth"],
|
||||||
max_retries=b["max_retries"], missing_extensions=b["missing_extensions"],
|
max_retries=b["max_retries"], missing_extensions=b["missing_extensions"],
|
||||||
min_child_budget=b["min_child_budget"])
|
min_child_budget=b["min_child_budget"])
|
||||||
|
|
||||||
lm_info = configure_lm()
|
lm_info = configure_lm(no_cache=no_cache)
|
||||||
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
|
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
|
||||||
install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt
|
install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt
|
||||||
streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} baseline={baseline}")
|
streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} "
|
||||||
|
f"baseline={baseline} no_cache={no_cache}")
|
||||||
|
|
||||||
if baseline:
|
if baseline:
|
||||||
answer = run_baseline(question, streams)
|
answer = run_baseline(question, streams)
|
||||||
|
|||||||
Reference in New Issue
Block a user