Files
floop/code/run_app.py
T
onibot 9eab127727 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.
2026-10-20 20:22:29 +02:00

123 lines
5.2 KiB
Python

#!/usr/bin/env python3
"""Run the floop draft on a question.
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 --baseline "Per què el cel és blau?" # raw LLM, one call (A/B comparison)
FLOOP_LM=ollama-cloud uv run run_app.py "..."
Always: runs/<ts>-<slug>/run.log written with flush -> `tail -f` it from another
terminal. With --verbose, the "thinking" stream (the future floop-as-LLM thinking
output — a subset of the log) also prints to the screen, flushed.
"""
from __future__ import annotations
import sys
import time
from pathlib import Path
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parent))
from floop.llm import configure_lm, install_prompt_log # noqa: E402
from floop.machine import FloopRun, RunReport # noqa: E402
from floop.state import Budget # noqa: E402
from floop.stream import RunStreams # noqa: E402
def run_baseline(question: str, streams: RunStreams) -> str:
"""The A/B control: the raw LM answers in ONE call — no decomposition, no
experts, no evidence. Same LM, same budget unit (1 call) as the loop's init."""
from floop.llm import active_lm
streams.call("BASELINE", f"single raw LM call: {question[:80]}",
think=f"raw LM: {question[:90]}")
t0 = time.time()
raw = active_lm()(messages=[{"role": "user", "content": question}])
first = raw[0] if isinstance(raw, list) else raw.outputs[0]
answer = first["text"] if isinstance(first, dict) and "text" in first else first.get("content") or str(first)
dt = round(time.time() - t0, 1)
streams.output("BASELINE", answer)
streams.log(f"baseline time={dt}s")
return answer
def main() -> None:
args = sys.argv[1:]
verbose = "--verbose" in args
baseline = "--baseline" in args
args = [a for a in args if a not in ("--verbose", "--baseline")]
if not args:
print(__doc__)
sys.exit(1)
question = " ".join(args)
code_dir = Path(__file__).resolve().parent
cfg = yaml.safe_load((code_dir / "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()
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
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}")
if baseline:
answer = run_baseline(question, streams)
streams.close()
print(f"goal: {question}")
print(f"lm: {lm_info['provider']} / {lm_info['model']} | mode=baseline (raw LLM, 1 call)")
print("\nraw LM answer:")
print(answer)
print(f"\nrun log: {streams.run_dir / 'run.log'}")
return
# knowledge expert: real pipeline when enabled, baseline LLM otherwise
knowledge_engine = None
if cfg.get("knowledge", {}).get("enabled", False):
try:
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
from knowledge.store import KnowledgeStore
from floop.engine import KnowledgeEngine, LLMExpertEngine
kcfg = cfg["knowledge"]
kconfig = KnowledgeConfig(
kb_path=str(code_dir / kcfg.get("kb_path", "knowledge_store/kg.sqlite")),
max_articles=kcfg.get("max_articles", 2),
max_search_results=kcfg.get("max_search_results", 4),
max_chunks_extracted=kcfg.get("max_chunks_extracted", 6),
chunk_chars_target=kcfg.get("chunk_chars_target", 32000),
chunk_chars_cap=kcfg.get("chunk_chars_cap", 48000),
)
ke = KnowledgeExpert(config=kconfig, streams=streams)
knowledge_engine = KnowledgeEngine(ke)
streams.log(f"knowledge pipeline enabled (kb={kconfig.kb_path})")
except Exception as e: # noqa: BLE001 — degrade honestly, never die at startup
streams.log(f"knowledge pipeline disabled: {e}")
knowledge_engine = None
try:
report: RunReport = FloopRun(question, budget, streams=streams,
knowledge_engine=knowledge_engine).run()
finally:
streams.close()
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(report.final_answer or "(no answer produced)")
print(f"\nrun log: {streams.run_dir / 'run.log'} (tail -f it next time)")
if __name__ == "__main__":
main()