Files
rag-technical-docs-assistant/docs/plans/local-s2s-adapter-plan.md
T

352 lines
25 KiB
Markdown

# Local speech-to-speech adapter: phased implementation plan
Date: 2026-10-15. Status: **planned; implementation and live acceptance not started**.
## 1. Outcome and scope
Add `local_s2s` alongside OpenAI and Gemini. Keep the OpenAI implementation usable,
preserve its behavior, and retain the original operational API container/image for
rollback. Initially run orchestration/VAD locally and obtain STT, a tool-capable
text LLM and TTS through OpenRouter. Local orchestration is not offline inference.
Replacing individual stages with local models is a later independent optimization.
This is a plan, not authorization to switch the running application, download
weights or perform unbounded paid evaluation. The original eight stages are consolidated into four phases without removing scope.
Each phase has a tangible demo,
acceptance criteria, evidence and a copy-ready English prompt. No phase has run.
## 2. Target architecture
```mermaid
flowchart LR
Browser[Existing Angular browser] <-->|Application PCM and JSON| API[FastAPI and VoiceRuntime]
API --> Tools[Existing tools and SearchService]
Tools --> Data[(Authorized knowledge)]
API --> Boundary[Small internal provider boundary]
Boundary <--> OA[Existing OpenAI adapter]
Boundary <--> GE[Existing Gemini adapter]
Boundary <--> LA[New local_s2s adapter]
LA <--> Engine[Pinned speech-to-speech service]
Engine --> VAD[Local VAD]
Engine --> STT[OpenRouter STT]
Engine --> LLM[OpenRouter text LLM]
Engine --> TTS[OpenRouter TTS]
```
The engine emits tool requests; our backend executes them. It receives no separate
database authority. Browser clients continue to use our API, never a public engine
endpoint or an OpenRouter key.
| Concern | Owner |
| --- | --- |
| Identity, organization, permissions and revisions | Existing application services |
| Turn ownership, deadlines, playback credits, evidence lifetime, next-turn release | VoiceRuntime |
| Native wire events/requests, error classification and configuration proof | Provider adapter |
| Actual local cancellation/history mutation and authoritative receipt | Pinned engine plus a minimal versioned extension when necessary |
| Recognition, text generation and synthesis | OpenRouter initially |
| Search/reuse, document eligibility and used-source validation | Existing knowledge services and DurableTools |
| Browser PCM and JSON contract | Existing application API contract |
### Boundary design
Normalize semantic events/operations actually required by runtime: effective
setup, consumed input, speech boundaries, generation identity, audio/transcript,
tool request and terminal outcome. Preserve native identity/provenance and replay
fingerprints. Do not turn an arbitrary transcript into a fake input-commit ack.
Interruption has separate generation-stop and history-repair progress. Runtime
supplies the response/item, session generation and final played coordinates; the
adapter establishes the actual result and runtime retains authority to release
the next turn. The receipt must identify the operation and applied state revision.
A boolean success flag, elapsed timer or sent request is insufficient proof.
Keep OpenAI's cancel/terminal/truncate/ack behavior intact behind this boundary.
Gemini's unsupported repair remains fail-closed. Prefer a small protocol/data model
to a plugin registry, event bus or wholesale state-machine rewrite.
## 3. Upstream evidence and hard compatibility gaps
Upstream documents a cascade and a core Realtime interface, not full OpenAI API
equivalence. Its documented conversation.item.truncate is a no-op without an ack.
Pin a commit and inspect its actual implementation/tests; changing the endpoint
URL alone cannot meet our cleanup contract. Sources:
[repository](https://github.com/huggingface/speech-to-speech),
[Realtime contract](https://github.com/huggingface/speech-to-speech/blob/main/src/speech_to_speech/api/openai_realtime/README.md).
HTTP STT progressive updates can repeatedly upload cumulative utterances. Remote
TTS cancellation can stop local publication without proving remote compute stopped.
These affect cost and late-result handling. Sources:
[STT backend](https://github.com/huggingface/speech-to-speech/blob/main/docs/openai-compatible-stt.md),
[TTS backend](https://github.com/huggingface/speech-to-speech/blob/main/docs/openai-compatible-tts.md).
OpenRouter documents separate STT/TTS endpoints and LLM tool calling. Model IDs,
voices, Persian behavior, supported parameters and rates require actual checks:
[STT](https://openrouter.ai/docs/guides/overview/multimodal/stt),
[TTS](https://openrouter.ai/docs/guides/overview/multimodal/tts),
[tools](https://openrouter.ai/docs/guides/features/tool-calling).
### Critical case: completed generation, unplayed audio
A model can finish text/audio while the browser has heard only the beginning.
Cancel may then do nothing, leaving unheard assistant prose in engine history.
Test the actual next LLM request, not only audio queue state or terminal flags.
Closing HTTP, clearing playback and returning response.done do not establish repair.
Do not infer a text prefix from audio-duration ratios or character counts. If
reliable heard-prefix alignment is unavailable, keep the gate open. Dropping an
entire interrupted assistant turn or retaining only fully played segments is a
weaker alternative policy requiring explicit acceptance and documentation; never
silently present it as exact heard-prefix preservation.
## 4. Invariants
1. OpenAI remains available. No automatic cross-provider fallback, new UI provider
selector or mid-session provider switch. Freeze effective configuration.
2. Keep original API containers/images and unrelated changes. No database reset,
pruning, compose down, rewriting old snapshots or document-content versioning.
3. Keep browser PCM16LE mono 24 kHz in both directions and existing public events.
4. One canonical search implementation, calibrated cutoff, document/chunk identity,
ready/active/authorized/undeleted filtering and final delivery revalidation.
5. Used-source membership validation is not full factual-entailment verification.
6. Generation completion differs from playback completion. Retained searches have
a lifetime independent of speech cancellation and retain their original deadline.
7. Bound queues, bytes, concurrency, deadlines and retry counts across all stages.
Do not stack automatic retries at multiple layers or conceal latency with buffers.
8. Secrets stay server-side. Default logs contain fixed categories/numeric state,
not complete provider payloads or real speech/document text.
9. Separate offline tests, isolated PostgreSQL acceptance, provider smokes and human
listening. Mock success or skipped checks do not prove live acceptance.
10. Never start a second API against the operational database. app/main.py invokes
lifecycle.reconcile_startup, which reconciles active sessions globally. A
different HTTP port alone is not isolation.
## 5. Four-phase roadmap
| Phase | Visible milestone | Previous stages combined |
| --- | --- | --- |
| 1 | OpenAI preserved through the provider boundary | Old 0 + 1 |
| 2 | Local/OpenRouter voice works in the existing test browser | Old 2 + 3 |
| 3 | Safe interruption plus full shared RAG and sources | Old 4 + 5 |
| 4 | Quality/cost decision and verified deployment rollback | Old 6 + 7 |
Only these four phases and their four prompts are active. The original version is
[archived](archive/local-s2s-eight-phase/README.md) for traceability. No implementation
phase has started, so this consolidation changes planning only. Required internal
checkpoints remain acceptance conditions inside each phase, not separate execution
phases. The preserved OpenAI path remains the fallback chosen by the operator.
## Phase 1 - Preserve OpenAI and introduce the provider boundary
**Visible outcome:** An existing OpenAI session still works; an offline before/after interruption replay proves the same cleanup and next-turn behavior.
**Entry:** No adapter implementation has started. Inspect the current repository and deployment first.
**Work:**
- Capture current/preserved container and image identities, effective provider/profile and focused regression results. Keep the operational deployment unchanged.
- Pin an upstream commit/build inputs and audit actual setup, input consumption, manual turn control, metadata/identities, tool events, audio rates, terminal states and history repair.
- Record a compatibility matrix and unresolved decisions, especially the no-op truncate and completed-but-unplayed history case.
- Extract only the small internal provider boundary needed by runtime. Runtime owns authorization, turn identity, playback credits, deadlines, evidence lifetime and next-turn release; adapters own native wire/confirmation details.
- Keep native OpenAI cancel/terminal/truncate/ack semantics, raw replay fingerprints and correlation intact. Preserve Gemini's conservative failures.
- Define correlated interruption progress with separate generation-stop and actual history-repair proof. Capability flags never waive safety gates.
- Add controlled-clock replay/conformance coverage and document the internal responsibility split without changing public browser behavior.
**Accept when:**
- Existing OpenAI regressions retain their assertions and pass; pre-existing failures are reported honestly.
- The same fixture before/after refactoring releases exactly one new response after matching cleanup, with wrong/missing/late/conflicting acknowledgements failing safely.
- Upstream SHA/build provenance, compatibility gaps and original rollback identities are recorded.
- No runtime switch, production data change, wholesale rewrite or model/voice branch in shared turn control.
**Show the user:** Run an existing OpenAI interaction if already authorized, and show a deterministic interruption trace through the new boundary. No new provider is enabled.
**Validation:** Existing context-sync, provider-selection, retained-search, source-report, output-limit and style tests; controlled-clock replay. Isolated PostgreSQL acceptance if persisted profile/lifecycle behavior is touched.
**Stop/narrow:** Unknown upstream behavior stays unverified. Do not weaken OpenAI or start a deployment switch to make the new boundary easier.
**Prompt:** [Phase 1](local-s2s-adapter-prompts/phase-01.md).
## Phase 2 - Add an isolated local stack and browser voice session
**Visible outcome:** The existing browser talks in Persian through local_s2s using OpenRouter STT/LLM/TTS, displays transcripts and closes normally in a disposable environment.
**Entry:** Phase 1 accepted. Isolated engine and candidate API use disposable DB/storage, not the operational database.
**Work:**
- Build a separate engine from the pinned SHA with local VAD and independently configured OpenRouter HTTP STT, tool-capable Chat Completions LLM and TTS. Avoid unnecessary local-model/GPU downloads.
- Discover/pin actual model IDs, voices, Persian hints, supported fields and PCM rates. Verify multipart/JSON STT, TTS streaming/format compatibility and explicit server-side credential forwarding.
- Begin with final-utterance STT. Bound requests/concurrency/bytes/retries/cleanup and meter startup probes. Provide stub mode plus an explicitly opt-in bounded live smoke and playable test audio.
- Add local_s2s settings/factory/readiness alongside openai/gemini. Preserve the browser PCM16LE mono24k and existing JSON events; use bounded stateful resampling if required.
- Freeze engine/patch/contract revision, component identities, voice/input policy and effective instruction/config digest. Compare to authoritative engine state, not request echoes or socket reachability.
- Map actual input acceptance, manual response creation/intent, tool framing, terminal/error and transcript/audio semantics without invented native commit events.
- Preserve owner/Origin/cookie/CSRF/replay/epoch checks and old snapshots. Audit provider DTO/DB constraints; use a forward migration only if actually needed and compatible with rollback.
- Use a separate test hostname/browser identity and disposable DB/storage. Until Phase 3, interruptions must fail safely and be labelled development-only; do not enable unsafe continuation.
**Accept when:**
- A normal browser greeting/answer/transcript/close works against the isolated candidate, and independent stage probes produce valid audio.
- Model/voice/rate/credential/effective-config mismatches fail setup accurately; keys and secret-derived hashes never enter profiles or logs.
- Existing OpenAI remains usable; new configuration does not rewrite old reservations or change the operational provider.
- Actual provider checks are distinguished from stubs. Missing credentials or real speech evidence leaves live acceptance pending.
**Show the user:** Show a recorded Persian utterance becoming a WAV response, then perform a normal greeting in the existing browser against the isolated candidate.
**Validation:** HTTP boundary fixtures, pinned-engine relevant tests, local adapter contract tests, isolated PostgreSQL profile/admission/replay/revocation cases and bounded actual browser/provider smoke.
**Stop/narrow:** A different port is not DB isolation. Do not claim safe barge-in or production parity before Phase 3; do not promote this provider.
**Prompt:** [Phase 2](local-s2s-adapter-prompts/phase-02.md).
## Phase 3 - Complete interruption, shared RAG and used sources
**Visible outcome:** The user interrupts and continues safely, receives correct document answers and sees only valid used sources; repeated interrupted searches are not duplicated.
**Entry:** Phase 2 accepted. Local engine history ownership and compatibility gaps are understood; shared SearchService remains authoritative.
**Work:**
- First implement/prove local interruption and history synchronization. Patch/version the pinned engine narrowly if it cannot apply the required real mutation.
- Cover active generation AND already-completed generation with queued unplayed audio. Track operation/response/item/segment/session identities and actual played coordinates.
- Inspect the next real controlled LLM request: unheard assistant sentinel text must be absent while valid previous user/tool/assistant context remains. Do not infer text alignment from duration/character ratios.
- Accept only receipts emitted after the actual mutation with applied history revision/provenance. Missing, wrong, stale or conflicting receipts fail within bounded deadlines; runtime retains release authority.
- If exact heard-prefix repair is unproven, keep the gate open. Whole-turn rollback or fully-played-segment retention is a weaker policy requiring explicit acceptance and contract documentation.
- Suppress obsolete STT/LLM/TTS outputs even if remote inference keeps computing. Keep backend retained retrieval separate from speech cancellation and preserve original deadlines.
- Then expose search_knowledge, reuse_last_evidence and report_used_sources through the existing backend dispatcher/ToolContext/DurableTools/SearchService; never add engine DB authority or a parallel RAG implementation.
- Preserve successful-terminal tool validation, call/item/response dedup, backend scope, calibrated eligible retrieval, source identities and handoff/delivery revalidation.
- Test current-turn source reports, private invalid-report correction, no_evidence versus technical error, knowledge revocation, topic switch and interrupted pending-search reuse.
- Evaluate known hours/fees, deputy name/organization and incentive percentage/date/exclusion failures. Correct citations alone do not prove correct answer content.
**Accept when:**
- No next response before generation-stop, real context repair and playback gates. Active and completed-unplayed history tests pass without fabricated acknowledgement events.
- Missing/wrong receipts fail safely; late output cannot contaminate a new turn or reused session; OpenAI interruption regressions remain intact.
- All three tools execute through existing authority; no stale/revoked/inactive/deleted evidence reaches reuse/delivery.
- Repeating an interrupted same-topic question uses one original retrieval plus revalidation, with valid used-source subset. Known critical document fixtures are answered correctly.
**Show the user:** Interrupt before an unheard sentinel and inspect the subsequent LLM context; then ask hours, deputy and incentive questions, including a pending-search interruption/repeat.
**Validation:** Controlled-clock/history-inspection/late-event tests; all affected OpenAI tests; existing retained-search/source suites extended to local; isolated DB evidence/revocation acceptance; bounded real barge-in and RAG checks.
**Stop/narrow:** This phase has two required checkpoints: history safety before dependent continuation tests, then shared RAG. They are not extra phases, and neither can be skipped or accepted from stopped playback alone.
**Prompt:** [Phase 3](local-s2s-adapter-prompts/phase-03.md).
## Phase 4 - Validate quality/cost and prove controlled switch/rollback
**Visible outcome:** A paired OpenAI/local scorecard supports the deployment decision, and the preserved OpenAI container is demonstrably restorable without rebuild.
**Entry:** Phase 3 accepted. Frozen corpus/model profiles, bounded live evaluation authorization and reviewable deployment/rollback configuration are available.
**Work:**
- Run paired Persian fixtures with the same authorized corpus and expected facts: names/roles, numbers/dates/conditions, noise/pauses/corrections, ambiguity, no evidence, follow-up and topic switch.
- Measure first audible response after speech end, tool time, interruption stop, underruns, duplicates, disconnects and successful tasks. Count actual model usage, STT duration, TTS units, startup/failure/abandoned work; unknown cost stays unknown.
- Fault-test quota, slow/down endpoints, partial stream loss, restart, saturation and teardown; no unbounded queues, retry storms or stale output. Use human listening separately from deterministic checks.
- Set/accept thresholds before evaluation. Provisional targets: zero critical factual fixture errors, p95 first-audible latency <= baseline + 1 second, no persistent underruns and cost per successful task <= 70% baseline for cost-saving promotion.
- Change one component at a time and report failures honestly. If quality/cost targets fail, keep OpenAI rather than silently changing thresholds or padding buffers.
- Finalize opt-in Compose, .env.example and operator runbook. Keep original container/image/config intact and separately tag candidate. Check any schema change against the old image; incompatible schema blocks simple rollback.
- Complete all reviewable preparation before operational switching. With explicit authorization, drain/close sessions, stop current API, then start candidate on operational DB. Never run both APIs against it simultaneously.
- Verify fresh-session greeting, RAG, sources, interruption and close; actually stop candidate/start preserved OpenAI without rebuild and verify a fresh baseline session.
- Leave final provider as explicitly requested. Record IDs/digests/commands/checks and limitations; container rollback is not DB/filesystem rollback or seamless media resume.
**Accept when:**
- Required paired factual, human-quality, failure and resource checks have actual evidence and sample counts; missing live checks block promotion.
- Cost-saving claims include failed/abandoned/startup usage; model pricing alone is not measured service savings.
- Original OpenAI restoration has actually succeeded and users/ingestion data are preserved. One API owns the operational lifecycle at a time.
- Final provider is explicitly recorded. Without switch authorization, prepare the result and remain operationally unchanged rather than claiming deployment completion.
**Show the user:** Play paired Persian name/date clips and show the scorecard. If authorized and accepted, demonstrate local RAG then OpenAI rollback without rebuilding the preserved container.
**Validation:** Focused/provider-free tests, isolated PostgreSQL acceptance, controlled faults, authorized paired real-provider checks and human listening; config/image inspection and controlled fresh-session switch/rollback.
**Stop/narrow:** Quality/cost evidence and explicit operational switch authorization are separate gates within this phase. Prepare independent work but do not bypass either.
**Prompt:** [Phase 4](local-s2s-adapter-prompts/phase-04.md).
## 6. Configuration, data and deployment contract
Proposed names below must be finalized before implementation and documented with
units/defaults. Do not create unvalidated option bags or leak credentials to LLMs.
| Scope | Proposed configuration |
| --- | --- |
| Selection | VOICE_PROVIDER=openai / gemini / local_s2s |
| Engine access | LOCAL_S2S_ENDPOINT and optional server-to-server credential |
| Identity | LOCAL_S2S_ENGINE_REVISION, adapter contract revision, effective config digest |
| Models | LOCAL_S2S_STT_MODEL, LOCAL_S2S_LLM_MODEL, LOCAL_S2S_TTS_MODEL, LOCAL_S2S_TTS_VOICE |
| Policy | STT language/final-only mode, LLM limits, TTS rate/format and verified options |
| Credentials | OpenRouter key only in engine component clients; never in database profile |
| Bounds | Connect/request/repair/close deadlines, queue bytes/items/concurrency |
Start with fixed component identities per engine configuration. Reservation
expectations must match authoritative engine state; never silently mutate shared
global models on every session.update. Later multi-profile concurrency requires a
separate isolation design.
Candidate API acceptance uses an isolated PostgreSQL/pgvector database and storage.
Cookies are not port-isolated: use a dedicated test hostname/browser profile and
credentials with matching trusted Origin. Do not copy production auth sessions
into a parallel test browser. Operational switching runs only one application API.
No schema migration is assumed. Inspect provider constraints/DTOs/profile replay
in Phases 1/2; use a new migration only if required and verify rollback image
compatibility. Do not add document_versions/version_id/version_no.
## 7. Validation commands and evidence
Verify paths and side effects at execution time. Focused baseline command:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py -q
```
Broaden when shared behavior changes justify it:
```powershell
.venv/Scripts/python -m pytest -m "not postgres"
git diff --check
```
Only with a verified disposable TEST_DATABASE_URL:
```powershell
.venv/Scripts/python -m pytest -m postgres --require-postgres
```
Existing timing/Windows failures must be recorded, not hidden by weakening tests.
Ordinary-suite skips do not establish PostgreSQL acceptance. Future local smoke
and conformance commands are phase deliverables, not existing verified commands.
Each phase produces docs/evaluation/local-s2s/phase-NN.md with scoped diff/commits,
exact commands, results, counts, fingerprints, visible demo, actual vs simulated
observations, not-run checks, blockers and rollback relevance. No keys/raw real
conversation logs. Save audio/transcripts only as explicitly consented evaluation
artifacts. Upstream CI success is not our runtime compatibility evidence.
Progress ledger: [local-s2s-adapter-progress.md](local-s2s-adapter-progress.md).
Prompt index: [local-s2s-adapter-prompts/README.md](local-s2s-adapter-prompts/README.md).
States: not_started, in_progress, offline_complete_live_pending, blocked, accepted.
Only accepted closes a required gate. Missing paid authorization blocks dependent
live work, not independent preparation. Reuse existing bounded authorization; do
not ask the user to approve the same action repeatedly.
## 8. Decisions to resolve and definition of done
- Upstream SHA, dependency/build lock and maintained patch provenance: Phase 1.
- Effective profile/config attestation and concurrent engine isolation: Phase 2.
- Real heard-prefix mapping/receipt: Phase 3 hard gate; weaker policy requires an
explicit product decision and intentional API/workflow documentation.
- Available OpenRouter models/voices, Persian quality, hardware footprint and
latency/cost: measure, do not infer from default local-model examples.
- Any future local weight licensing is checked for the chosen model separately.
- Candidate promotion follows evidence, not an assumption that local is cheaper.
Done means independently selectable local_s2s, working OpenAI, unchanged trusted
RAG authority, browser compatibility, real correlated history repair, bounded
failure handling and recorded Persian quality/latency/cost acceptance. Restoring
the compatible preserved OpenAI container has actually worked. Missing real or
human acceptance remains a blocker, not a completed implementation.