feat(voice): add isolated Local S2S v3 candidate and acceptance evidence
Extract the provider boundary while retaining OpenAI/Gemini contracts. Add an opt-in isolated Local S2S adapter, pinned engine extension, bounded component gateway and frozen effective configuration profiles. Enforce request token limits, zero retries, local asset validation, connection deadlines, disconnect ownership, bounded cleanup and signals. Include regression coverage, pinned source fixtures, operator guidance, asset fingerprints and guarded disposable PostgreSQL acceptance tooling. Preserve immutable fixture bytes across Git line-ending conversion. Validation recorded in the reports: - 74 repair, 107 combined and 242 preservation checks passed. - Fresh PostgreSQL local checks: 2 passed. - Expanded PostgreSQL: 57 passed, 6 documented baseline failures. - Compose configurations, staged whitespace and fixture hashes passed. Phase 1 live listening and Phase 2 complete engine/SDK/POSIX, real component audio and Persian browser acceptance remain pending. No operational switch, paid call, model download or Phase 3 implementation is included.
This commit is contained in:
@@ -102,6 +102,9 @@ def create_voice_session(req: CreateLiveSessionRequest, response: Response,
|
||||
response.status_code = 201 if result['status'] == 'connected' else 202
|
||||
response.headers['Idempotency-Replayed'] = 'true'
|
||||
return result
|
||||
if config.provider == 'local_s2s':
|
||||
from app.modules.voice.local_s2s import require_isolated_candidate
|
||||
require_isolated_candidate(config, IngestionSettings(), database_url=engine.url)
|
||||
cutoff = capability(config)
|
||||
profile = config.profile()
|
||||
# Construct configured embedding transport only after replay recovery.
|
||||
@@ -166,6 +169,9 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
try:
|
||||
user = await blocking(auth_service.get_current_user, websocket.cookies.get(COOKIE_NAME))
|
||||
info = await blocking(lifecycle_service.validate_stream, user, session_id, initial=True)
|
||||
if config.provider == 'local_s2s':
|
||||
from app.modules.voice.local_s2s import require_isolated_candidate
|
||||
require_isolated_candidate(config, search_service.settings, database_url=engine.url)
|
||||
config.require_voice()
|
||||
if search_service.cutoff is None and not config.voice_transport_testing:
|
||||
raise ValueError('CALIBRATION_REQUIRED')
|
||||
|
||||
@@ -15,7 +15,8 @@ from uuid import uuid4
|
||||
from app.modules.knowledge.service import SearchInput
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from app.modules.voice.serialization import bounded_json
|
||||
from app.infrastructure.realtime import POLICY, strict_json, ProviderProtocolError
|
||||
from app.infrastructure.realtime import POLICY
|
||||
from app.modules.voice.provider import strict_json, ProviderProtocolError
|
||||
|
||||
class GeminiContextError(ProviderProtocolError):
|
||||
context_sync = True
|
||||
@@ -102,6 +103,21 @@ class GeminiLiveAdapter:
|
||||
self._sent_samples = 0
|
||||
self._resampler = PCM24To16()
|
||||
|
||||
def cancellation_request(self, response_id, operation_id=None):
|
||||
event = dict(type="response.cancel", response_id=response_id)
|
||||
if operation_id is not None:
|
||||
event["event_id"] = operation_id
|
||||
return event
|
||||
|
||||
def history_repair_request(self, repair):
|
||||
# Preserve the existing send-path failure and its bounded cleanup.
|
||||
return dict(type="conversation.item.truncate", event_id=repair.operation_id,
|
||||
item_id=repair.item_id, content_index=repair.content_index,
|
||||
audio_end_ms=repair.played_ms)
|
||||
|
||||
def confirm_history_repair(self, repair, event):
|
||||
raise GeminiContextError('Gemini context cannot be safely truncated')
|
||||
|
||||
def setup(self):
|
||||
return dict(type='session.update', session={'provider':'gemini'})
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Pinned local engine GA transport; no invented native input/history receipts."""
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from app.modules.voice.provider import ProviderProtocolError
|
||||
from app.modules.voice.local_s2s import setup_session, effective_identity
|
||||
|
||||
|
||||
class LocalS2SContextError(ProviderProtocolError):
|
||||
context_sync = True
|
||||
|
||||
|
||||
class LocalS2SAdapter(RealtimeAdapter):
|
||||
def __init__(self, transport, *, config, settings):
|
||||
# The local text model is not an OpenAI Realtime model. Keep its config
|
||||
# independent of OpenAI reasoning/transcription settings.
|
||||
self.transport, self.config, self.settings = transport, config, settings
|
||||
self.model, self.voice = config.selected_model, config.selected_voice
|
||||
self._setup = setup_session(config)
|
||||
self._identity = effective_identity(config.components(), self._setup)
|
||||
self._confirmed = False
|
||||
|
||||
def setup(self):
|
||||
from copy import deepcopy
|
||||
return dict(type='session.update', session=deepcopy(self._setup))
|
||||
|
||||
def acknowledged(self, session):
|
||||
# A session echo cannot certify a fixed global engine's real components.
|
||||
# The versioned engine extension derives this from initialized handlers.
|
||||
if not isinstance(session, dict) or session.get('s2s_effective') != self._identity:
|
||||
return False
|
||||
def matches(actual, expected):
|
||||
if isinstance(expected, dict):
|
||||
return isinstance(actual, dict) and all(k in actual and matches(actual[k], v) for k, v in expected.items())
|
||||
if isinstance(expected, list):
|
||||
return isinstance(actual, list) and len(actual) == len(expected) and all(matches(a, b) for a, b in zip(actual, expected))
|
||||
return type(actual) is type(expected) and actual == expected
|
||||
self._confirmed = matches(session, self._setup)
|
||||
return self._confirmed
|
||||
|
||||
def token_limited(self, response):
|
||||
# No unverified local terminal signature is accepted as a successful answer.
|
||||
return False
|
||||
|
||||
def is_no_active(self, error):
|
||||
return False
|
||||
|
||||
def confirm_history_repair(self, repair, event):
|
||||
raise LocalS2SContextError('Local history repair is not available in Phase 2')
|
||||
|
||||
async def send_serialized(self, wire):
|
||||
from app.modules.voice.provider import strict_json
|
||||
event = strict_json(wire)
|
||||
if event.get('type') in ('response.cancel', 'conversation.item.truncate'):
|
||||
raise LocalS2SContextError('Local interruption requires Phase 3 history repair')
|
||||
await self.transport.send(wire)
|
||||
|
||||
|
||||
async def connect_local(config, limits):
|
||||
from websockets.asyncio.client import connect
|
||||
token = config.local_s2s_token.get_secret_value()
|
||||
return await connect(config.local_s2s_endpoint,
|
||||
additional_headers={'Authorization': 'Bearer ' + token} if token else {},
|
||||
proxy=None, compression=None, max_size=limits.max_provider_message_bytes, max_queue=16,
|
||||
open_timeout=limits.connect_timeout_seconds, close_timeout=limits.send_timeout_seconds,
|
||||
ping_interval=20, ping_timeout=20)
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Private OpenAI Realtime wire adapter; no application/provider IDs cross to clients."""
|
||||
import json
|
||||
from urllib.parse import quote
|
||||
|
||||
from app.modules.knowledge.service import SearchInput
|
||||
@@ -8,8 +7,9 @@ from app.modules.voice.configuration import OpenAIInputSettings
|
||||
from app.modules.voice.serialization import bounded_json
|
||||
from app.modules.voice.openai_style import effective_instructions
|
||||
|
||||
class ProviderProtocolError(ValueError):
|
||||
pass
|
||||
from app.modules.voice.provider import (
|
||||
ProviderProtocolError, canonical_json, strict_json, HistoryRepair, HistoryRepairReceipt,
|
||||
)
|
||||
|
||||
POLICY = """You are the official voice assistant for «شرکت شهرکهای صنعتی اصفهان».
|
||||
Your scope is strictly limited to answering questions regarding «شرکت شهرکهای صنعتی اصفهان», including its regulations, industrial parks in Isfahan province, land allocations, contracts, permits, circulars, and official procedures.
|
||||
@@ -52,21 +52,6 @@ When calling search_knowledge:
|
||||
- Preserve the user's explicitly stated place names, person names, document titles and identifiers in query. Shortening the question must not replace them with different entities. If a name is unclear, ask for clarification rather than guessing.
|
||||
- Set 'context' to null. Never write explanations or user intent in 'context'."""
|
||||
|
||||
def canonical_json(value):
|
||||
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
||||
separators=(",", ":"), sort_keys=True)
|
||||
|
||||
def strict_json(raw):
|
||||
def pairs(items):
|
||||
value = {}
|
||||
for key, item in items:
|
||||
if key in value:
|
||||
raise ValueError("Duplicate JSON key")
|
||||
value[key] = item
|
||||
return value
|
||||
return json.loads(raw, object_pairs_hook=pairs,
|
||||
parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Nonfinite JSON")))
|
||||
|
||||
class RealtimeAdapter:
|
||||
# Argument-done can precede a cut-off tool call: wait for terminal success.
|
||||
defer_tool_execution = True
|
||||
@@ -146,6 +131,30 @@ class RealtimeAdapter:
|
||||
for key in empty_defaults
|
||||
if key not in expected['audio']['input']['transcription'])
|
||||
|
||||
def cancellation_request(self, response_id, operation_id=None):
|
||||
event = dict(type="response.cancel", response_id=response_id)
|
||||
if operation_id is not None:
|
||||
event["event_id"] = operation_id
|
||||
return event
|
||||
|
||||
def history_repair_request(self, repair: HistoryRepair):
|
||||
return dict(type="conversation.item.truncate", event_id=repair.operation_id,
|
||||
item_id=repair.item_id, content_index=repair.content_index,
|
||||
audio_end_ms=repair.played_ms)
|
||||
|
||||
def confirm_history_repair(self, repair: HistoryRepair, event):
|
||||
# Native OpenAI ack has no request event_id/response_id. Runtime first
|
||||
# matches exactly one dispatched item/part in this session; never invent
|
||||
# additional upstream confirmation or infer a heard transcript prefix.
|
||||
if (event.get("type") != "conversation.item.truncated"
|
||||
or event.get("item_id") != repair.item_id
|
||||
or type(event.get("content_index")) is not int
|
||||
or event["content_index"] != repair.content_index
|
||||
or type(event.get("audio_end_ms")) is not int
|
||||
or event["audio_end_ms"] != repair.played_ms):
|
||||
raise ProviderProtocolError("History repair acknowledgement mismatch")
|
||||
return HistoryRepairReceipt(repair, event.get("event_id"), "openai.item_truncated")
|
||||
|
||||
def interrupted_tool_output(self, call_id):
|
||||
# Resolve abandoned private tool calls without publishing stale evidence.
|
||||
return dict(type="conversation.item.create", item=dict(
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
"""Selected voice transport construction shared by the API and operator smoke."""
|
||||
import asyncio
|
||||
from app.modules.voice.provider import VoiceProvider
|
||||
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
|
||||
from app.infrastructure.realtime import RealtimeAdapter, connect as connect_openai
|
||||
|
||||
|
||||
async def create_adapter(config, limits):
|
||||
async def create_adapter(config, limits) -> VoiceProvider:
|
||||
config.require_voice()
|
||||
if config.provider == 'local_s2s':
|
||||
from app.infrastructure.local_s2s import LocalS2SAdapter, connect_local
|
||||
if limits.output_capacity_profile != 'standard':
|
||||
raise ValueError('OpenAI output capacity cannot be used for local S2S')
|
||||
transport = await asyncio.wait_for(connect_local(config, limits), limits.connect_timeout_seconds)
|
||||
try:
|
||||
return LocalS2SAdapter(transport, config=config, settings=limits)
|
||||
except BaseException:
|
||||
await asyncio.wait_for(transport.close(), limits.send_timeout_seconds)
|
||||
raise
|
||||
if config.provider == 'gemini' and limits.output_capacity_profile != 'standard':
|
||||
raise ValueError('OpenAI output capacity cannot be used for Gemini')
|
||||
input_settings = None
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Explicit offline stage demonstration or bounded opt-in OpenRouter smoke.
|
||||
|
||||
Default stub output is a labelled test tone, never evidence of Persian speech.
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import base64
|
||||
from io import BytesIO
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import wave
|
||||
|
||||
import httpx
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app.modules.voice.provider import strict_json
|
||||
|
||||
MAX_PCM = 480000 # 10 seconds at 24 kHz, also bounds saved evaluation audio.
|
||||
|
||||
|
||||
def wav_bytes(pcm):
|
||||
output = BytesIO()
|
||||
with wave.open(output, 'wb') as audio:
|
||||
audio.setnchannels(1)
|
||||
audio.setsampwidth(2)
|
||||
audio.setframerate(24000)
|
||||
audio.writeframes(pcm)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def tone():
|
||||
return b''.join(struct.pack('<h', round(1800 * math.sin(2 * math.pi * 440 * i / 24000)))
|
||||
for i in range(9600))
|
||||
|
||||
|
||||
async def bounded_response(client, endpoint, *, max_bytes, **kwargs):
|
||||
async with asyncio.timeout(30):
|
||||
async with client.stream('POST', 'https://openrouter.ai/api/v1/' + endpoint, **kwargs) as response:
|
||||
if response.status_code != 200:
|
||||
raise ValueError('LOCAL_STAGE_HTTP_FAILURE')
|
||||
body = bytearray()
|
||||
async for part in response.aiter_bytes(8192):
|
||||
if len(body) + len(part) > max_bytes:
|
||||
raise ValueError('LOCAL_STAGE_RESPONSE_CAPACITY')
|
||||
body.extend(part)
|
||||
return bytes(body), response.headers.get('content-type', '').split(';')[0]
|
||||
|
||||
|
||||
async def stages(config, pcm, client, key, *, stt_format='multipart'):
|
||||
if not pcm or len(pcm) % 2 or len(pcm) > MAX_PCM:
|
||||
raise ValueError('LOCAL_STAGE_INPUT_CAPACITY')
|
||||
headers = {'Authorization': 'Bearer ' + key}
|
||||
audio = wav_bytes(pcm)
|
||||
if stt_format == 'multipart':
|
||||
payload = dict(files={'file': ('fixture.wav', audio, 'audio/wav')},
|
||||
data={'model': config.local_s2s_stt_model, 'language': 'fa', 'response_format': 'json'})
|
||||
elif stt_format == 'json':
|
||||
payload = dict(json=dict(model=config.local_s2s_stt_model, language='fa', response_format='json',
|
||||
input_audio=dict(data=base64.b64encode(audio).decode('ascii'), format='wav')))
|
||||
else:
|
||||
raise ValueError('LOCAL_STAGE_STT_FORMAT')
|
||||
raw, media = await bounded_response(client, 'audio/transcriptions', headers=headers, max_bytes=65536, **payload)
|
||||
if media != 'application/json':
|
||||
raise ValueError('LOCAL_STAGE_STT_FORMAT')
|
||||
text = strict_json(raw).get('text')
|
||||
if not isinstance(text, str) or not text.strip() or len(text) > 1024:
|
||||
raise ValueError('LOCAL_STAGE_STT_RESULT')
|
||||
raw, media = await bounded_response(client, 'chat/completions', headers=headers, max_bytes=65536,
|
||||
json=dict(model=config.local_s2s_llm_model, stream=False, max_tokens=128,
|
||||
messages=[dict(role='system', content='Reply briefly in Persian. A greeting only; no document claims.'),
|
||||
dict(role='user', content=text)]))
|
||||
if media != 'application/json':
|
||||
raise ValueError('LOCAL_STAGE_LLM_FORMAT')
|
||||
result = strict_json(raw)
|
||||
choices = result.get('choices')
|
||||
if not isinstance(choices, list) or len(choices) != 1 or choices[0].get('finish_reason') != 'stop':
|
||||
raise ValueError('LOCAL_STAGE_LLM_TERMINAL')
|
||||
answer = choices[0].get('message', {}).get('content')
|
||||
if not isinstance(answer, str) or not answer.strip() or len(answer) > 300:
|
||||
raise ValueError('LOCAL_STAGE_LLM_RESULT')
|
||||
raw, media = await bounded_response(client, 'audio/speech', headers=headers, max_bytes=MAX_PCM,
|
||||
json=dict(model=config.local_s2s_tts_model, voice=config.local_s2s_tts_voice,
|
||||
input=answer, response_format='pcm'))
|
||||
if media != 'audio/pcm' or not raw or len(raw) % 2:
|
||||
raise ValueError('LOCAL_STAGE_TTS_FORMAT')
|
||||
return raw
|
||||
|
||||
|
||||
def stub_response(request):
|
||||
if request.url.path.endswith('/audio/transcriptions'):
|
||||
return httpx.Response(200, json={'text': '\u0633\u0644\u0627\u0645'})
|
||||
if request.url.path.endswith('/chat/completions'):
|
||||
return httpx.Response(200, json={'choices': [{'finish_reason': 'stop', 'message': {'content': '\u0633\u0644\u0627\u0645'}}]})
|
||||
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=tone())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--live', action='store_true', help='Makes exactly 3 paid requests; no retries or startup probes.')
|
||||
parser.add_argument('--input', type=Path, help='Consented PCM16 mono 24k WAV, at most 10 seconds.')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--save-evaluation-audio', action='store_true', help='Consent to saving actual provider speech.')
|
||||
parser.add_argument('--stt-format', choices=['multipart', 'json'], default='multipart')
|
||||
args = parser.parse_args()
|
||||
if args.output.exists():
|
||||
parser.error('Output already exists; choose a new filename.')
|
||||
if args.live and (not args.input or not args.save_evaluation_audio):
|
||||
parser.error('--live requires consented --input and --save-evaluation-audio')
|
||||
if args.live:
|
||||
config = VoiceSettings(provider='local_s2s')
|
||||
if not all((config.local_s2s_stt_model, config.local_s2s_llm_model, config.local_s2s_tts_model, config.local_s2s_tts_voice)):
|
||||
parser.error('Explicit local model/voice settings are required.')
|
||||
key = os.environ.get('OPENROUTER_API_KEY', '')
|
||||
if not key:
|
||||
parser.error('OPENROUTER_API_KEY is required.')
|
||||
# Check size before reading/decompressing input.
|
||||
if args.input.stat().st_size > MAX_PCM + 4096:
|
||||
parser.error('Input is too large.')
|
||||
with wave.open(str(args.input), 'rb') as audio:
|
||||
if (audio.getnchannels(), audio.getsampwidth(), audio.getframerate(), audio.getcomptype()) != (1, 2, 24000, 'NONE'):
|
||||
parser.error('Expected mono PCM16 24kHz WAV.')
|
||||
pcm = audio.readframes(240001)
|
||||
transport = httpx.AsyncHTTPTransport(retries=0)
|
||||
else:
|
||||
config = VoiceSettings(_env_file=None, provider='local_s2s',
|
||||
local_s2s_stt_model='stub/stt', local_s2s_llm_model='stub/llm',
|
||||
local_s2s_tts_model='stub/tts', local_s2s_tts_voice='stub')
|
||||
key, pcm, transport = 'stub-only', tone(), httpx.MockTransport(stub_response)
|
||||
async def run():
|
||||
async with httpx.AsyncClient(transport=transport, timeout=30, follow_redirects=False) as client:
|
||||
async with asyncio.timeout(90):
|
||||
return await stages(config, pcm, client, key, stt_format=args.stt_format)
|
||||
try:
|
||||
output = asyncio.run(run())
|
||||
with args.output.open('xb') as target:
|
||||
target.write(wav_bytes(output))
|
||||
except (ValueError, KeyError, TypeError, OSError, httpx.HTTPError, TimeoutError):
|
||||
print(json.dumps(dict(status='failed', mode='live' if args.live else 'stub')))
|
||||
return 1
|
||||
print(json.dumps(dict(status='ok', mode='live' if args.live else 'stub-test-tone',
|
||||
requests=3, paid_requests=3 if args.live else 0,
|
||||
sample_rate=24000, samples=len(output)//2)))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -32,6 +32,10 @@ async def lifespan(app):
|
||||
engine = None
|
||||
startup_error = None
|
||||
try:
|
||||
from app.modules.voice.local_s2s import require_isolated_candidate
|
||||
candidate_config = dependencies.get_voice_settings()
|
||||
if candidate_config.provider == 'local_s2s':
|
||||
require_isolated_candidate(candidate_config, dependencies.get_ingestion_settings())
|
||||
engine = dependencies.get_engine()
|
||||
lifecycle = dependencies.get_lifecycle_service(engine)
|
||||
await blocking(dependencies.prepare_search_tools)
|
||||
|
||||
@@ -5,6 +5,7 @@ from typing import Literal
|
||||
from urllib.parse import urlsplit
|
||||
from pydantic import AliasChoices, BaseModel, Field, SecretStr, field_validator, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from app.modules.voice.local_s2s import LocalS2SSettings
|
||||
|
||||
|
||||
class OpenAIInputSettings(BaseModel):
|
||||
@@ -87,9 +88,9 @@ class OpenAIInputSettings(BaseModel):
|
||||
dict(type=self.openai_realtime_noise_reduction))
|
||||
|
||||
|
||||
class VoiceSettings(OpenAIInputSettings, BaseSettings):
|
||||
class VoiceSettings(LocalS2SSettings, OpenAIInputSettings, BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True)
|
||||
provider: Literal['gemini', 'openai'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
|
||||
provider: Literal['gemini', 'openai', 'local_s2s'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
|
||||
gemini_api_key: SecretStr = SecretStr('')
|
||||
gemini_model: str = Field(default='gemini-2.0-flash-exp', min_length=1, max_length=200)
|
||||
gemini_voice: str = Field(default='Aoede', min_length=1, max_length=80)
|
||||
@@ -184,26 +185,50 @@ class VoiceSettings(OpenAIInputSettings, BaseSettings):
|
||||
|
||||
@property
|
||||
def selected_model(self):
|
||||
if self.provider == 'local_s2s':
|
||||
return self.local_s2s_llm_model
|
||||
return self.gemini_model if self.provider == 'gemini' else self.openai_realtime_model
|
||||
|
||||
@property
|
||||
def selected_voice(self):
|
||||
if self.provider == 'local_s2s':
|
||||
return self.local_s2s_tts_voice
|
||||
return self.gemini_voice if self.provider == 'gemini' else self.openai_realtime_voice
|
||||
|
||||
@property
|
||||
def selected_proxy(self):
|
||||
if self.provider == 'local_s2s':
|
||||
return None
|
||||
return self.gemini_proxy if self.provider == 'gemini' else self.openai_realtime_proxy
|
||||
|
||||
@property
|
||||
def selected_key(self):
|
||||
if self.provider == 'local_s2s':
|
||||
return self.local_s2s_token
|
||||
return self.gemini_api_key if self.provider == 'gemini' else self.openai_realtime_api_key
|
||||
|
||||
def require_voice(self):
|
||||
if self.provider == 'local_s2s':
|
||||
if (not self.local_s2s_enabled or not self.voice_transport_testing
|
||||
or not all((self.local_s2s_stt_model, self.local_s2s_llm_model,
|
||||
self.local_s2s_tts_model, self.local_s2s_tts_voice))):
|
||||
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
|
||||
token = self.local_s2s_token.get_secret_value()
|
||||
if len(token) > 512 or (token and (not token.isascii() or any(c.isspace() for c in token))):
|
||||
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
|
||||
return
|
||||
key = self.selected_key.get_secret_value()
|
||||
if not key or len(key) > 512 or not key.isascii() or any(c.isspace() for c in key):
|
||||
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
|
||||
|
||||
def profile(self):
|
||||
if self.provider == 'local_s2s':
|
||||
from app.modules.voice.local_s2s import effective_identity, setup_session
|
||||
return dict(provider='local_s2s', model=self.selected_model, voice=self.selected_voice,
|
||||
input_sample_rate=24000, output_sample_rate=24000,
|
||||
evidence_policy_revision='same-session-evidence-retained-v5',
|
||||
development_only=True, interruption_policy='close_until_phase3',
|
||||
local_s2s=effective_identity(self.components(), setup_session(self)))
|
||||
profile = dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
|
||||
input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000,
|
||||
evidence_policy_revision='same-session-evidence-retained-v5')
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Frozen, credential-free identity for the development-only local engine."""
|
||||
from hashlib import sha256
|
||||
from urllib.parse import urlsplit
|
||||
from typing import Literal
|
||||
from pydantic import BaseModel, Field, SecretStr, field_validator
|
||||
from app.modules.voice.provider import canonical_json
|
||||
|
||||
UPSTREAM_REVISION = '619e3fe4f71d1c6f35c15870d588a3638de34722'
|
||||
CONTRACT_REVISION = 'rag-local-s2s-phase2-v1'
|
||||
PATCH_REVISION = 'rag-local-s2s-phase2-v3'
|
||||
|
||||
|
||||
class LocalS2SSettings(BaseModel):
|
||||
local_s2s_enabled: bool = False
|
||||
local_s2s_endpoint: str = 'ws://local-s2s-engine:8765/v1/realtime'
|
||||
local_s2s_token: SecretStr = SecretStr('')
|
||||
local_s2s_engine_revision: Literal[UPSTREAM_REVISION] = UPSTREAM_REVISION
|
||||
local_s2s_stt_model: str = Field(default='', max_length=200)
|
||||
local_s2s_llm_model: str = Field(default='', max_length=200)
|
||||
local_s2s_tts_model: str = Field(default='', max_length=200)
|
||||
local_s2s_tts_voice: str = Field(default='', max_length=80)
|
||||
local_s2s_language: Literal['fa'] = 'fa'
|
||||
local_s2s_max_output_tokens: int = Field(default=256, ge=1, le=1024)
|
||||
local_s2s_request_timeout_seconds: float = Field(default=30, gt=0, le=60, allow_inf_nan=False)
|
||||
|
||||
@field_validator('local_s2s_endpoint')
|
||||
@classmethod
|
||||
def endpoint(cls, value):
|
||||
try:
|
||||
p = urlsplit(value)
|
||||
p.port
|
||||
if (len(value) > 512 or p.scheme not in ('ws', 'wss') or not p.hostname
|
||||
or p.username or p.password or p.query or p.fragment or p.path != '/v1/realtime'):
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
raise ValueError('Invalid local engine endpoint') from None
|
||||
return value
|
||||
|
||||
@field_validator('local_s2s_stt_model', 'local_s2s_llm_model', 'local_s2s_tts_model', 'local_s2s_tts_voice')
|
||||
@classmethod
|
||||
def local_component_identifier(cls, value):
|
||||
if not value.isascii() or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/' for c in value):
|
||||
raise ValueError('Invalid local component identifier')
|
||||
return value
|
||||
|
||||
def components(self):
|
||||
return dict(stt=dict(backend='openai', model=self.local_s2s_stt_model,
|
||||
language='fa', response_format='json', final_only=True),
|
||||
llm=dict(backend='chat-completions', model=self.local_s2s_llm_model,
|
||||
max_output_tokens=self.local_s2s_max_output_tokens),
|
||||
tts=dict(backend='openai', model=self.local_s2s_tts_model,
|
||||
voice=self.local_s2s_tts_voice, response_format='pcm', sample_rate=24000),
|
||||
request_timeout_seconds=self.local_s2s_request_timeout_seconds)
|
||||
|
||||
|
||||
def setup_session(config):
|
||||
# Reuse the existing backend tool schema/policy; no second retrieval path.
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
session = RealtimeAdapter(None).setup()['session']
|
||||
session.pop('reasoning', None)
|
||||
session['model'] = config.local_s2s_llm_model
|
||||
session['max_output_tokens'] = config.local_s2s_max_output_tokens
|
||||
session['audio']['input']['transcription'] = dict(model=config.local_s2s_stt_model, language='fa')
|
||||
session['audio']['output']['voice'] = config.local_s2s_tts_voice
|
||||
session['audio']['output']['speed'] = 1.0
|
||||
return session
|
||||
|
||||
|
||||
def effective_identity(components, session):
|
||||
return dict(engine_revision=UPSTREAM_REVISION, patch_revision=PATCH_REVISION,
|
||||
contract_revision=CONTRACT_REVISION, components=components,
|
||||
effective_config_sha256=sha256(canonical_json(dict(components=components, session=session)).encode()).hexdigest())
|
||||
|
||||
|
||||
def require_isolated_candidate(config, ingestion, *, database_url=None):
|
||||
"""Run before startup reconciliation, never on the operational database."""
|
||||
from sqlalchemy.engine import make_url
|
||||
if config.provider != 'local_s2s':
|
||||
return
|
||||
config.require_voice()
|
||||
url = make_url(database_url if database_url is not None else ingestion.database_url.get_secret_value())
|
||||
if not url.database or not url.database.endswith('_local_s2s_test'):
|
||||
raise ValueError('Local S2S requires an isolated *_local_s2s_test database')
|
||||
for path in (ingestion.original_directory, ingestion.extraction_directory):
|
||||
if 'local-s2s-test' not in path.resolve().parts:
|
||||
raise ValueError('Local S2S requires dedicated local-s2s-test storage')
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Private provider port; browser events and runtime safety policy stay unchanged.
|
||||
|
||||
Events retain their admitted native identities and replay fingerprints. A terminal
|
||||
response proves generation stopped, never that unheard history was repaired.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from typing import Protocol
|
||||
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
|
||||
|
||||
class ProviderProtocolError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def canonical_json(value):
|
||||
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
||||
separators=(",", ":"), sort_keys=True)
|
||||
|
||||
|
||||
def strict_json(raw):
|
||||
def pairs(items):
|
||||
value = {}
|
||||
for key, item in items:
|
||||
if key in value:
|
||||
raise ValueError("Duplicate JSON key")
|
||||
value[key] = item
|
||||
return value
|
||||
return json.loads(raw, object_pairs_hook=pairs,
|
||||
parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Nonfinite JSON")))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HistoryRepair:
|
||||
"""Runtime-frozen correlation, after terminal and final playback coordinates."""
|
||||
session_id: str
|
||||
generation: int
|
||||
response_id: str
|
||||
operation_id: str
|
||||
item_id: str
|
||||
content_index: int
|
||||
played_ms: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HistoryRepairReceipt:
|
||||
repair: HistoryRepair
|
||||
# Native provenance, not an invented provider history revision. OpenAI's
|
||||
# truncate event supplies item/part/position, but no operation or revision.
|
||||
native_event_id: str | None
|
||||
provenance: str
|
||||
|
||||
|
||||
class VoiceProvider(Protocol):
|
||||
"""Required transport/setup/repair operations; no provider-name branching.
|
||||
|
||||
Native optional extensions (consumed/backlog/tool completion classification)
|
||||
remain adapter-owned. Runtime owns all authority, deadlines and release gates.
|
||||
"""
|
||||
settings: RuntimeSettings
|
||||
|
||||
def setup(self) -> dict: ...
|
||||
def acknowledged(self, session: dict) -> bool: ...
|
||||
def serialize(self, event: dict) -> str: ...
|
||||
async def send_serialized(self, wire: str) -> None: ...
|
||||
async def send(self, event: dict) -> None: ...
|
||||
async def receive(self) -> dict: ...
|
||||
def cancellation_request(self, response_id: str, operation_id: str | None = None) -> dict: ...
|
||||
def history_repair_request(self, repair: HistoryRepair) -> dict: ...
|
||||
def confirm_history_repair(self, repair: HistoryRepair, event: dict) -> HistoryRepairReceipt: ...
|
||||
def is_no_active(self, error: dict) -> bool: ...
|
||||
def abort(self) -> bool: ...
|
||||
async def close(self) -> None: ...
|
||||
@@ -13,7 +13,9 @@ from pydantic import ValidationError
|
||||
from app.modules.knowledge.evidence import SearchExecution
|
||||
from app.modules.knowledge.langchain_tool import ToolContext, create_search_tool
|
||||
from app.modules.knowledge.service import SearchInput, authority, transaction
|
||||
from app.infrastructure.realtime import canonical_json, strict_json, ProviderProtocolError
|
||||
from app.modules.voice.provider import (
|
||||
canonical_json, strict_json, ProviderProtocolError, VoiceProvider, HistoryRepair, HistoryRepairReceipt,
|
||||
)
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from app.modules.voice.diagnostics import diagnostic, protocol_reason, terminal_failure_reason, trace
|
||||
from app.modules.voice.serialization import bounded_json, json_size, bounded_json_digest
|
||||
@@ -133,6 +135,8 @@ class Audio:
|
||||
cleanup: str | None = None
|
||||
cleanup_deadline: float | None = None
|
||||
cleanup_dispatched: bool = False
|
||||
repair: HistoryRepair | None = None
|
||||
repair_receipt: HistoryRepairReceipt | None = None
|
||||
|
||||
@dataclass
|
||||
class Command:
|
||||
@@ -163,7 +167,7 @@ class VoiceRuntime:
|
||||
authority_check is a trusted async backend callback that captures/revalidates
|
||||
the session's persisted actor/epoch. It is never model input.
|
||||
"""
|
||||
def __init__(self, adapter, service, runner, user_id, emit, *,
|
||||
def __init__(self, adapter: VoiceProvider, service, runner, user_id, emit, *,
|
||||
authority_check=None, clock=time.monotonic, tool_seconds=None,
|
||||
session_id=None, max_calls=None, settings=None, close_client=None, tool_store=None):
|
||||
self.settings = settings or getattr(adapter, "settings", None) or RuntimeSettings()
|
||||
@@ -423,8 +427,7 @@ class VoiceRuntime:
|
||||
self.discard_pending_transcript(response)
|
||||
if not response.terminal and not response.cancel_event:
|
||||
response.cancel_event = identity()
|
||||
self.command(dict(type="response.cancel", response_id=response.id,
|
||||
event_id=response.cancel_event))
|
||||
self.command(self.adapter.cancellation_request(response.id, response.cancel_event))
|
||||
task = asyncio.create_task(self._finish_failure(writable))
|
||||
self.tasks.add(task)
|
||||
task.add_done_callback(self._failure_finished)
|
||||
@@ -970,8 +973,7 @@ class VoiceRuntime:
|
||||
audio.data.clear()
|
||||
if not response.terminal and not response.cancel_event:
|
||||
response.cancel_event = identity()
|
||||
self.command(dict(type="response.cancel", response_id=response.id,
|
||||
event_id=response.cancel_event))
|
||||
self.command(self.adapter.cancellation_request(response.id, response.cancel_event))
|
||||
if any(r.visible for r in affected):
|
||||
self.control(dict(type="turn_interrupted", turn_ref=old.ref,
|
||||
cancelled_tool_call_ids=[
|
||||
@@ -1109,8 +1111,9 @@ class VoiceRuntime:
|
||||
self.retire(audio)
|
||||
continue
|
||||
audio.cleanup = identity()
|
||||
self.command(dict(type="conversation.item.truncate", event_id=audio.cleanup,
|
||||
item_id=audio.item, content_index=audio.index, audio_end_ms=audio.played))
|
||||
audio.repair = HistoryRepair(self.session_id, response.turn.token,
|
||||
response.id, audio.cleanup, audio.item, audio.index, audio.played)
|
||||
self.command(self.adapter.history_repair_request(audio.repair))
|
||||
|
||||
async def client_control(self, raw):
|
||||
async with self.lock:
|
||||
@@ -1492,7 +1495,7 @@ class VoiceRuntime:
|
||||
intent = wire.get("metadata", {}).get("voice_intent")
|
||||
if (self.pending_create is None or not self.intent_dispatched
|
||||
or intent != self.pending_create[0]):
|
||||
self.command(dict(type="response.cancel", response_id=wire["id"]))
|
||||
self.command(self.adapter.cancellation_request(wire["id"]))
|
||||
raise ValueError("Unsolicited response")
|
||||
_, turn = self.pending_create
|
||||
response = Response(wire["id"], turn, creation_intent=intent,
|
||||
@@ -1504,8 +1507,7 @@ class VoiceRuntime:
|
||||
response.interrupted = True
|
||||
response.final_deadline = self.clock() + self.settings.final_progress_window_ms / 1000
|
||||
response.cancel_event = identity()
|
||||
self.command(dict(type="response.cancel", response_id=response.id,
|
||||
event_id=response.cancel_event))
|
||||
self.command(self.adapter.cancellation_request(response.id, response.cancel_event))
|
||||
elif self.responses[wire["id"]].creation_intent != wire.get("metadata", {}).get("voice_intent"):
|
||||
raise ValueError("Response creation identity conflict")
|
||||
elif kind in ("response.output_item.added", "response.output_item.done"):
|
||||
@@ -1733,6 +1735,11 @@ class VoiceRuntime:
|
||||
event_type=kind, audio=matches[0] if len(matches) == 1 else None)
|
||||
return
|
||||
audio = matches[0]
|
||||
receipt = self.adapter.confirm_history_repair(audio.repair, event)
|
||||
if (not isinstance(receipt, HistoryRepairReceipt)
|
||||
or receipt.repair != audio.repair):
|
||||
raise ProviderProtocolError("Uncorrelated history repair receipt")
|
||||
audio.repair_receipt = receipt
|
||||
audio.cleanup_deadline = None
|
||||
self.trace("truncate_acknowledged", audio=audio)
|
||||
self.retire(audio)
|
||||
|
||||
@@ -43,7 +43,7 @@ class RuntimeSettings(BaseSettings):
|
||||
|
||||
@classmethod
|
||||
def for_provider(cls, provider):
|
||||
if provider not in ('openai', 'gemini'):
|
||||
if provider not in ('openai', 'gemini', 'local_s2s'):
|
||||
raise ValueError('Unsupported voice provider')
|
||||
return cls(output_capacity_profile='openai-repair' if provider == 'openai' else 'standard')
|
||||
|
||||
|
||||
Reference in New Issue
Block a user