forehear 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
forehear/__init__.py ADDED
@@ -0,0 +1,47 @@
1
+ """forehear: look-ahead retrieval for voice agents.
2
+
3
+ Start retrieval while the user is still talking, cancel the guesses that turn
4
+ out wrong, and have context ready the moment they stop.
5
+ """
6
+
7
+ from .controller import Cancel, Controller, ControllerStats, Deliver, Start
8
+ from .events import EventKind, TranscriptEvent
9
+ from .policies import Adaptive, EagerEndOfTurn, FinalOnly, FixedInterval, Policy, StablePrefix, TurnView
10
+ from .retrievers import BM25Index, DenseIndex, with_latency
11
+ from .runtime import Lookahead, Retriever
12
+ from .types import Delivery, Doc, SpecStatus, Speculation, TurnOutcome
13
+ from .validators import ExactMatch, ResultOverlap, TokenCoverage, Validator
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ __all__ = [
18
+ "Adaptive",
19
+ "BM25Index",
20
+ "Cancel",
21
+ "Controller",
22
+ "ControllerStats",
23
+ "Deliver",
24
+ "DenseIndex",
25
+ "Delivery",
26
+ "Doc",
27
+ "EagerEndOfTurn",
28
+ "EventKind",
29
+ "ExactMatch",
30
+ "FinalOnly",
31
+ "FixedInterval",
32
+ "Lookahead",
33
+ "Policy",
34
+ "ResultOverlap",
35
+ "Retriever",
36
+ "SpecStatus",
37
+ "Speculation",
38
+ "StablePrefix",
39
+ "Start",
40
+ "TokenCoverage",
41
+ "TranscriptEvent",
42
+ "TurnOutcome",
43
+ "TurnView",
44
+ "Validator",
45
+ "__version__",
46
+ "with_latency",
47
+ ]
File without changes
forehear/bench/cli.py ADDED
@@ -0,0 +1,263 @@
1
+ """``forehear`` command line: run the benchmark, replay a turn, list profiles."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from .. import __version__
13
+ from ..controller import Action, Cancel, Controller, Deliver, Start
14
+ from ..retrievers import BM25Index, DenseIndex
15
+ from ..text import normalize
16
+ from .data import DataUnavailableError, Turn, load_corpus, load_turns
17
+ from .latency import PROFILES, LatencyProfile
18
+ from .runner import (
19
+ SCENARIOS,
20
+ eot_sweep,
21
+ retrievability_curve,
22
+ run_matrix,
23
+ standard_policies,
24
+ validator_sweep,
25
+ )
26
+ from .sim import Oracle, SearchCache, Timing, _turn_events
27
+
28
+ __all__ = ["main"]
29
+
30
+
31
+ def _log(msg: str) -> None:
32
+ print(f"[forehear] {msg}", file=sys.stderr, flush=True)
33
+
34
+
35
+ def _setup(args: argparse.Namespace) -> tuple[list[Turn], SearchCache, dict[str, Any]]:
36
+ t0 = time.time()
37
+ turns = load_turns(args.traces, limit=args.limit or None)
38
+ corpus = load_corpus(args.corpus)
39
+ index: BM25Index | DenseIndex
40
+ if getattr(args, "retriever", "bm25") == "dense":
41
+ index = DenseIndex.from_model2vec(corpus, args.dense_model)
42
+ retriever_name = f"dense ({args.dense_model}, model2vec)"
43
+ else:
44
+ index = BM25Index(corpus)
45
+ retriever_name = "BM25 (forehear.BM25Index)"
46
+ search = SearchCache(index.search, args.k)
47
+ _log(f"{len(turns):,} turns, {len(corpus):,} passages indexed in {time.time() - t0:.1f}s")
48
+ meta = {
49
+ "turns": len(turns),
50
+ "corpus": len(corpus),
51
+ "retriever": retriever_name,
52
+ "k": args.k,
53
+ "asr": "Vosk en-us-0.22-lgraph",
54
+ "chunk_ms": 100,
55
+ }
56
+ return turns, search, meta
57
+
58
+
59
+ def cmd_bench(args: argparse.Namespace) -> int:
60
+ turns, search, meta = _setup(args)
61
+ profiles = [PROFILES[p] for p in args.profiles] if args.profiles else list(PROFILES.values())
62
+ scenarios = {
63
+ name: Timing(asr_lag_ms=args.asr_lag_ms, eager_ms=t.eager_ms, eot_ms=args.eot_ms)
64
+ for name, t in SCENARIOS.items()
65
+ if not args.scenarios or name in args.scenarios
66
+ }
67
+ probe = search.ids
68
+ policies = [p for p in standard_policies(probe=probe) if not args.policies or p.name in args.policies]
69
+ meta["eot_ms"] = args.eot_ms
70
+ t0 = time.time()
71
+ rows = run_matrix(turns, search, scenarios=scenarios, profiles=profiles, policies=policies, progress=_log)
72
+ curve = retrievability_curve(turns, search) if not args.no_extras else []
73
+ sweep_profile = PROFILES["rerank"] if "rerank" in PROFILES else profiles[0]
74
+ sweep = (
75
+ validator_sweep(
76
+ turns, search, sweep_profile, Timing(asr_lag_ms=args.asr_lag_ms, eot_ms=args.eot_ms), probe=probe
77
+ )
78
+ if not args.no_extras
79
+ else []
80
+ )
81
+ eot_rows = (
82
+ eot_sweep(
83
+ turns,
84
+ search,
85
+ [p for p in profiles if p.name in ("hosted_kb", "rerank")] or profiles[:1],
86
+ asr_lag_ms=args.asr_lag_ms,
87
+ )
88
+ if not args.no_extras
89
+ else []
90
+ )
91
+ _log(f"simulated in {time.time() - t0:.1f}s ({len(search):,} distinct queries)")
92
+
93
+ from .report import markdown_report, plot_all, write_json
94
+
95
+ out = Path(args.out)
96
+ out.mkdir(parents=True, exist_ok=True)
97
+ meta["version"] = __version__
98
+ meta["profiles"] = {p.name: {"median_ms": p.median_ms, "p95_ms": p.p95_ms} for p in profiles}
99
+ write_json(
100
+ out / "results.json",
101
+ {"meta": meta, "rows": rows, "retrievability": curve, "sweep": sweep, "eot_sweep": eot_rows},
102
+ )
103
+ report = markdown_report(rows, curve, sweep, meta, eot_rows)
104
+ (out / "RESULTS.md").write_text(report)
105
+ if not args.no_plots:
106
+ try:
107
+ for p in plot_all(out, rows, curve, sweep):
108
+ _log(f"wrote {p}")
109
+ except ImportError:
110
+ _log("matplotlib not installed; skipping figures (pip install 'forehear[plots]')")
111
+ _log(f"wrote {out / 'RESULTS.md'} and {out / 'results.json'}")
112
+ if not args.quiet:
113
+ print(report)
114
+ return 0
115
+
116
+
117
+ def cmd_replay(args: argparse.Namespace) -> int:
118
+ """Print a millisecond timeline of one turn under one policy."""
119
+ turns, search, _ = _setup(args)
120
+ by_id = {t.id: t for t in turns}
121
+ turn = by_id.get(args.turn) if args.turn else turns[args.index]
122
+ if turn is None:
123
+ _log(f"unknown turn id {args.turn}")
124
+ return 2
125
+ specs = standard_policies(probe=search.ids)
126
+ spec = {p.name: p for p in specs}.get(args.policy)
127
+ if spec is None:
128
+ _log(f"unknown policy {args.policy}; choose from {', '.join(p.name for p in specs)}")
129
+ return 2
130
+ profile: LatencyProfile = PROFILES[args.profile]
131
+ scen = SCENARIOS[args.scenario]
132
+ timing = Timing(asr_lag_ms=args.asr_lag_ms, eager_ms=scen.eager_ms, eot_ms=args.eot_ms)
133
+ ctl: Controller = spec.factory()
134
+ if isinstance(ctl.policy, Oracle):
135
+ ctl.policy.final = turn.asr_final
136
+
137
+ print(f"turn {turn.id} policy={spec.name} profile={profile.name} scenario={args.scenario}")
138
+ print(f" question : {turn.question}")
139
+ print(f" asr final: {turn.asr_final}")
140
+ print(f" gold : {', '.join(sorted(turn.gold))}\n")
141
+ import heapq
142
+ import itertools
143
+
144
+ seq = itertools.count()
145
+ q: list[tuple[float, int, str, Any]] = [(e.t_ms, next(seq), "ev", e) for e in _turn_events(turn, timing)]
146
+ heapq.heapify(q)
147
+ live: dict[int, str] = {}
148
+
149
+ def gold_mark(query: str) -> str:
150
+ return "GOLD" if any(d.id in turn.gold for d in search(query)) else "miss"
151
+
152
+ def run(actions: list[Action], t: float) -> bool:
153
+ for a in actions:
154
+ if isinstance(a, Start):
155
+ lat = profile.sample(f"{turn.id}|{normalize(a.spec.query)}")
156
+ live[a.spec.id] = a.spec.query
157
+ heapq.heappush(q, (t + lat, next(seq), "res", a.spec.id))
158
+ kind = "speculate" if a.spec.speculative else "retrieve "
159
+ mark = gold_mark(a.spec.query)
160
+ print(f"{t:8.0f} ms {kind} #{a.spec.id} {a.spec.query!r} (~{lat:.0f} ms, {mark})")
161
+ elif isinstance(a, Cancel):
162
+ live.pop(a.spec_id, None)
163
+ print(f"{t:8.0f} ms cancel #{a.spec_id}")
164
+ elif isinstance(a, Deliver):
165
+ d = a.delivery
166
+ src = f"reused #{d.spec_id}" if d.reused else f"fresh #{d.spec_id}"
167
+ hit = "GOLD" if any(x.id in turn.gold for x in d.docs) else "miss"
168
+ print(f"{t:8.0f} ms DELIVER {src}, wait {d.wait_ms:.0f} ms, top-{args.k} {hit}")
169
+ return True
170
+ return False
171
+
172
+ while q:
173
+ t, _, kind, payload = heapq.heappop(q)
174
+ if kind == "ev":
175
+ ev = payload
176
+ label = ev.kind.value
177
+ print(f"{t:8.0f} ms {label:<17} {ev.text!r}" if ev.text else f"{t:8.0f} ms {label}")
178
+ if run(ctl.handle(ev), t):
179
+ break
180
+ else:
181
+ if payload not in live:
182
+ continue
183
+ query = live.pop(payload)
184
+ print(f"{t:8.0f} ms result #{payload}")
185
+ if run(ctl.on_result(payload, search(query), t), t):
186
+ break
187
+ base = profile.sample(f"{turn.id}|{normalize(turn.asr_final)}")
188
+ print(f"\nwithout look-ahead the wait would have been {base:.0f} ms")
189
+ return 0
190
+
191
+
192
+ def cmd_profiles(_: argparse.Namespace) -> int:
193
+ for p in PROFILES.values():
194
+ print(f"{p.name:<11} median {p.median_ms:>5.0f} ms p95 {p.p95_ms:>5.0f} ms {p.description}")
195
+ return 0
196
+
197
+
198
+ def cmd_curve(args: argparse.Namespace) -> int:
199
+ turns, search, _ = _setup(args)
200
+ print(json.dumps(retrievability_curve(turns, search), indent=2))
201
+ return 0
202
+
203
+
204
+ def main(argv: list[str] | None = None) -> int:
205
+ ap = argparse.ArgumentParser(prog="forehear", description="Look-ahead retrieval for voice agents.")
206
+ ap.add_argument("--version", action="version", version=f"forehear {__version__}")
207
+ sub = ap.add_subparsers(dest="cmd", required=True)
208
+
209
+ def common(p: argparse.ArgumentParser) -> None:
210
+ p.add_argument("--traces", help="trace file (default: bundled HeySQuAD/Vosk traces)")
211
+ p.add_argument("--corpus", help="corpus file (default: bundled SQuAD v2 passages)")
212
+ p.add_argument("--limit", type=int, default=0, help="use only the first N turns")
213
+ p.add_argument("--k", type=int, default=5, help="top-k for recall (default 5)")
214
+ p.add_argument(
215
+ "--eot-ms", type=float, default=500.0, help="end of turn after last word (default 500)"
216
+ )
217
+ p.add_argument("--asr-lag-ms", type=float, default=0.0, help="extra delay on interims (default 0)")
218
+ p.add_argument(
219
+ "--retriever", choices=["bm25", "dense"], default="bm25", help="retriever (default bm25)"
220
+ )
221
+ p.add_argument(
222
+ "--dense-model",
223
+ default="minishlab/potion-retrieval-32M",
224
+ help="model2vec model for --retriever dense (pip install 'forehear[dense]')",
225
+ )
226
+
227
+ b = sub.add_parser("bench", help="run the full benchmark matrix")
228
+ common(b)
229
+ b.add_argument("--profiles", nargs="*", choices=list(PROFILES), help="latency profiles")
230
+ b.add_argument("--scenarios", nargs="*", choices=list(SCENARIOS), help="turn-signal scenarios")
231
+ b.add_argument("--policies", nargs="*", help="policy names (default: all)")
232
+ b.add_argument("--out", default="results", help="output directory (default: results/)")
233
+ b.add_argument("--no-plots", action="store_true")
234
+ b.add_argument("--no-extras", action="store_true", help="skip retrievability curve and sweep")
235
+ b.add_argument("--quiet", action="store_true")
236
+ b.set_defaults(func=cmd_bench)
237
+
238
+ r = sub.add_parser("replay", help="print a timeline of one turn")
239
+ common(r)
240
+ r.add_argument("--turn", help="turn id")
241
+ r.add_argument("--index", type=int, default=0, help="turn index if --turn is not given")
242
+ r.add_argument("--policy", default="stable_prefix")
243
+ r.add_argument("--profile", default="rerank", choices=list(PROFILES))
244
+ r.add_argument("--scenario", default="interims_only", choices=list(SCENARIOS))
245
+ r.set_defaults(func=cmd_replay)
246
+
247
+ c = sub.add_parser("curve", help="print the retrievability curve as JSON")
248
+ common(c)
249
+ c.set_defaults(func=cmd_curve)
250
+
251
+ p = sub.add_parser("profiles", help="list latency profiles")
252
+ p.set_defaults(func=cmd_profiles)
253
+
254
+ args = ap.parse_args(argv)
255
+ try:
256
+ return int(args.func(args))
257
+ except DataUnavailableError as exc:
258
+ _log(str(exc))
259
+ return 2
260
+
261
+
262
+ if __name__ == "__main__":
263
+ raise SystemExit(main())
forehear/bench/data.py ADDED
@@ -0,0 +1,180 @@
1
+ """Benchmark data: spoken turns with real streaming-ASR interim hypotheses.
2
+
3
+ Two files, both produced by ``scripts/build_heysquad_traces.py``:
4
+
5
+ ``heysquad_dev_vosk.jsonl.gz``
6
+ One line per human-recorded HeySQuAD question: every interim hypothesis
7
+ Vosk emitted while streaming the audio in 100 ms chunks (timestamped in
8
+ audio time), the final transcript, word-level speech start/end, and the id
9
+ of the gold SQuAD paragraph.
10
+ ``squad_v2_passages.jsonl.gz``
11
+ The retrieval corpus: every unique SQuAD v2 paragraph (train + dev).
12
+
13
+ Files are looked up in ``$FOREHEAR_DATA``, then the repository's ``data/``
14
+ directory, then the user cache (downloaded on first use).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import gzip
20
+ import hashlib
21
+ import json
22
+ import os
23
+ import sys
24
+ import urllib.error
25
+ import urllib.request
26
+ from collections.abc import Iterator
27
+ from dataclasses import dataclass
28
+ from pathlib import Path
29
+
30
+ from .. import __version__
31
+ from ..types import Doc
32
+
33
+ __all__ = [
34
+ "CORPUS_FILE",
35
+ "TRACES_FILE",
36
+ "DataUnavailableError",
37
+ "Turn",
38
+ "data_path",
39
+ "load_corpus",
40
+ "load_turns",
41
+ ]
42
+
43
+
44
+ class DataUnavailableError(RuntimeError):
45
+ """The benchmark data could not be found locally or downloaded."""
46
+
47
+
48
+ TRACES_FILE = "heysquad_dev_vosk.jsonl.gz"
49
+ CORPUS_FILE = "squad_v2_passages.jsonl.gz"
50
+
51
+ #: SHA-256 of the published data files. Downloads are checked against these,
52
+ #: so a benchmark run always uses exactly the data the results were made with.
53
+ _SHA256 = {
54
+ TRACES_FILE: "2adad5e240dfea969f49dfe6ce82cb83b50a31a476acf6d4b0ef3c2bd0b0147a",
55
+ CORPUS_FILE: "07590f68585d5270347b89d0833565c049ec277d6ceda187dbb393774cdd1fdd",
56
+ }
57
+ _REPO_RAW = "https://raw.githubusercontent.com/sagarthegreat/Infinity"
58
+
59
+
60
+ def _base_urls() -> list[str]:
61
+ """Where to download from: an explicit override, else this release's tag, then ``main``."""
62
+ override = os.environ.get("FOREHEAR_DATA_URL")
63
+ if override:
64
+ return [override if override.endswith("/") else override + "/"]
65
+ return [f"{_REPO_RAW}/v{__version__}/data/", f"{_REPO_RAW}/main/data/"]
66
+
67
+
68
+ @dataclass(frozen=True, slots=True)
69
+ class Turn:
70
+ """One user turn as a voice agent would have heard it."""
71
+
72
+ id: str
73
+ question: str
74
+ """Reference (typed) question."""
75
+ gold: frozenset[str]
76
+ """Ids of passages that answer the question."""
77
+ asr_final: str
78
+ """Final ASR transcript."""
79
+ speech_start_ms: float
80
+ speech_end_ms: float
81
+ events: tuple[tuple[float, str], ...]
82
+ """``(audio_time_ms, hypothesis)`` for every change of the interim hypothesis."""
83
+ words: tuple[tuple[str, float, float], ...] = ()
84
+ """``(word, start_ms, end_ms)`` from the final ASR result."""
85
+ is_impossible: bool = False
86
+
87
+ @property
88
+ def speech_ms(self) -> float:
89
+ return self.speech_end_ms - self.speech_start_ms
90
+
91
+
92
+ def _candidates(name: str) -> Iterator[Path]:
93
+ env = os.environ.get("FOREHEAR_DATA")
94
+ if env:
95
+ yield Path(env) / name
96
+ here = Path(__file__).resolve()
97
+ for parent in here.parents:
98
+ if (parent / "pyproject.toml").exists():
99
+ yield parent / "data" / name
100
+ break
101
+ yield Path.cwd() / "data" / name
102
+ cache = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "forehear"
103
+ yield cache / name
104
+
105
+
106
+ def data_path(name: str, *, download: bool = True) -> Path:
107
+ """Locate a benchmark data file, downloading it to the cache if needed."""
108
+ candidates = list(_candidates(name))
109
+ for path in candidates:
110
+ if path.exists():
111
+ return path
112
+ if not download:
113
+ raise FileNotFoundError(f"{name} not found in: {', '.join(map(str, candidates))}")
114
+ target = candidates[-1]
115
+ target.parent.mkdir(parents=True, exist_ok=True)
116
+ tmp = target.with_suffix(target.suffix + ".part")
117
+ errors = []
118
+ for base in _base_urls():
119
+ url = base + name
120
+ print(f"forehear: downloading {url}", file=sys.stderr)
121
+ try:
122
+ digest = hashlib.sha256()
123
+ with urllib.request.urlopen(url, timeout=60) as resp, open(tmp, "wb") as fh:
124
+ while chunk := resp.read(1 << 20):
125
+ digest.update(chunk)
126
+ fh.write(chunk)
127
+ except (OSError, urllib.error.URLError) as exc:
128
+ errors.append(f"{url}: {exc}")
129
+ continue
130
+ expected = _SHA256.get(name)
131
+ if expected and digest.hexdigest() != expected and not os.environ.get("FOREHEAR_DATA_URL"):
132
+ errors.append(f"{url}: checksum mismatch")
133
+ continue
134
+ tmp.replace(target)
135
+ return target
136
+ tmp.unlink(missing_ok=True)
137
+ raise DataUnavailableError(
138
+ f"could not download the benchmark data file {name}.\n "
139
+ + "\n ".join(errors)
140
+ + "\nDownload it manually from https://github.com/sagarthegreat/Infinity/tree/main/data "
141
+ f"into {target.parent} (or set FOREHEAR_DATA to the folder that holds it)."
142
+ )
143
+
144
+
145
+ def load_turns(path: str | Path | None = None, *, limit: int | None = None) -> list[Turn]:
146
+ """Load benchmark turns."""
147
+ p = Path(path) if path else data_path(TRACES_FILE)
148
+ out: list[Turn] = []
149
+ with gzip.open(p, "rt", encoding="utf-8") as fh:
150
+ for line in fh:
151
+ r = json.loads(line)
152
+ out.append(
153
+ Turn(
154
+ id=r["id"],
155
+ question=r["question"],
156
+ gold=frozenset(r["gold_doc_ids"]),
157
+ asr_final=r["asr_final"],
158
+ speech_start_ms=float(r["speech_start_ms"]),
159
+ speech_end_ms=float(r["speech_end_ms"]),
160
+ events=tuple((float(t), str(text)) for t, text in r["events"]),
161
+ words=tuple((str(w), float(a), float(b)) for w, a, b in r.get("words", ())),
162
+ is_impossible=bool(r.get("is_impossible", False)),
163
+ )
164
+ )
165
+ if limit and len(out) >= limit:
166
+ break
167
+ return out
168
+
169
+
170
+ def load_corpus(path: str | Path | None = None) -> list[Doc]:
171
+ """Load the retrieval corpus."""
172
+ p = Path(path) if path else data_path(CORPUS_FILE)
173
+ docs: list[Doc] = []
174
+ with gzip.open(p, "rt", encoding="utf-8") as fh:
175
+ for line in fh:
176
+ r = json.loads(line)
177
+ title = r.get("title") or ""
178
+ text = f"{title}. {r['text']}" if title else r["text"]
179
+ docs.append(Doc(id=r["id"], text=text))
180
+ return docs
@@ -0,0 +1,78 @@
1
+ """Retrieval latency profiles.
2
+
3
+ Each profile is a log-normal distribution fitted to a median and a p95. The
4
+ values come from published measurements and vendor documentation collected in
5
+ ``docs/research/``; they are meant to be representative, not exact. Pass your
6
+ own with ``LatencyProfile(name, median_ms, p95_ms)`` or measure your stack and
7
+ replay it.
8
+
9
+ Sampling is *keyed*: the latency of a call depends only on ``(seed, key)``,
10
+ where the key is the turn id plus the normalised query. Every policy therefore
11
+ sees the same latency for the same query in the same turn, so comparisons
12
+ between policies are paired and noise-free.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import math
19
+ import random
20
+ from dataclasses import dataclass
21
+
22
+ __all__ = ["PROFILES", "LatencyProfile"]
23
+
24
+ _Z95 = 1.6448536269514722
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class LatencyProfile:
29
+ name: str
30
+ median_ms: float
31
+ p95_ms: float
32
+ description: str = ""
33
+ seed: int = 0
34
+
35
+ @property
36
+ def sigma(self) -> float:
37
+ return max(0.0, math.log(self.p95_ms / self.median_ms) / _Z95)
38
+
39
+ @property
40
+ def mean_ms(self) -> float:
41
+ return self.median_ms * math.exp(self.sigma**2 / 2)
42
+
43
+ def sample(self, key: str) -> float:
44
+ digest = hashlib.blake2b(f"{self.seed}|{self.name}|{key}".encode(), digest_size=8).digest()
45
+ rng = random.Random(int.from_bytes(digest, "big"))
46
+ return rng.lognormvariate(math.log(self.median_ms), self.sigma)
47
+
48
+
49
+ PROFILES: dict[str, LatencyProfile] = {
50
+ p.name: p
51
+ for p in (
52
+ LatencyProfile(
53
+ "local",
54
+ 8,
55
+ 25,
56
+ "In-process index (FAISS/BM25 in the agent process). Look-ahead cannot help much here.",
57
+ ),
58
+ LatencyProfile(
59
+ "hosted_kb",
60
+ 250,
61
+ 550,
62
+ "Embedding API + managed vector DB. Remote vector DBs measure ~100-300 ms and remote "
63
+ "embedding ~200 ms (Salesforce VoiceAgentRAG); ElevenLabs documents ~250 ms for RAG.",
64
+ ),
65
+ LatencyProfile(
66
+ "rerank",
67
+ 750,
68
+ 1400,
69
+ "Hosted KB plus a cross-encoder reranker over 10-20 candidates (measured 585-1258 ms).",
70
+ ),
71
+ LatencyProfile(
72
+ "web_search",
73
+ 1600,
74
+ 3500,
75
+ "Web search or a tool call. Stream RAG measures 3.37 s mean tool latency.",
76
+ ),
77
+ )
78
+ }
@@ -0,0 +1,98 @@
1
+ """Aggregate metrics, named after their hardware-prefetching ancestors where one exists."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from dataclasses import asdict, dataclass
7
+
8
+ from .sim import TurnResult
9
+
10
+ __all__ = ["Summary", "percentile", "summarize"]
11
+
12
+
13
+ def percentile(values: Sequence[float], q: float) -> float:
14
+ """Linear-interpolated percentile, ``q`` in [0, 100]."""
15
+ if not values:
16
+ return 0.0
17
+ xs = sorted(values)
18
+ pos = (len(xs) - 1) * q / 100.0
19
+ lo = int(pos)
20
+ hi = min(lo + 1, len(xs) - 1)
21
+ return xs[lo] + (xs[hi] - xs[lo]) * (pos - lo)
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class Summary:
26
+ turns: int
27
+ # latency
28
+ wait_mean_ms: float
29
+ wait_p50_ms: float
30
+ wait_p90_ms: float
31
+ wait_p95_ms: float
32
+ baseline_wait_mean_ms: float
33
+ baseline_wait_p50_ms: float
34
+ baseline_wait_p90_ms: float
35
+ saved_mean_ms: float
36
+ saved_p50_ms: float
37
+ saved_p90_ms: float
38
+ zero_wait_rate: float
39
+ """Share of turns whose context was ready at end of turn."""
40
+ # speculation quality (prefetch vocabulary)
41
+ coverage: float
42
+ """Turns served from a speculative call / turns."""
43
+ accuracy: float
44
+ """Speculative calls that served a turn / speculative calls issued."""
45
+ lateness: float
46
+ """Served turns where the speculative call was still in flight at end of turn."""
47
+ # cost
48
+ calls_per_turn: float
49
+ speculative_calls_per_turn: float
50
+ wasted_calls_per_turn: float
51
+ # quality
52
+ recall_at_k: float
53
+ baseline_recall_at_k: float
54
+ recall_delta: float
55
+ lead_mean_ms: float
56
+ """Mean lead time over turns where a speculative call held a gold passage before end of turn."""
57
+
58
+ def as_dict(self) -> dict[str, float]:
59
+ return asdict(self)
60
+
61
+
62
+ def summarize(results: Sequence[TurnResult]) -> Summary:
63
+ n = len(results)
64
+ if n == 0:
65
+ raise ValueError("no results")
66
+ waits = [r.wait_ms for r in results]
67
+ base = [r.baseline_wait_ms for r in results]
68
+ saved = [r.saved_ms for r in results]
69
+ spec_calls = sum(r.speculative_calls for r in results)
70
+ total_calls = sum(r.speculative_calls + r.fresh_calls for r in results)
71
+ served = [r for r in results if r.reused]
72
+ leads = [r.lead_ms for r in results if r.lead_ms is not None]
73
+ recall = sum(r.hit for r in results) / n
74
+ base_recall = sum(r.baseline_hit for r in results) / n
75
+ return Summary(
76
+ turns=n,
77
+ wait_mean_ms=sum(waits) / n,
78
+ wait_p50_ms=percentile(waits, 50),
79
+ wait_p90_ms=percentile(waits, 90),
80
+ wait_p95_ms=percentile(waits, 95),
81
+ baseline_wait_mean_ms=sum(base) / n,
82
+ baseline_wait_p50_ms=percentile(base, 50),
83
+ baseline_wait_p90_ms=percentile(base, 90),
84
+ saved_mean_ms=sum(saved) / n,
85
+ saved_p50_ms=percentile(saved, 50),
86
+ saved_p90_ms=percentile(saved, 90),
87
+ zero_wait_rate=sum(1 for w in waits if w <= 0.0) / n,
88
+ coverage=len(served) / n,
89
+ accuracy=len(served) / spec_calls if spec_calls else 0.0,
90
+ lateness=(sum(r.late for r in served) / len(served)) if served else 0.0,
91
+ calls_per_turn=total_calls / n,
92
+ speculative_calls_per_turn=spec_calls / n,
93
+ wasted_calls_per_turn=sum(r.wasted_calls for r in results) / n,
94
+ recall_at_k=recall,
95
+ baseline_recall_at_k=base_recall,
96
+ recall_delta=recall - base_recall,
97
+ lead_mean_ms=(sum(leads) / len(leads)) if leads else 0.0,
98
+ )