knowledge: table fragments for extract + exact prompt log (run G fixes)
Run G hung at call 8/80 for minutes with no way to see what was sent.
Reproducing it found TWO root causes, both fixed here:
1. THE 22K TABLE CHUNK WAS A PARSER BUG, not just a size problem. The
world-rivers table marks each data row's leading cell with
'!scope="row"|' (a row-label th); parse_tables flagged any row that
touched a '!' as a header row, so all 227 data rows collapsed into ONE
header of 1,825 cells and zero rows. tables_as_text then flattened
that monster into a single 22,021-char prose chunk. Fix: a row is a
header row only if ALL its cells are '!' cells; mixed rows are data
rows. Live: the world table now parses as 8 cols x 227 rows.
2. NO PROMPT OBSERVABILITY. The log's CALL/OUTPUT lines never carried
what the LM actually received. floop/llm.py now installs a dspy global
callback (PromptLogCallback): every LM call's exact rendered prompt
lands in runs/<ts>/prompts/NN-stage.txt (NN mirrors the budget counter
-- 08-EXTRACT.txt IS call 8/80), plus size/duration lines in run.log.
Stage comes from a module stack (dspy fires on_module_start with a
DIFFERENT call_id than the inner LM call -- verified with DummyLM
probes), not a call_id map.
Plus the design Emili steered (tables reach the extractor as typed
fragments, never prose dumps):
- tables_as_chunks: per-table fragments of <=40 rows, EVERY fragment
repeats header + caption, part i/N markers; the extractor always knows
which table ('troç 2/10') it is reading.
- STOP_TABLE: the extractor may early-skip a table whose subject is
wrong for the question after one fragment; fixed code skips the rest
of THAT table. ExtractSignature teaches the protocol.
- fetch_rich no longer appends the '== Tables ==' enrichment to prose
(the giant chunk's birthplace; also let verify_count cite the table as
'prose'). Tables reach the extract path only as fragments; LIST and
harvest keep reading page.tables directly.
- fragment candidates pass the same containment check against prose +
full table text; LIST answer's table never re-enters extract.
Tests: knowledge/tests/tablefrags.py (fragment generation/render,
STOP_TABLE skipping, fragment extraction with containment, prompt log
files + log lines). Live smoke: world article 10 chunks none >5k; world
table = 6 fragments (max 5,787c); Italy discharge fragment intact
(Po/1540). Full suite 47/47.
This commit is contained in:
@@ -2,10 +2,17 @@
|
||||
|
||||
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).
|
||||
|
||||
This module also installs the PROMPT LOG: a dspy global callback that writes
|
||||
every LLM call's exact rendered prompt to runs/<ts>/prompts/NN-stage.txt and a
|
||||
size line to run.log — the "what did it actually send?" channel that the log's
|
||||
CALL/OUTPUT lines never carried (GAP: run G, call 8/80 — a 22k-char table
|
||||
chunk sat for minutes with no way to see the prompt without rebuilding it).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import dspy
|
||||
@@ -17,6 +24,105 @@ def _load_yaml() -> dict:
|
||||
return yaml.safe_load(cfg.read_text())
|
||||
|
||||
|
||||
def _slug_stage(text: str, maxlen: int = 24) -> str:
|
||||
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
||||
return s[:maxlen].rstrip("-") or "call"
|
||||
|
||||
|
||||
class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
"""Writes the exact rendered prompt of every LM call to the run dir.
|
||||
|
||||
dspy fires on_module_start/on_module_end around each Predict's forward
|
||||
(call_id DIFFERENT from the inner LM call's), so a call_id-keyed map
|
||||
would lose the stage. A stack does not: the LM call runs synchronously
|
||||
inside the innermost module's forward, so the top of the stack at
|
||||
on_lm_start IS the stage that made the call.
|
||||
|
||||
Output: runs/<ts>/prompts/NN-stage.txt — NN mirrors the budget counter
|
||||
(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.
|
||||
"""
|
||||
|
||||
def __init__(self, streams) -> None:
|
||||
self.streams = streams # RunStreams or None (baseline mode)
|
||||
self._stack: list[str] = [] # nested module stages (innermost last)
|
||||
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
||||
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
||||
|
||||
# -- dspy plumbing -------------------------------------------------------
|
||||
|
||||
def on_module_start(self, call_id, instance, inputs):
|
||||
sig = getattr(getattr(instance, "signature", None), "__name__", None)
|
||||
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
|
||||
self._stack.append(label)
|
||||
|
||||
def on_module_end(self, call_id, outputs, exception):
|
||||
if self._stack:
|
||||
self._stack.pop()
|
||||
|
||||
def on_lm_start(self, call_id, instance, inputs):
|
||||
import time
|
||||
self._starts[call_id] = time.monotonic()
|
||||
label = self._stack[-1] if self._stack else "lm"
|
||||
self._stage_of[call_id] = label
|
||||
streams = self.streams
|
||||
msgs = inputs.get("messages", []) or []
|
||||
text = "\n\n".join(
|
||||
f"[{m.get('role', '?')}] {m.get('content', '')}" for m in msgs
|
||||
if isinstance(m, dict)
|
||||
)
|
||||
chars = len(text)
|
||||
if streams is not None:
|
||||
n = streams.bump_prompt_seq()
|
||||
fn = f"{n:02d}-{label}.txt"
|
||||
pdir = streams.run_dir / "prompts"
|
||||
pdir.mkdir(exist_ok=True)
|
||||
(pdir / fn).write_text(
|
||||
f"# stage={label} call_seq={n} chars={chars} "
|
||||
f"tokens~{chars // 4}\n\n" + text,
|
||||
encoding="utf-8",
|
||||
)
|
||||
streams.log(
|
||||
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
|
||||
f"-> prompts/{fn}"
|
||||
)
|
||||
else:
|
||||
print(f"[prompt] stage={label} chars={chars} tokens~{chars // 4}")
|
||||
|
||||
def on_lm_end(self, call_id, outputs, exception):
|
||||
import time
|
||||
streams = self.streams
|
||||
label = self._stage_of.pop(call_id, "lm")
|
||||
start = self._starts.pop(call_id, None)
|
||||
dur = f"{time.monotonic() - start:.1f}s" if start is not None else "?"
|
||||
if streams is not None:
|
||||
streams.log(f"prompt {label} done in {dur}")
|
||||
|
||||
|
||||
# dspy module class -> log stage label (knowledge/ + floop/ share the callback)
|
||||
_STAGE_BY_MODULE = {
|
||||
"Predict": "predict",
|
||||
"InitDecompose": "INIT",
|
||||
"Route": "ROUTE",
|
||||
"Expert": "EXPERT",
|
||||
"Missing": "MISSING",
|
||||
"Answer": "ANSWER",
|
||||
"KnowledgeExpert": "knowledge",
|
||||
"InitSignature": "INIT",
|
||||
"RouteSignature": "ROUTE",
|
||||
"ExpertSignature": "EXPERT",
|
||||
"MissingSignature": "MISSING",
|
||||
"AnswerSignature": "ANSWER",
|
||||
"ExtractSignature": "EXTRACT",
|
||||
"AnswerFromKG": "answer_kg",
|
||||
"TranslateSignature": "TRANSLATE",
|
||||
"SelectTableSignature": "SELECT_TABLE",
|
||||
"VerifyCountSignature": "VERIFY_COUNT",
|
||||
"SkimPromoteSignature": "PROMOTE",
|
||||
}
|
||||
|
||||
|
||||
def configure_lm() -> dict:
|
||||
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
|
||||
|
||||
@@ -43,7 +149,19 @@ def configure_lm() -> dict:
|
||||
return {"provider": provider, "model": p["model"], "base_url": p["base_url"]}
|
||||
|
||||
|
||||
def install_prompt_log(streams) -> None:
|
||||
"""Attach the prompt log callback globally (call once per run, after
|
||||
configure_lm). Idempotent: replacing streams re-installs one callback."""
|
||||
global _PROMPT_LOG
|
||||
if _PROMPT_LOG is not None:
|
||||
_PROMPT_LOG.streams = streams
|
||||
return
|
||||
_PROMPT_LOG = PromptLogCallback(streams)
|
||||
dspy.configure(callbacks=[_PROMPT_LOG])
|
||||
|
||||
|
||||
_ACTIVE: "dspy.LM | None" = None
|
||||
_PROMPT_LOG: "PromptLogCallback | None" = None
|
||||
|
||||
|
||||
def active_lm() -> "dspy.LM":
|
||||
|
||||
Reference in New Issue
Block a user