forehear 0.1.0__tar.gz

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.
Files changed (35) hide show
  1. forehear-0.1.0/.gitignore +13 -0
  2. forehear-0.1.0/LICENSE +202 -0
  3. forehear-0.1.0/NOTICE +13 -0
  4. forehear-0.1.0/PKG-INFO +287 -0
  5. forehear-0.1.0/README.md +244 -0
  6. forehear-0.1.0/data/README.md +69 -0
  7. forehear-0.1.0/pyproject.toml +81 -0
  8. forehear-0.1.0/src/forehear/__init__.py +47 -0
  9. forehear-0.1.0/src/forehear/bench/__init__.py +0 -0
  10. forehear-0.1.0/src/forehear/bench/cli.py +263 -0
  11. forehear-0.1.0/src/forehear/bench/data.py +180 -0
  12. forehear-0.1.0/src/forehear/bench/latency.py +78 -0
  13. forehear-0.1.0/src/forehear/bench/metrics.py +98 -0
  14. forehear-0.1.0/src/forehear/bench/report.py +263 -0
  15. forehear-0.1.0/src/forehear/bench/runner.py +230 -0
  16. forehear-0.1.0/src/forehear/bench/sim.py +236 -0
  17. forehear-0.1.0/src/forehear/controller.py +386 -0
  18. forehear-0.1.0/src/forehear/events.py +70 -0
  19. forehear-0.1.0/src/forehear/integrations/__init__.py +0 -0
  20. forehear-0.1.0/src/forehear/integrations/livekit.py +128 -0
  21. forehear-0.1.0/src/forehear/integrations/pipecat.py +213 -0
  22. forehear-0.1.0/src/forehear/policies.py +352 -0
  23. forehear-0.1.0/src/forehear/py.typed +0 -0
  24. forehear-0.1.0/src/forehear/retrievers.py +166 -0
  25. forehear-0.1.0/src/forehear/runtime.py +190 -0
  26. forehear-0.1.0/src/forehear/text.py +69 -0
  27. forehear-0.1.0/src/forehear/types.py +103 -0
  28. forehear-0.1.0/src/forehear/validators.py +114 -0
  29. forehear-0.1.0/tests/integrations/test_livekit.py +95 -0
  30. forehear-0.1.0/tests/integrations/test_pipecat.py +120 -0
  31. forehear-0.1.0/tests/test_bench.py +242 -0
  32. forehear-0.1.0/tests/test_controller.py +220 -0
  33. forehear-0.1.0/tests/test_policies.py +128 -0
  34. forehear-0.1.0/tests/test_runtime.py +104 -0
  35. forehear-0.1.0/tests/test_validators_text_retrievers.py +101 -0
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .venv/
5
+ dist/
6
+ build/
7
+ .coverage
8
+ coverage.xml
9
+ .pytest_cache/
10
+ .mypy_cache/
11
+ .ruff_cache/
12
+ /results-local/
13
+ *.part
forehear-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
forehear-0.1.0/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ forehear
2
+ Copyright 2026 sagarthegreat and forehear contributors
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ The benchmark data in data/ is distributed under its own licenses:
7
+
8
+ - data/heysquad_dev_vosk.jsonl.gz is derived from HeySQuAD (Wu et al., 2023,
9
+ arXiv:2304.13689), licensed CC BY 4.0. Transcripts were produced with Vosk
10
+ (Alpha Cephei, Apache 2.0).
11
+ - data/squad_v2_passages.jsonl.gz contains paragraphs from SQuAD 2.0
12
+ (Rajpurkar, Jia & Liang, 2018), licensed CC BY-SA 4.0. Redistributions of
13
+ this file must keep the same license.
@@ -0,0 +1,287 @@
1
+ Metadata-Version: 2.5
2
+ Name: forehear
3
+ Version: 0.1.0
4
+ Summary: Look-ahead retrieval for voice agents: start RAG while the user is still talking, and measure whether it pays off.
5
+ Project-URL: Homepage, https://github.com/sagarthegreat/Infinity
6
+ Project-URL: Repository, https://github.com/sagarthegreat/Infinity
7
+ Project-URL: Issues, https://github.com/sagarthegreat/Infinity/issues
8
+ Author: sagarthegreat
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Keywords: asr,benchmark,latency,livekit,pipecat,rag,retrieval,speculative-execution,voice-agents
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Provides-Extra: dense
27
+ Requires-Dist: model2vec>=0.4; extra == 'dense'
28
+ Requires-Dist: numpy>=1.24; extra == 'dense'
29
+ Provides-Extra: dev
30
+ Requires-Dist: mypy>=1.10; extra == 'dev'
31
+ Requires-Dist: numpy>=1.24; extra == 'dev'
32
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
33
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
34
+ Requires-Dist: pytest>=8; extra == 'dev'
35
+ Requires-Dist: ruff==0.17.6; extra == 'dev'
36
+ Provides-Extra: livekit
37
+ Requires-Dist: livekit-agents>=1.2; extra == 'livekit'
38
+ Provides-Extra: pipecat
39
+ Requires-Dist: pipecat-ai>=0.0.80; extra == 'pipecat'
40
+ Provides-Extra: plots
41
+ Requires-Dist: matplotlib>=3.7; extra == 'plots'
42
+ Description-Content-Type: text/markdown
43
+
44
+ <div align="center">
45
+
46
+ # forehear
47
+
48
+ **Look-ahead retrieval for voice agents.**
49
+ Start RAG while the user is still talking, cancel the guesses that turn out wrong,
50
+ and have context ready the moment they stop.
51
+
52
+ [![CI](https://github.com/sagarthegreat/Infinity/actions/workflows/ci.yml/badge.svg)](https://github.com/sagarthegreat/Infinity/actions/workflows/ci.yml)
53
+ ![Python](https://img.shields.io/badge/python-3.10%E2%80%933.13-blue)
54
+ ![License](https://img.shields.io/badge/license-Apache--2.0-green)
55
+ ![Dependencies](https://img.shields.io/badge/core%20dependencies-0-brightgreen)
56
+
57
+ </div>
58
+
59
+ Voice agents that answer from documents retrieve **after** the user stops
60
+ talking. The lookup (embedding call, vector database, reranker, web search)
61
+ sits on the critical path of every turn, while the speech recogniser has been
62
+ streaming its best guess of the question for seconds. forehear runs retrieval
63
+ on those guesses, validates the best one against the final transcript, and
64
+ hands the LLM context that is usually already there.
65
+
66
+ ```text
67
+ $ forehear replay --index 1 --policy stable_prefix --profile rerank # a real recording, real streaming ASR
68
+ 2400 ms interim "what didn't like her" <- the recogniser stumbles...
69
+ 2900 ms interim 'what did microsoft' <- ...and revises itself
70
+ 4300 ms speculate #1 'what did microsoft announced that it would rename' (~514 ms, GOLD)
71
+ 4800 ms speculate #2 'what did microsoft announced that it would rename one' (~1207 ms, GOLD)
72
+ 5000 ms speculate #3 'what did microsoft announced that it would rename one drive' (~666 ms, GOLD)
73
+ 5666 ms result #3
74
+ 5700 ms speculate #4 '... rename one drive for business' (~870 ms, GOLD)
75
+ 6110 ms end_of_turn 'what did microsoft announced that it would rename one drive for business to'
76
+ 6110 ms cancel #4
77
+ 6110 ms DELIVER reused #3, wait 0 ms, top-5 GOLD
78
+
79
+ without look-ahead the wait would have been 770 ms
80
+ ```
81
+
82
+ ## Results
83
+
84
+ Benchmarked on **4,018 questions read aloud by people**, streamed through a real
85
+ streaming recogniser, with retrieval over 19,831 passages. Every number below is
86
+ deterministic and reproduced by `forehear bench` in a few minutes on a laptop
87
+ ([full results](https://github.com/sagarthegreat/Infinity/blob/main/results/RESULTS.md), [method](https://github.com/sagarthegreat/Infinity/blob/main/docs/benchmark.md)).
88
+
89
+ **Most speech stacks give you interim transcripts and a final end of turn**
90
+ (Deepgram Nova, AssemblyAI, Google, AWS, Whisper-based). Mean time from end of
91
+ turn until retrieved context is ready:
92
+
93
+ | retrieval path (median latency) | retrieve after end of turn | **forehear** (`stable_prefix`) | ready at end of turn | calls / turn | recall@5 Δ |
94
+ |---|---:|---:|---:|---:|---:|
95
+ | hosted vector DB (250 ms) | 280 ms | **76 ms** (−73%) | 67% | 3.5 | −2.9 pt |
96
+ | + reranker (750 ms) | 806 ms | **392 ms** (−51%) | 35% | 3.5 | −3.3 pt |
97
+ | web search / tool (1.6 s) | 1,790 ms | **1,347 ms** (−25%) | 9% | 3.5 | −2.0 pt |
98
+ | in-process index (8 ms) | 10 ms | 2 ms | 80% | 3.5 | −1.3 pt |
99
+
100
+ **If your stack has an eager end-of-turn signal** (Deepgram Flux, LiveKit
101
+ preflight, Pipecat eager strategies), retrieving on it is today's best option,
102
+ and the bar forehear has to beat:
103
+
104
+ | retrieval path | after end of turn | on eager EOT | **forehear** (`stable_prefix`) | **forehear** (`adaptive`) |
105
+ |---|---:|---:|---:|---:|
106
+ | hosted vector DB | 280 ms | 45 ms · 1.1 calls | **17 ms** · 4.0 calls | 22 ms · 2.7 calls |
107
+ | + reranker | 806 ms | 507 ms · 1.1 calls | **323 ms** · 4.0 calls | 352 ms · 2.8 calls |
108
+ | web search / tool | 1,790 ms | 1,490 ms · 1.1 calls | **1,327 ms** · 4.0 calls | 1,348 ms · 2.8 calls |
109
+
110
+ What the benchmark says, including where look-ahead *doesn't* help:
111
+
112
+ * **The answer is often findable before the user finishes.** One second before
113
+ the last word, the interim transcript already retrieves a correct passage in
114
+ 43% of turns (final transcript: 76%).
115
+ * **It pays most where the wait is longest: slow retrieval and no eager signal.**
116
+ With an eager end-of-turn signal and a fast hosted KB, retrieving on that signal
117
+ already gets you within ~30 ms. A local index has nothing to win;
118
+ `Adaptive` measures that and switches itself off (1.01 calls/turn).
119
+ * **The cost is retrieval calls, not LLM calls:** about 3.5 per turn by default,
120
+ 2.6 with `stable_prefix_lean` or `Adaptive(budget=3)` for most of the savings.
121
+ (Deepgram's eager mode costs 50-70% more *LLM* calls.)
122
+ * **Reuse has a quality price, and you choose it.** Accepting a guess that covers
123
+ 80% of the final query's content words costs about 3 points of recall@5.
124
+ `ResultOverlap(0.8)` cuts that to under 1 point, and `ResultOverlap(0.9)` is lossless
125
+ (on this benchmark) while still saving 261 ms per turn behind a reranker.
126
+ * **Waiting for the recogniser to "settle" loses.** Trusting only words two
127
+ hypotheses agree on (LocalAgreement, standard in simultaneous translation)
128
+ does worse than a plain timer. The last words of a question never get a second
129
+ hypothesis, and they are the words retrieval needs.
130
+ * Results hold with dense retrieval ([`results/dense/`](https://github.com/sagarthegreat/Infinity/blob/main/results/dense/RESULTS.md)).
131
+
132
+ <p align="center">
133
+ <img src="https://raw.githubusercontent.com/sagarthegreat/Infinity/main/results/retrievability.png" width="49%" alt="Share of turns whose interim transcript already retrieves a correct passage, by time before end of speech">
134
+ <img src="https://raw.githubusercontent.com/sagarthegreat/Infinity/main/results/validator_sweep.png" width="49%" alt="Latency saved vs recall change for two reuse validators">
135
+ </p>
136
+ <p align="center">
137
+ <img src="https://raw.githubusercontent.com/sagarthegreat/Infinity/main/results/tradeoff_interims_only.png" width="98%" alt="Mean wait vs retrieval calls per turn for every policy and latency profile">
138
+ </p>
139
+
140
+ ## Install
141
+
142
+ ```bash
143
+ pip install forehear # core: zero dependencies
144
+ ```
145
+
146
+ Optional extras: `forehear[pipecat]`, `forehear[livekit]`, `forehear[plots]` (benchmark figures),
147
+ `forehear[dense]` (embedding retriever). The latest development version installs with
148
+ `pip install git+https://github.com/sagarthegreat/Infinity`.
149
+
150
+ ## Use it
151
+
152
+ ```python
153
+ from forehear import Lookahead
154
+
155
+ async def search_kb(query: str) -> list[dict]: # your existing retrieval; must be read-only
156
+ return await vector_db.search(query, k=5)
157
+
158
+ lookahead = Lookahead(retrieve=search_kb)
159
+
160
+ # wire these to your speech-to-text callbacks
161
+ lookahead.speech_started()
162
+ lookahead.interim("can i return a damaged")
163
+ lookahead.interim("can i return a damaged item") # retrieval starts here, in the background
164
+ delivery = await lookahead.end_of_turn("can i return a damaged item for a refund")
165
+
166
+ delivery.docs # context for the LLM, usually ready with zero wait
167
+ delivery.reused # True if it came from a guess made while the user was talking
168
+ delivery.wait_ms # latency retrieval added to this turn
169
+ ```
170
+
171
+ Run `python examples/quickstart.py` for a self-contained demo (no keys, no audio).
172
+
173
+ ### Pipecat
174
+
175
+ ```python
176
+ from forehear import Lookahead
177
+ from forehear.integrations.pipecat import lookahead_processors
178
+
179
+ tap, inject = lookahead_processors(Lookahead(retrieve=search_kb))
180
+ pipeline = Pipeline([
181
+ transport.input(), stt, tap, # tap: watches interim/eager transcripts
182
+ aggregators.user(), inject, llm, tts, # inject: adds the context before the LLM
183
+ transport.output(), aggregators.assistant(),
184
+ ])
185
+ ```
186
+
187
+ Works with Pipecat's own speculative inference (`enable_eager_end_of_turn`):
188
+ the speculative `LLMContextFrame` gets context for the eager transcript, and the
189
+ final frame reuses it without another call. Full bot: [`examples/pipecat_bot.py`](https://github.com/sagarthegreat/Infinity/blob/main/examples/pipecat_bot.py).
190
+
191
+ ### LiveKit Agents
192
+
193
+ ```python
194
+ from forehear import Lookahead
195
+ from forehear.integrations.livekit import LookaheadAgent, attach
196
+
197
+ class Support(LookaheadAgent): # instead of livekit.agents.Agent
198
+ def __init__(self):
199
+ super().__init__(instructions="...", lookahead=Lookahead(retrieve=search_kb))
200
+
201
+ agent = Support()
202
+ attach(session, agent.lookahead) # feeds interim transcripts from the AgentSession
203
+ await session.start(agent=agent, room=ctx.room)
204
+ ```
205
+
206
+ Full agent: [`examples/livekit_agent.py`](https://github.com/sagarthegreat/Infinity/blob/main/examples/livekit_agent.py).
207
+ Both adapters are tested against the real frameworks in CI.
208
+
209
+ ### Tuning
210
+
211
+ | knob | default | what it does |
212
+ |---|---|---|
213
+ | `policy` | `StablePrefix()` | when to guess: every hypothesis with 3+ content words and a new one |
214
+ | `policy=Adaptive(budget=3.0)` | | holds calls/turn under a budget; turns itself off when retrieval is already fast |
215
+ | `validator` | `TokenCoverage(0.8)` | when a guess may stand in for the final query |
216
+ | `validator=ResultOverlap(probe, threshold=0.8)` | | reuse only if a cheap first stage returns the same top-k: about 1/3 of the recall loss for most of the savings |
217
+ | `max_inflight` | `2` | concurrent guesses; the oldest is cancelled when a better one arrives |
218
+ | `hedge` | `False` | if the best guess is still running at end of turn, also start a fresh call and use whichever wins |
219
+
220
+ Speculative calls are discarded all the time, so route only **read-only**
221
+ retrieval through forehear, never bookings, writes or memory updates.
222
+
223
+ ## The benchmark
224
+
225
+ There was no open way to measure this, so forehear ships one. It uses **real
226
+ human speech, real streaming-ASR revisions and real retrieval**, and is
227
+ deterministic and CPU-only:
228
+
229
+ * 4,018 questions **read aloud by people** (HeySQuAD), streamed through
230
+ Vosk in 100 ms chunks. Every interim hypothesis is recorded, including
231
+ revisions such as "what didn't like her" → "what did microsoft".
232
+ * Retrieval over all 19,831 SQuAD v2 paragraphs (BM25, or dense with `--retriever dense`).
233
+ * The production `Controller` replayed on a virtual clock, with latency profiles
234
+ fitted to published measurements and paired draws across policies.
235
+ * Metrics borrowed from hardware prefetching (coverage, accuracy, lateness),
236
+ plus cost (calls/turn) and quality (recall@k vs. the final transcript).
237
+
238
+ ```bash
239
+ forehear bench # full matrix, a few minutes, writes results/
240
+ forehear replay --index 42 # millisecond timeline of one turn
241
+ ```
242
+
243
+ Methodology, metrics and limitations: [`docs/benchmark.md`](https://github.com/sagarthegreat/Infinity/blob/main/docs/benchmark.md).
244
+ Bring your own traces: [`data/README.md`](https://github.com/sagarthegreat/Infinity/blob/main/data/README.md).
245
+
246
+ ## How it works
247
+
248
+ ```
249
+ STT / turn detector ──events──▶ Controller (sans-IO state machine) ──actions──▶ runtime or simulator
250
+ SPEECH_START, INTERIM, ├─ Policy: "fire now, with this query" Start / Cancel / Deliver
251
+ EAGER_END_OF_TURN, └─ Validator: "may this result stand in
252
+ TURN_RESUMED, END_OF_TURN for the final query?"
253
+ ```
254
+
255
+ The controller does no I/O: it turns timestamped events into `Start`,
256
+ `Cancel` and `Deliver` actions. The asyncio runtime executes those for real,
257
+ and the benchmark executes them on a virtual clock, so **what you benchmark is
258
+ what you ship**. Design notes, and how to write your own policy:
259
+ [`docs/design.md`](https://github.com/sagarthegreat/Infinity/blob/main/docs/design.md).
260
+
261
+ ## Prior art
262
+
263
+ A literature and code review is in [`docs/research/`](https://github.com/sagarthegreat/Infinity/blob/main/docs/research/landscape-review.md). In short:
264
+
265
+ | | retrieval on partial speech | open code | open benchmark | waste reported |
266
+ |---|---|---|---|---|
267
+ | Stream RAG (Meta/CMU, 2025) | ✅ web search / KG | promised | AudioCRAG (partial) | ❌ |
268
+ | "When does streaming tool use help?" (2026) | ✅ analysis (CRAG) | ❌ | ❌ | bound only |
269
+ | Hiding tool latency on-device (2026) | ✅ tool calls | ❌ | ❌ | ❌ |
270
+ | LiveKit preemptive generation / Pipecat speculative inference | ❌ (LLM only) | ✅ | ❌ | ❌ |
271
+ | EVA-Bench (ServiceNow, 2026) | ❌ (lists speculation as a limitation) | ✅ | ✅ end-to-end | ❌ |
272
+ | **forehear** | ✅ any retriever | ✅ | ✅ real speech + real ASR | ✅ |
273
+
274
+ ## Roadmap
275
+
276
+ * Multi-turn spoken dialogue traces (DSTC10 Track 2) and more ASR engines
277
+ (Deepgram, AssemblyAI, Whisper-streaming, Parakeet).
278
+ * Learned policies: predict "the query has converged" from the hypothesis stream.
279
+ * Query completion: retrieve for the *predicted* end of the sentence, not the prefix.
280
+ * An end-to-end run inside EVA-Bench (needs API keys; contributions welcome).
281
+
282
+ ## Contributing, citing, license
283
+
284
+ Contributions are very welcome, especially new policies with benchmark results:
285
+ see [CONTRIBUTING.md](https://github.com/sagarthegreat/Infinity/blob/main/CONTRIBUTING.md). To cite forehear, use
286
+ [CITATION.cff](https://github.com/sagarthegreat/Infinity/blob/main/CITATION.cff). Code is Apache-2.0; benchmark data keeps its
287
+ upstream licenses (HeySQuAD CC BY 4.0, SQuAD CC BY-SA 4.0), see [NOTICE](https://github.com/sagarthegreat/Infinity/blob/main/NOTICE).