feat(stream): thinking + run log for CLI (GAP-13 CLI part)

RunStreams: run.log always (flushed, tail -f-able) with full technical detail; thinking stream to screen under --verbose (flushed, [T] lines, > depth prefixes). Machine hooks on INIT/MISSING/ROUTE/EXPERT/ANSWER + budget ticks; child runs share the parent's stream; engine emits its raw output. Verified live: 8-call train run inline, fresh-question run 69.6s (proxy caches identical temp-0 prompts; noted).
This commit is contained in:
2026-10-13 17:50:57 +02:00
parent 550128c9bb
commit 6733cb660e
7 changed files with 163 additions and 19 deletions
+11 -1
View File
@@ -10,11 +10,21 @@ is the real v0.1 shape; only the formal layer is missing.
```bash
cd floop/code
.venv/bin/python run_app.py "What information do I need to plan a trip to Tokyo?" # any question
.venv/bin/python run_app.py --verbose "..." # + "thinking" on screen, flushed
FLOOP_LM=ollama-cloud .venv/bin/python run_app.py "..." # cloud LM instead of local
```
- **Always**: `runs/<ts>-<slug>/run.log` (gitignored), written with explicit flush —
`tail -f runs/<latest>/run.log` from another terminal shows progress live.
- **`--verbose`**: the **thinking stream** also prints to the screen, flushed. Thinking is
floop's future user-facing "thinking" output (what floop-as-LLM will stream); it is a
SUBSET of the log — the log keeps all technical detail (budget, provenance, raw payloads),
thinking stays readable. They will diverge over time (Emili, 2026-10-13).
- Screen thinking lines carry the `[T]` marker; recursion depth shows as `>` prefixes.
- The same events will drive the OpenAI-compatible endpoint's streaming mode (SCOPE.md §4).
`config.yaml` holds the budget knobs and the two LM providers (no keys in code:
`ollama-cloud` reads `OLLAMA_API_KEY` from the environment).
`ollama-cloud` reads `OLLAMA_API_KEY` from the environment). Logs live in `runs/`.
## What is real vs stub (the honest map)
+3 -1
View File
@@ -41,11 +41,13 @@ class LLMExpertEngine:
self.kind = expert_kind
self.name = f"stub:{expert_kind}"
def run(self, qid, question, parent_question, table, answer_type):
def run(self, qid, question, parent_question, table, answer_type, streams=None):
self.charge() # the engine IS an LLM call in this draft — it costs budget
ev = table.dump()
draft = self.modules.expert_draft(
question, self.kind, ev, parent_question=parent_question)
if streams is not None:
streams.output("EXPERT", f"value={draft['value']} quote={draft['source_quote'][:80]}")
verified = False # v0.2: formal check layer (sorts/units/consistency) BEFORE engine
payload: dict = {"value": draft["value"]}
if draft["source_quote"]:
+27 -3
View File
@@ -17,6 +17,7 @@ from .engine import CATALOG, LLMExpertEngine, UserRequestEngine
from .dspy_modules import FloopModules
from .state import (Budget, BudgetExhausted, EvidenceRow, EvidenceTable,
OpenQuestion, QuestionStack, instantiate)
from .stream import RunStreams
EXPERT_ENGINES = ("knowledge", "logic", "analytic", "numeric")
@@ -49,12 +50,15 @@ class FloopRun:
"""One FLOOP execution over one question (top-level or recursive child)."""
def __init__(self, question: str, budget: Budget, depth: int = 0,
modules: FloopModules | None = None, parent_goal: str = "") -> None:
modules: FloopModules | None = None, parent_goal: str = "",
streams: RunStreams | None = None) -> None:
self.query = question
self.budget = budget
self.depth = depth
self.parent_goal = parent_goal
self.modules = modules or FloopModules()
self.streams = streams or RunStreams(question)
self.tprefix = ">" * (depth + 1) + " " if depth else "" # depth marker on screen
self.table = EvidenceTable()
self.stack = QuestionStack(question)
self.user_engine = UserRequestEngine(self.modules)
@@ -65,6 +69,8 @@ class FloopRun:
def _charge(self) -> None:
self.budget.charge_llm()
self.streams.log(f"budget llm_calls={self.budget.llm_calls}"
f"/{self.budget.max_llm_calls} depth={self.depth}")
# ---- the loop (ALGORITHM.md §2) ----------------------------------------
@@ -92,13 +98,19 @@ class FloopRun:
def _init_decompose(self) -> None:
self._charge()
self.streams.call("INIT", f"decompose: {self.query[:80]}",
think=self.tprefix + f"decomposing: {self.query[:100]}")
subs = self.modules.init_decompose(self.query)
self.streams.output("INIT", chr(10).join(s["text"] for s in subs) or "(no subquestions)")
self._add_questions(subs, reason="init")
def _missing_round(self) -> None:
self._charge()
self.budget.missing_used += 1
self.streams.call("MISSING", f"goal stuck: {self.query[:80]}",
think=self.tprefix + "goal not derivable; asking what is missing")
subs = self.modules.missing_decompose(self.query, self.table.dump())
self.streams.output("MISSING", chr(10).join(s["text"] for s in subs) or "(no new questions)")
self._add_questions(subs, reason="missing")
def _add_questions(self, subs: list[dict], reason: str) -> None:
@@ -119,7 +131,10 @@ class FloopRun:
def _route_and_execute(self, q: OpenQuestion) -> None:
self._charge()
self.streams.call("ROUTE", f"{q.qid}: {q.text[:80]}",
think=self.tprefix + f"routing {q.qid}: {q.text[:90]}")
attendant, why = self.modules.route_question(q.text, CATALOG, self._context(q))
self.streams.output("ROUTE", f"{attendant} ({why})")
if attendant == "floop":
self._execute_child(q)
@@ -132,8 +147,10 @@ class FloopRun:
q.reason = "user expert not wired (draft)"
elif attendant in EXPERT_ENGINES:
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
self.streams.call("EXPERT", f"{attendant} on {q.qid}: {q.text[:80]}",
think=self.tprefix + f"asking {attendant}: {q.text[:90]}")
row = engine.run(q.qid, instantiate(q.text, self.table),
self.query, self.table, q.answer_type)
self.query, self.table, q.answer_type, streams=self.streams)
self.engine_calls += 1
self._append_checked(row, q)
else:
@@ -154,9 +171,13 @@ class FloopRun:
child_budget = self.budget.slice_for_child()
child = FloopRun(question=instantiate(q.text, self.table),
budget=child_budget, depth=self.depth + 1,
modules=self.modules, parent_goal=self.query)
modules=self.modules, parent_goal=self.query,
streams=self.streams)
report = child.run()
self.budget.llm_calls += child_budget.llm_calls
self.streams.state(
f"child run done: llm_calls={report.llm_calls} rows={len(report.evidence_rows)}",
think=True)
row = EvidenceRow(
qid=q.qid, answer_type=q.answer_type,
payload={"value": report.final_answer},
@@ -194,8 +215,11 @@ class FloopRun:
answer = ""
try:
self._charge()
self.streams.call("ANSWER", f"synthesize answer for: {self.query[:80]}",
think=self.tprefix + "writing the answer from the evidence table")
answer = self.modules.synthesize(
self.query, self.table.dump(), unverified=not verified)
self.streams.final(answer)
except BudgetExhausted:
self.notes.append("budget died before the answer step")
return RunReport(
+90
View File
@@ -0,0 +1,90 @@
"""Progress streams for a floop run: the log (complete, technical) and thinking
(the screen channel for CLI; the future "thinking" output of floop-as-LLM).
Design (SCOPE.md §4 / GAP-13): every event lands in runs/<ts>-<slug>/run.log with
explicit flush (tail -f-able). The screen shows ONLY the thinking subset, and only
with --verbose. log ⊇ thinking; they will diverge over time.
"""
from __future__ import annotations
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
def _slug(text: str, maxlen: int = 40) -> str:
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
return s[:maxlen].rstrip("-") or "run"
def now_hms() -> str:
return datetime.now(timezone.utc).astimezone().strftime("%H:%M:%S")
class RunStreams:
"""Two sinks, one class: log always (flushed); thinking to screen iff verbose."""
def __init__(self, question: str, verbose: bool = False,
runs_dir: str | None = None) -> None:
base = Path(runs_dir) if runs_dir else Path(__file__).resolve().parent.parent / "runs"
base.mkdir(parents=True, exist_ok=True)
ts = datetime.now(timezone.utc).astimezone().strftime("%Y%m%d-%H%M%S")
self.run_dir = base / f"{ts}-{_slug(question)}"
self.run_dir.mkdir(parents=True, exist_ok=True)
self.log_path = self.run_dir / "run.log"
self.verbose = verbose
self._fh = open(self.log_path, "a", encoding="utf-8")
def close(self) -> None:
if self._fh and not self._fh.closed:
self._fh.close()
# ---- channels ----------------------------------------------------------
def log(self, text: str) -> None:
"""Technical detail: log only, never on screen."""
self._emit_log(f"LOG {text}")
def think(self, text: str | None) -> None:
"""Thinking: screen iff verbose (flushed); always to log as [T] lines."""
if text is None:
return
for line in text.rstrip(chr(10)).split(chr(10)):
self._emit_log(f"[T] {line}", screen=f"[T] {line}")
def think_line(self, text: str) -> None:
self.think(text)
# ---- structural events -------------------------------------------------
def call(self, stage: str, description: str, think: str | None = None) -> None:
"""An LLM call or engine step is starting."""
self._emit_log(f"CALL {stage}: {description}")
if think is not None:
self.think_line(f"[{stage}] {think}")
def output(self, stage: str, text: str, think: bool = True) -> None:
"""Raw LLM (or engine) output as it lands."""
self._emit_log(f"OUTPUT {stage}: {text}")
if think:
self.think(text)
def state(self, text: str, think: bool = False) -> None:
"""State change: evidence appended, question status, budget."""
self._emit_log(f"STATE {text}")
if think:
self.think_line(text)
def final(self, text: str) -> None:
self._emit_log(f"FINAL {text}")
self.think_line(f"[FINAL] {text}")
# ---- internals ---------------------------------------------------------
def _emit_log(self, log_payload: str, screen: str | None = None) -> None:
line = f"[{now_hms()}] {log_payload}"
self._fh.write(line + "\n")
self._fh.flush()
if screen is not None and self.verbose:
print(screen, flush=True)
+23 -9
View File
@@ -1,10 +1,13 @@
#!/usr/bin/env python3
"""Run the floop draft on a question.
.venv/bin/python run_app.py "Per què el cel és blau?"
.venv/bin/python run_app.py "Per què el cel és blau?" # log only
.venv/bin/python run_app.py --verbose "Per què el cel és blau?" # + thinking on screen
FLOOP_LM=ollama-cloud .venv/bin/python run_app.py "..."
Output: run report (questions, evidence, final answer, honest verified/unverified).
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
@@ -15,25 +18,35 @@ import yaml
sys.path.insert(0, str(Path(__file__).resolve().parent))
from floop.llm import configure_lm # noqa: E402
from floop.llm import configure_lm # noqa: E402
from floop.machine import FloopRun, RunReport # noqa: E402
from floop.state import Budget # noqa: E402
from floop.state import Budget # noqa: E402
from floop.stream import RunStreams # noqa: E402
def main() -> None:
if len(sys.argv) < 2:
args = sys.argv[1:]
verbose = "--verbose" in args
args = [a for a in args if a != "--verbose"]
if not args:
print(__doc__)
sys.exit(1)
question = " ".join(sys.argv[1:])
question = " ".join(args)
cfg = yaml.safe_load((Path(__file__).resolve().parent / "config.yaml").read_text())
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()
report: RunReport = FloopRun(question, budget).run()
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose}")
try:
report: RunReport = FloopRun(question, budget, streams=streams).run()
finally:
streams.close()
print(f"goal: {report.goal}")
print(f"lm: {lm_info['provider']} / {lm_info['model']} | llm_calls={report.llm_calls} "
@@ -47,7 +60,8 @@ def main() -> None:
for line in report.evidence_rows:
print(f" {line}")
print(f"\nfinal answer [{'VERIFIED' if report.verified else 'UNVERIFIED'}]:")
print(answer_block := (report.final_answer or "(no answer produced)"))
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__":