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:
@@ -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
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user