feat(voice): implement local S2S retained history and provider selection

Add pinned CPU engine dependencies, retained interrupted-response history, provider admission, offline evaluation and isolated browser tooling.

Record Phase 2 acceptance and Phase 3/4 preparation, bounded paid-test accounting and interruption incident findings. Human interruption acceptance, paired OpenAI evaluation and rollback remain pending.
This commit is contained in:
11linear11
2026-10-16 17:09:27 -04:00
parent 8d348f0ba1
commit a94b8cd3ea
111 changed files with 14764 additions and 58 deletions
+1 -1
View File
@@ -5,7 +5,7 @@ FROM ${ENGINE_BASE_IMAGE}
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
WORKDIR /app
COPY .local-s2s-build/requirements.lock /build/requirements.lock
RUN pip install --no-cache-dir --require-hashes -r /build/requirements.lock
RUN pip install --no-cache-dir --only-binary=:all: --require-hashes -r /build/requirements.lock
COPY .local-s2s-build/upstream /opt/speech-to-speech
RUN pip install --no-deps --no-build-isolation /opt/speech-to-speech
COPY pyproject.toml alembic.ini /app/
+4 -1
View File
@@ -9,7 +9,10 @@
!services/local_s2s/
!services/local_s2s/**
!.local-s2s-build/
!.local-s2s-build/**
!.local-s2s-build/upstream/
!.local-s2s-build/upstream/**
!.local-s2s-build/requirements.lock
!.local-s2s-build/build-manifest.json
**/.git
**/.venv
**/__pycache__
+114 -3
View File
@@ -1,11 +1,122 @@
# Phase 2 local engine (development only)
This stack is isolated from operational OpenAI. Phase 1 live acceptance is still
pending. Do not activate this candidate until that prerequisite is accepted and
a bounded live run is authorized. Offline tests do not prove real Persian voice.
Current preparation (2026-10-16): [Phase 4 frontend/provider selection and paired evaluation tooling](../../docs/evaluation/local-s2s/phase-04.md).
Phase 3 retains interrupted answers as explicitly unheard drafts per the user's
revised policy; real barge-in/RAG/factual acceptance remains pending. Phase 4 is
prepared for isolated testing, not deployed or accepted. No new paid request,
audio tuning or operational switch. Earlier checkpoints below are historical.
Current verdict (2026-10-16): **Phase 2 accepted for isolated development-only
normal Persian browser voice**. [Final evidence](../../docs/evaluation/local-s2s/phase-02-accepted-20261016.md)
and [machine-readable results](../../docs/evaluation/local-s2s/phase-02-accepted-20261016.json):
125 local + 258 preservation + 63 PostgreSQL tests passed; actual browser response
fully played and closed normally. Conservative cost exposure $0.420504399, below
the same $1 cap; final invoice details remain unresolved with full reserves held.
Paid engine stopped normally. No buffer/speed change or operational promotion.
Phase 3/4 remain not_started. Earlier checkpoints below are historical and are
superseded where they describe open Phase 2 gates.
Current incident follow-up: [first browser-turn initialization stall repaired](../../docs/evaluation/local-s2s/phase-02-browser-first-turn-repair-20261016.md).
User session failed after transcription. Native snapshots identified first-reply
Lingua model preload; same cache now warms before listener readiness. Three full
proxy/API/native continuous-input fixture sessions and98 focused tests pass.
Fixed image a51167d1952a; no buffer/speed/timeout change. Repair handoff carries all
prior attempts; cumulative reservation ceiling $0.995118333 of the same$1. Human
browser acceptance remains open; earlier ready checkpoints below are historical.
Current browser handoff (2026-10-16): [isolated browser is ready](../../docs/evaluation/local-s2s/phase-02-browser-ready-20261016.md).
Angular/API/login and actual proxied WebSocket session_ready/normal close passed;
no inference in connection check. Three real startup probes passed. Human microphone/
reply/transcript acceptance remains open. Same $1 authorization; reconciled prior
exposure $0.689118333, cumulative ceiling $0.901118333, startup reserve $0.748118333.
Private login file and 30-minute engine watchdog documented. No tuning/operational change.
Latest actual run (2026-10-16): [real native Persian round trip passed](../../docs/evaluation/local-s2s/phase-02-real-native-20261016.md).
Six actual requests succeeded, 2.528s reply audio, successful terminal/normal
release and clean shutdown. Cumulative reservation is $0.998 of the same $1;
final billing remains unresolved, so no further paid request. User accepted native output; browser/microphone remains open; earlier memory blocker below is historical.
No operational switch or audio tuning change.
Latest preparation (2026-10-16): [bounded real native session](../../docs/evaluation/local-s2s/phase-02-native-paid-preparation-20261016.md).
Single-sample pronunciation accepted by the user. Cumulative reservation ceiling
is $0.998 including the retained $0.56; no new paid request. Real launch awaits
>5GiB host headroom. Budget/runner checks and actual native fixture pass; browser
and real session acceptance remain open. Audio tuning and operations unchanged.
This stack is isolated from operational OpenAI. Phase 1 live acceptance passed
on the isolated Linux candidate; see the current evidence below. Local engine
conformance/assets and bounded live authorization remain separate activation gates.
Offline tests do not prove real local_s2s Persian voice.
## Offline result now
Real component follow-up **2026-10-16**: [authorized $1 component evidence](../../docs/evaluation/local-s2s/phase-02-real-components-20261016.md).
Actual PCM TTS/Kore, Whisper STT and GPT-4.1 mini succeeded after an initial WAV
HTTP400. Generated Persian audio is 5.16s; human listening is pending. Four attempts,
$0.56 retained reservation; STT+LLM reported about $0.00033833, TTS/final billing not
yet verified. Do not bypass the exclusive paid ledger to rerun. Real browser/native
integration remains open; no engine startup, tuning or operational change occurred.
Native session **2026-10-16**: [actual session/audio/signals and memory incident](../../docs/evaluation/local-s2s/phase-02-native-session-20261016.md).
Candidate `phase2-session-fix-v2`, immutable ID
`sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b`,
passed normal native PCM/transcript/intent/close, setup mismatch, OS-signal and
fixture-provider failure checks. 110 focused tests pass. Gateway/client shutdown
now precedes dependent waits. Run the report's guarded sequential runner; earlier
parallel 4GiB tests coincided with an actual IDE OOM kill. Audio limits/tuning and
existing deadlines are unchanged. Cold/one-core failures remain disclosed; real
component/Persian browser acceptance remains pending. No paid calls or downloads.
Queue repair **2026-10-16**: [corrected candidate evidence](../../docs/evaluation/local-s2s/phase-02-queue-repair-20261016.md).
The type-compatible subclass resolves Queue[Any] construction without changing
the 256-item bound or overflow stop. Separate image `phase2-queue-fix`, ID
`sha256:6ad4a6a418ef3122923724760b9b2fa8e55cd7db10189614492f5e2b1dc23a74`,
passed actual asset-backed construction, three fixture warmups, typed queue/FIFO/
overflow and cleanup checks. 109 targeted tests passed. The original image/tag
and Compose defaults are preserved; native-session/audio/POSIX gates remain open.
Authorized asset acquisition **2026-10-16**: [actual evidence and constructor failure](../../docs/evaluation/local-s2s/phase-02-linux-assets-20261016.md).
The required resources now exist under `.local-s2s-build/assets-linux/`; the
14-file Linux manifest is `docs/evaluation/local-s2s/phase-02-linux-assets.json`,
SHA-256 `869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26`.
Actual NLTK POS and Silero JIT/silence checks pass in the image. Full construction
fails because the Queue lambda cannot serve upstream Queue[Any] annotations.
No runtime fix applied during downloading; resolve this before real startup.
Follow-up **2026-10-16**: [asset inventory and Linux signal subset](../../docs/evaluation/local-s2s/phase-02-offline-preflight-20261016.md).
Four actual SIGINT/SIGTERM checks passed against lifecycle/gateway with fixture
runtime/provider I/O. Existing punkt data loaded inside the image; NLTK POS tagger
and Silero source/JIT resources are still missing. This does not close full-engine
or native-worker signal acceptance. The report includes the repeatable offline
command; no runtime edits, downloads or paid calls occurred.
Latest **2026-10-16** result: image `rag-local-s2s-candidate:phase2` built
successfully, ID `sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1`.
15 native imports, six actual-handler/SDK controlled-I/O scenarios, two startup
guards and 423 provider-free regression checks passed. See
`docs/evaluation/local-s2s/phase-02-image-build-20261016.md` for exact evidence and
limitations, including the unused CUDA-tagged upstream TTS wheel. Earlier missing
build/native-import statements below are historical. Do not start paid engine
initialization as a health check; real NLTK/VAD resources and full-engine tests
remain prerequisites. No operational provider or voice tuning changed.
Latest Linux preparation: Phase 1 OpenAI preservation acceptance is recorded in
`docs/evaluation/local-s2s/phase-01-linux-preparation.md`. A full **134-package**
Python 3.11/Linux CPU hash lock and wheel-only dry run are now available; see
`docs/evaluation/local-s2s/phase-02-dependency-lock.md` and the adjacent
`requirements-linux-cpu.in`, `cpu-constraints.txt`, `requirements-linux-cpu.lock`.
This supersedes the older missing-lock/base/source statements below. Engine
build/import/conformance/live acceptance remain open. Use the report's verified
trixie amd64 base digest, not the earlier Windows digest. The CPU constraints pin
two exact official wheel URLs; other packages resolve only from PyPI.
For a fresh build workspace, run the existing preparation helper with the report's
base digest; compare its generated `requirements.in` with
`requirements-linux-cpu.in`, then copy the reviewed `requirements-linux-cpu.lock`
to `.local-s2s-build/requirements.lock`. Preserve an existing prepared workspace;
do not overwrite it or re-resolve silently during a build. Actual image build and
provider startup are not authorized by dependency resolution alone.
From the repository root:
```powershell
+10 -1
View File
@@ -14,6 +14,10 @@ LIMITS = {'/v1/audio/transcriptions': (1100000, 65536),
'/v1/audio/speech': (16384, 1440000)}
class EvaluationBudgetExhausted(ValueError):
"""Evaluation admission refused before any provider request."""
class ComponentServer:
def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None):
if not key or not key.isascii() or any(c.isspace() for c in key):
@@ -48,11 +52,13 @@ class ComponentServer:
await self.stopping.wait()
finally:
server.close()
await server.wait_closed()
tasks = list(self.requests)
for task, writer in list(self.requests.items()):
writer.close()
task.cancel()
# Newer Python also waits for accepted clients here. Close/cancel
# those owners first so waiting cannot defer provider cancellation.
await server.wait_closed()
if tasks:
await asyncio.wait(tasks, timeout=1)
self.counts['shutdown_pending'] = sum(not t.done() for t in tasks)
@@ -194,6 +200,9 @@ class ComponentServer:
forwarding.result()
else:
self.counts['disconnected'] += 1
except EvaluationBudgetExhausted:
self.counts['budget_rejected'] += 1
await self._error(writer, 429)
except TimeoutError:
self.counts['expired'] += 1
except asyncio.CancelledError:
+3
View File
@@ -0,0 +1,3 @@
# Exact Python 3.11 Linux x86_64 CPU wheels, from the official PyTorch index.
torch @ https://download-r2.pytorch.org/whl/cpu/torch-2.11.0%2Bcpu-cp311-cp311-manylinux_2_28_x86_64.whl#sha256=8a56a8c95531ef0e454510ba8bbd9d11dc7a9000337265210b10f6bfeacdd485
torchaudio @ https://download-r2.pytorch.org/whl/cpu/torchaudio-2.11.0%2Bcpu-cp311-cp311-manylinux_2_28_x86_64.whl#sha256=2ddcb49458aa9783121222c535c0eb9cd54445ec44bb8dd22c9e52cdb730dbc2
+13 -1
View File
@@ -13,6 +13,7 @@ def build_runtime(config, stop):
from speech_to_speech.config import load_config, resolve_config
from speech_to_speech.configured_runtime import build_configured_server
from speech_to_speech.api.openai_realtime.handlers.session import SessionHandler
from speech_to_speech.pipeline.language_detection import warm_language_detector
import speech_to_speech.s2s_pipeline as pipeline
import speech_to_speech.LLM.base_openai_compatible_language_model as base_llm
import speech_to_speech.api.openai_realtime.server as server_module
@@ -25,10 +26,21 @@ def build_runtime(config, stop):
kwargs['source'] = 'local'
return native_load(str(source), *args, **kwargs)
torch.hub.load = local_vad
pipeline.Queue = lambda *args, **kwargs: FailClosedQueue(stop)
class PipelineQueue(FailClosedQueue):
# Upstream uses Queue both as a constructor and in Queue[Any] annotations.
def __init__(self, *args, **kwargs):
super().__init__(stop)
pipeline.Queue = PipelineQueue
# Base setup invokes warmup from inside construction; install before it runs.
install_client_policy(base_llm, config)
# The pinned output processor also detects language for fixed session configs.
# Its first lazy Lingua preload can hold the GIL beyond the media send deadline.
# Prime the same cache before exposing the listener, within the startup budget.
warm_language_detector()
resolved = resolve_config(load_config(Path(__file__).with_name('pipeline.yaml')), names=['local'])
if config.local_s2s_retain_interrupted_answers:
from services.local_s2s.history import install_retained_history
install_retained_history()
runtime = build_configured_server(resolved, stop)
try:
units = runtime.server.pool
+106
View File
@@ -0,0 +1,106 @@
"""Offline paired scorecard. Reads observations; never calls or switches a provider."""
import argparse
from collections import Counter
from decimal import Decimal, InvalidOperation
import json
import math
from pathlib import Path
PROVIDERS = ('openai', 'local_s2s')
def number(value):
if isinstance(value, bool):
raise ValueError('Boolean is not a measurement')
try:
result = Decimal(str(value))
except InvalidOperation:
raise ValueError('Invalid measurement') from None
if not result.is_finite() or result < 0:
raise ValueError('Measurements must be finite and nonnegative')
return result
def p95(values):
return sorted(values)[math.ceil(.95 * len(values)) - 1] if values else None
def scorecard(data):
samples, charges = data['samples'], data['charges']
if len(samples) > 10000 or len(charges) > 10000:
raise ValueError('Evaluation input bound exceeded')
blockers, results, ids = [], {}, set()
for sample in samples:
if sample['provider'] not in PROVIDERS or not isinstance(sample['case_id'], str) or not sample['case_id']:
raise ValueError('Invalid paired case identity')
for flag in ('success', 'critical_error', 'persistent_underrun', 'duplicate', 'disconnected'):
if type(sample[flag]) is not bool:
raise ValueError('Observation flags must be boolean')
for field in ('first_audible_ms', 'tool_ms', 'interruption_stop_ms'):
if sample.get(field) is not None:
number(sample[field])
if sample['success'] and sample.get('first_audible_ms') is None:
raise ValueError('Successful sample needs audible latency')
for charge in charges:
if charge['provider'] not in PROVIDERS or charge['kind'] not in ('startup', 'request', 'failed', 'abandoned', 'session'):
raise ValueError('Invalid charge classification')
if not isinstance(charge['id'], str) or not charge['id'] or charge['id'] in ids:
raise ValueError('Charge identity missing or duplicated')
ids.add(charge['id'])
if charge['cost_usd'] is not None:
number(charge['cost_usd'])
counts = {}
minimum = data.get('minimum_samples_per_provider')
if type(minimum) is not int or minimum < 1:
blockers.append('sample_threshold_not_set')
for provider in PROVIDERS:
rows = [r for r in samples if r['provider'] == provider]
counts[provider] = Counter(r['case_id'] for r in rows)
costs = [r for r in charges if r['provider'] == provider]
complete = bool(costs) and data.get('billing_complete', {}).get(provider) is True and all(r['cost_usd'] is not None for r in costs)
total = sum((number(r['cost_usd']) for r in costs), Decimal(0)) if complete else None
successes = sum(r['success'] for r in rows)
results[provider] = dict(samples=len(rows), successful_tasks=successes,
p95_first_audible_ms=p95([float(number(r['first_audible_ms'])) for r in rows if r['success']]),
p95_tool_ms=p95([float(number(r['tool_ms'])) for r in rows if r.get('tool_ms') is not None]),
p95_interruption_stop_ms=p95([float(number(r['interruption_stop_ms'])) for r in rows if r.get('interruption_stop_ms') is not None]),
total_cost_usd=str(total) if total is not None else None,
cost_per_success_usd=str(total / successes) if total is not None and successes else None)
if not rows or (type(minimum) is int and len(rows) < minimum):blockers.append(provider + ':insufficient_samples')
if not complete:blockers.append(provider + ':billing_incomplete')
if any(not r['success'] or r['critical_error'] or r['persistent_underrun'] or r['duplicate'] or r['disconnected'] for r in rows):
blockers.append(provider + ':task_or_quality_failure')
if counts['openai'] != counts['local_s2s']:blockers.append('cases_not_paired')
base, local = results['openai'], results['local_s2s']
if base['p95_first_audible_ms'] is not None and local['p95_first_audible_ms'] is not None:
if local['p95_first_audible_ms'] > base['p95_first_audible_ms'] + 1000:blockers.append('latency_target_failed')
if base['cost_per_success_usd'] is not None and local['cost_per_success_usd'] is not None:
if number(base['cost_per_success_usd']) == 0:blockers.append('baseline_cost_not_positive')
if number(local['cost_per_success_usd']) > number(base['cost_per_success_usd']) * Decimal('.70'):
blockers.append('cost_target_failed')
for gate in ('thresholds_accepted', 'real_provider_observations', 'human_quality_accepted', 'rollback_verified'):
if data.get(gate) is not True:blockers.append(gate + ':pending')
profiles = data.get('profile_sha256', {})
if any(not isinstance(profiles.get(p), str) or len(profiles[p]) != 64 or any(c not in '0123456789abcdef' for c in profiles[p]) for p in PROVIDERS):
blockers.append('profile_identity_missing')
return dict(status='criteria_met' if not blockers else 'not_accepted', providers=results,
blockers=blockers, thresholds=dict(latency_delta_ms=1000,cost_ratio='.70',minimum_samples_per_provider=minimum),
percentile_method='nearest-rank', cost_method='sum_all_supplied_charges_including_startup_failure_abandoned',
authorization_to_switch=False)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--input', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
if args.input.stat().st_size > 10 * 1024 * 1024:
parser.error('Evaluation input exceeds 10MiB')
result = scorecard(json.loads(args.input.read_text()))
with args.output.open('x') as output:
json.dump(result, output, ensure_ascii=False, indent=2, allow_nan=False)
output.write('\n')
if __name__ == '__main__':
main()
+4
View File
@@ -63,6 +63,10 @@ def install_session_proof(handler_class, service_components, session_template):
return [project(a, b) for a, b in zip(value, shape)]
return value
session = project(actual, session_template)
from app.modules.voice.local_s2s import RETENTION_INSTRUCTIONS as INSTRUCTIONS
if (session.get('instructions', '').endswith(INSTRUCTIONS)
and not getattr(self._service, '_rag_retention_enabled', False)):
raise ValueError('LOCAL_ENGINE_RETENTION_EXTENSION_MISSING')
components = service_components[id(self._service)]
identity = effective_identity(components, session)
return result.model_copy(update={'session': result.session.model_copy(update={'s2s_effective': identity})})
+192
View File
@@ -0,0 +1,192 @@
"""Retain interrupted text as explicitly unheard draft history, never as delivery.
This extension does not estimate a heard prefix or claim native truncation. Raw
answers remain available in the session; evidence reuse stays backend-owned.
"""
from copy import deepcopy
from dataclasses import dataclass, field
from uuid import uuid4
from app.modules.voice.local_s2s import RETENTION_POLICY as POLICY, DRAFT_MARKER as MARKER
@dataclass
class RetainedHistory:
records: dict = field(default_factory=dict)
receipts: dict = field(default_factory=dict)
revision: int = 0
backend_session: str | None = None
def remember(self, response_id, items, wire_ids, anchor):
if not items or not wire_ids:
return
if response_id in self.records:
raise ValueError('Duplicate retained response')
if len(self.records) >= 64:
raise ValueError('Retained response capacity')
size = sum(len(str(part.text or '').encode()) for item in items for part in item.content)
occupied = sum(row['bytes'] for row in self.records.values())
if size > 131072 or occupied + size > 524288:
raise ValueError('Retained text capacity')
self.records[response_id] = dict(items=deepcopy(items), wire_ids=set(wire_ids),
anchor=anchor, bytes=size, applied=False)
def _annotate_locked(self, chat, record):
ids = {item.id for item in record['items']} | record['wire_ids']
for wire_id in record['wire_ids']:
ids |= chat._assistant_item_aliases.get(wire_id, set())
existing = [item for item in chat.buffer if item.id in ids]
if any(getattr(item, 'role', None) != 'assistant' for item in existing):
raise ValueError('Retained assistant ownership mismatch')
if record['applied']:
if not existing or any(not (part.text or '').startswith(MARKER)
for item in existing for part in item.content):
raise ValueError('Retained history annotation lost')
return
targets = existing or deepcopy(record['items'])
if not existing and (record['anchor'] is None or record['anchor'] not in {item.id for item in chat.buffer}):
raise ValueError('Retained draft anchor evicted')
for item in targets:
item.content = [part.model_copy(update={'text':
MARKER + '\nNot fully heard; saved for possible repetition.\n' + (part.text or '')})
for part in item.content]
if not existing:
# Cancellation rolls provisional output back upstream. Restore its
# saved text at the original turn, explicitly as a draft.
anchor = record['anchor']
for item in targets:
chat._add_item_locked(item, insert_at=chat._turn_insertion_index_locked(anchor))
anchor = item.id
record['applied'] = True
def apply(self, chat, request, native_session):
required = {'type','event_id','session_id','engine_session_id','generation',
'response_id','item_id','content_index','audio_end_ms'}
if (set(request) != required or request['type'] != 's2s.history.retain'
or request['engine_session_id'] != native_session
or any(not isinstance(request[k], str) or not request[k] or len(request[k]) > 200
for k in ('event_id','session_id','response_id','item_id'))
or type(request['generation']) is not int or request['generation'] < 0
or type(request['content_index']) is not int or request['content_index'] != 0
or type(request['audio_end_ms']) is not int or request['audio_end_ms'] < 0):
raise ValueError('Invalid retained history request')
if self.backend_session not in (None, request['session_id']):
raise ValueError('Retained history session mismatch')
previous = self.receipts.get(request['event_id'])
if previous:
if previous[0] != request:
raise ValueError('Conflicting retained history replay')
return deepcopy(previous[1])
if len(self.receipts) >= 128:
raise ValueError('Retained receipt capacity')
record = self.records.get(request['response_id'])
if record is None or request['item_id'] not in record['wire_ids']:
raise ValueError('Unknown retained response item')
# Native generation has already stopped. Mutate the same Chat object
# subsequently copied by the real LLM handler, under its existing lock.
with chat._lock:
self._annotate_locked(chat, record)
self.revision += 1
receipt = dict(request, type='s2s.history.retained',
event_id='retain_'+uuid4().hex, operation_id=request['event_id'],
history_revision=self.revision, policy=POLICY, applied=True)
self.backend_session = request['session_id']
self.receipts[request['event_id']] = (deepcopy(request), deepcopy(receipt))
return receipt
def install_retained_history():
"""Narrow hooks for the audited pinned engine; no source checkout mutation."""
from speech_to_speech.api.openai_realtime.handlers.response import ResponseHandler
from speech_to_speech.api.openai_realtime.service import RealtimeService
import speech_to_speech.api.openai_realtime.websocket_router as router
if getattr(RealtimeService, '_rag_retention_enabled', False):
raise ValueError('Retained history extension already installed')
original_finish, original_dispatch = ResponseHandler.finish_response, router._dispatch_client_event
original_unregister = RealtimeService.unregister
stores, anchors = {}, {}
def finish(self, conn_id, *args, **kwargs):
st = self._state(conn_id)
response_id = st.current_response_id
chat = st.runtime_config.chat
with chat._lock:
tracked = chat._provisional_generations.get(st.current_response_key, (set(),set()))[0]
items = deepcopy([item for item in chat.buffer if item.id in tracked
and getattr(item, 'role', None) == 'assistant'])
anchor = None
for item in chat.buffer:
if item.id in tracked:
break
anchor = item.id
if not items:
anchor = st.input_item_by_turn_revision.get((st.current_response_turn_id, st.current_response_turn_revision))
if anchor is None:
anchor = anchors.get((id(self._service),conn_id))
events = original_finish(self, conn_id, *args, **kwargs)
for event in events:
if event.type != 'response.done':
continue
output = event.response.output or []
wire_ids = [item.id for item in output if getattr(item, 'role', None) == 'assistant']
if not items and wire_ids and anchor is not None:
from speech_to_speech.LLM.chat import make_assistant_message
for output_item in output:
if getattr(output_item, 'role', None) == 'assistant':
text = ''.join(getattr(part, 'transcript', None) or getattr(part, 'text', None) or ''
for part in output_item.content)
if text:
saved = make_assistant_message(text)
saved.id = output_item.id
items.append(saved)
# No audio/text item means no retained-answer receipt is needed.
if items and wire_ids:
store=stores.setdefault((id(self._service),conn_id), RetainedHistory())
store.remember(response_id, items, wire_ids, anchor)
if event.response.status == 'cancelled':
# Preserve ahead-of-playback text even when every emitted
# audio sample was already consumed and no truncate follows.
with chat._lock:
store._annotate_locked(chat, store.records[response_id])
return events
async def dispatch(unit, session_id, raw, transport, **kwargs):
service = unit.service
if raw.get('type') == 's2s.history.retain':
try:
st = service._state(session_id)
if st.in_response or st.response_pending:
raise ValueError('Generation is not stopped')
store = stores.get((id(service),session_id))
if store is None:
raise ValueError('No retained history')
receipt = store.apply(st.runtime_config.chat, raw, st.session_id)
async with transport._send_lock:
await transport.websocket.send_json(receipt)
except (ValueError, KeyError, TypeError, AttributeError):
error = service.make_error('Retained history synchronization failed', 's2s_history_failed')
error.error.event_id = raw.get('event_id')
await transport.send_events([error])
return
if raw.get('type') == 'response.cancel':
st = service._state(session_id)
if not st.in_response or raw.get('response_id') != st.current_response_id:
error = service.make_error('Cancellation identity mismatch', 's2s_history_failed')
error.error.event_id = raw.get('event_id')
await transport.send_events([error])
return
if raw.get('type') == 'response.create':
anchors[(id(service),session_id)] = service._state(session_id).runtime_config.chat.history_anchor_id()
await original_dispatch(unit, session_id, raw, transport, **kwargs)
def unregister(self, conn_id):
try:
return original_unregister(self, conn_id)
finally:
stores.pop((id(self),conn_id), None)
anchors.pop((id(self),conn_id), None)
ResponseHandler.finish_response = finish
RealtimeService.unregister = unregister
RealtimeService._rag_retention_enabled = True
router._dispatch_client_event = dispatch
+3 -2
View File
@@ -36,11 +36,12 @@ def bounded_call(action, timeout):
def cleanup(runtime, guard, thread, stop, *, timeout=2, emit=print):
stop.set()
counters = {}
# Every operation is independent; a failed or wedged stop cannot skip I/O cleanup.
# Cancel owned provider I/O before joining workers which may be awaiting it.
# Every operation is independent; one failure cannot skip later cleanup.
for name, action in (
('runtime_stop', runtime.stop if runtime is not None else lambda: None),
('gateway_shutdown', guard.shutdown),
('gateway_close', guard.server_close),
('runtime_stop', runtime.stop if runtime is not None else lambda: None),
('gateway_join', lambda: thread.join(timeout)),
):
counters[name] = bounded_call(action, timeout)
@@ -0,0 +1,59 @@
Pillow>=12.2,<13
PyMuPDF>=1.26,<2
PyYAML>=6,<7
SQLAlchemy>=2.0.36,<2.1
alembic>=1.14,<2
anyio>=4.0,<5
argon2-cffi>=23.1,<26
defusedxml>=0.7.1,<1
espeakng-loader>=0.2.4; platform_system == 'Darwin'
fastapi>=0.115,<1
fastapi>=0.115.0
faster-qwen3-tts>=0.5.4; platform_system == 'Windows'
faster-qwen3-tts[ggml]>=0.5.4; platform_system != 'Darwin' and platform_system != 'Windows'
httpx>=0.27,<1
httpx>=0.28.0
huggingface-hub>=0.34.0
jsonschema>=4.0
langchain-core>=1,<2
librosa==0.11.0
lingua-language-detector>=2.0.2
miniaudio==1.61; platform_system == 'Darwin'
misaki>=0.9.4; platform_system == 'Darwin'
mlx-audio==0.4.7; platform_system == 'Darwin'
mlx-lm==0.31.3; platform_system == 'Darwin'
mlx-metal==0.32.3; platform_system == 'Darwin'
mlx==0.32.3; platform_system == 'Darwin'
nano-parakeet>=0.2.0; platform_system != 'Darwin'
nltk==3.10.3
numpy>=1.26.0,<2.4.4; platform_system == 'Darwin'
numpy>=1.26.0; platform_system != 'Darwin'
onnxruntime>=1.17.0
openai==2.28.0
pgvector>=0.3.6,<1
phonemizer-fork>=3.3.2; platform_system == 'Darwin'
pillow>=10.0.0
psycopg[binary]>=3.2.3,<4
pydantic-settings>=2.7,<3
pydantic>=2.0
python-multipart>=0.0.20,<0.1
rich>=13.0
scipy>=1.10.0
setuptools>=77.0.3
sounddevice==0.5.3; platform_system == 'Darwin'
sounddevice>=0.5.0; platform_system != 'Darwin'
soundfile>=0.13.0; platform_system == 'Darwin'
soxr>=0.3.2
spacy>=3.8.4; platform_system == 'Darwin'
tiktoken>=0.8,<1
torch==2.11.0; platform_system == 'Darwin'
torch>=2.4.0; platform_system != 'Darwin'
torchaudio==2.11.0; platform_system == 'Darwin'
torchaudio>=2.4.0; platform_system != 'Darwin'
transformers==5.18.0; platform_system == 'Darwin'
transformers>=5.18.0,<6; platform_system != 'Darwin'
uvicorn>=0.30.0
uvicorn>=0.34,<1
websockets>=12.0
websockets>=15,<18
wheel
File diff suppressed because it is too large Load Diff