"""Progress and time estimates for the stages of answering one question. Estimates come from how long each kind of stage took on earlier questions, so they are rough on the first question and improve as the demo is used. Generation length is unknown in advance, so progress inside a generating stage is measured against the average length seen so far, and is capped below 100% until it ends. """ import time from dataclasses import dataclass # Starting guesses, replaced by observed values after the first run of each stage kind. DEFAULT_SECONDS = {"search": 1.0, "read": 10.0, "answer_notes": 6.0, "answer_text": 8.0} DEFAULT_TOKENS = {"read": 150.0, "answer_notes": 100.0, "answer_text": 100.0} SMOOTHING = 0.5 # weight of the newest observation in the running averages IN_STAGE_CAP = 0.95 _seconds: dict[str, float] = {} _tokens: dict[str, float] = {} @dataclass class Stage: """One step of the pipeline. Stages with the same `key` share a running time estimate.""" key: str label: str def _blend(store: dict[str, float], key: str, value: float) -> None: store[key] = value if key not in store else SMOOTHING * value + (1 - SMOOTHING) * store[key] def expected_seconds(key: str) -> float: """Expected duration of a stage kind.""" return _seconds.get(key, DEFAULT_SECONDS[key]) def expected_tokens(key: str) -> float: """Expected generated length of a stage kind.""" return _tokens.get(key, DEFAULT_TOKENS.get(key, 1.0)) class Tracker: """Follows one question through its stages and renders a progress bar.""" def __init__(self, stages: list[Stage]) -> None: """Start timing; `stages` may be replaced once the pages to read are known.""" self.stages = stages # Stage weights are fixed when planned, so learning from a finished stage never moves the bar backwards. self.weights = [expected_seconds(s.key) for s in stages] self.finished: list[tuple[str, float]] = [] self.tokens = 0 self._peak = 0.0 self._start = self._stage_start = time.perf_counter() def set_stages(self, stages: list[Stage]) -> None: """Replace the plan; stages already finished keep their weights.""" done = len(self.finished) self.stages = stages self.weights = self.weights[:done] + [expected_seconds(s.key) for s in stages[done:]] def update(self, tokens: int) -> None: """Record how many tokens the current stage has generated so far.""" self.tokens = tokens def advance(self) -> None: """Mark the current stage finished and learn from how long it took.""" index = len(self.finished) now = time.perf_counter() stage = self.stages[index] seconds = now - self._stage_start self.finished.append((stage.label, seconds)) _blend(_seconds, stage.key, seconds) if self.tokens: _blend(_tokens, stage.key, float(self.tokens)) self._stage_start, self.tokens = now, 0 def _current_fraction(self, stage: Stage) -> float: if stage.key == "search" or not self.tokens: return 0.0 return min(self.tokens / expected_tokens(stage.key), IN_STAGE_CAP) def percent_and_remaining(self) -> tuple[float, float]: """Estimated percent complete (never decreasing) and seconds left.""" index = len(self.finished) if index >= len(self.stages): return 100.0, 0.0 in_stage = self._current_fraction(self.stages[index]) total = sum(self.weights) elapsed = sum(self.weights[:index]) + self.weights[index] * in_stage remaining = sum(self.weights[index + 1 :]) + self.weights[index] * (1 - in_stage) self._peak = max(self._peak, 100 * elapsed / total) return self._peak, remaining def render(self, finished: bool = False) -> str: """HTML for the progress bar, or the timing breakdown once finished.""" elapsed = time.perf_counter() - self._start if finished: steps = " · ".join(f"{label} {seconds:.1f}s" for label, seconds in self.finished) return _bar(100, f"Done in {elapsed:.1f}s", steps) percent, remaining = self.percent_and_remaining() index = min(len(self.finished), len(self.stages) - 1) calibrated = all(s.key in _seconds for s in self.stages) eta = f" · about {remaining:.0f}s left" if calibrated else " · estimating time left..." return _bar(percent, f"{self.stages[index].label}: ~{percent:.0f}%", f"{elapsed:.0f}s elapsed{eta}") def _bar(percent: float, title: str, detail: str) -> str: """Styled by `.run-progress` in app.css.""" return ( "
" f"
{title}" f"{detail}
" f"
" )