feat(backend): integrate document deletion and grounded speech providers

Enable replay-safe document deletion and public deployment model identifiers with the forward voice-model schema revision.

Add GapGPT dialogue and ElevenLabs speech routing, strict extractive grounding, ten-source retrieval and regression coverage.

Validation: 199 targeted provider-free tests passed. The full provider-free run stalled and was interrupted; PostgreSQL acceptance was not run because TEST_DATABASE_URL is unset.
This commit is contained in:
amirhosein mazaheri
2026-10-20 09:00:37 +03:30
parent 2bffb9476a
commit 42400495af
27 changed files with 1003 additions and 28 deletions
+101 -8
View File
@@ -2,6 +2,8 @@
import asyncio
import json
import os
from contextvars import ContextVar
from uuid import uuid4
from collections import Counter
import socket
from threading import Event, Thread
@@ -11,6 +13,15 @@ import httpx
CLEANUP_WINDOW_SECONDS = 1.0
HALF_CLOSE_HEADER = 'x-local-s2s-half-close'
REQUEST_TRACE = ContextVar('local_component_trace', default=None)
def trace_phase(phase, **values):
state = REQUEST_TRACE.get()
if state is not None:
state.update(phase=phase, **values)
LIMITS = {'/v1/audio/transcriptions': (1100000, 65536),
'/v1/chat/completions': (1048576, 1048576),
'/v1/audio/speech': (16384, 1440000)}
@@ -21,12 +32,27 @@ class EvaluationBudgetExhausted(ValueError):
class ComponentServer:
def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None, responsive=False):
def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None, responsive=False, provider='split', tts_provider='upstream', tts_key=None, stt_provider='upstream', stt_key=None, strict_grounding=False):
if not key or not key.isascii() or any(c.isspace() for c in key):
raise ValueError('LOCAL_COMPONENT_CREDENTIAL_REQUIRED')
if provider not in ('split', 'gapgpt'):
raise ValueError('LOCAL_COMPONENT_PROVIDER_UNSUPPORTED')
if tts_provider not in ('upstream', 'elevenlabs'):
raise ValueError('LOCAL_TTS_PROVIDER_UNSUPPORTED')
if tts_provider == 'elevenlabs' and (not tts_key or not tts_key.isascii() or any(c.isspace() for c in tts_key)):
raise ValueError('LOCAL_ELEVENLABS_CREDENTIAL_REQUIRED')
if stt_provider not in ('upstream', 'elevenlabs'):
raise ValueError('LOCAL_STT_PROVIDER_UNSUPPORTED')
if stt_provider == 'elevenlabs' and (not stt_key or not stt_key.isascii() or any(c.isspace() for c in stt_key)):
raise ValueError('LOCAL_ELEVENLABS_CREDENTIAL_REQUIRED')
self.strict_grounding = strict_grounding
self.stt_provider, self.stt_key = stt_provider, stt_key
self.tts_provider, self.tts_key = tts_provider, tts_key
self.provider = provider
self.responsive = responsive
self.key, self.transport, self.timeout = key, transport, timeout
self.inactivity = min(timeout, 5) if inactivity is None else min(timeout, inactivity)
default_inactivity = timeout if provider == 'gapgpt' else min(timeout, 5)
self.inactivity = default_inactivity if inactivity is None else min(timeout, inactivity)
if self.timeout <= 0 or self.inactivity <= 0:
raise ValueError('LOCAL_COMPONENT_DEADLINE_REQUIRED')
self.counts = Counter()
@@ -102,10 +128,13 @@ class ComponentServer:
pass
async def _forward(self, client, writer, path, fields, body, response):
url = 'https://openrouter.ai/api' + path
url = ('https://api.gapgpt.app' if self.provider == 'gapgpt' else 'https://openrouter.ai/api') + path
auth_key = self.key
forward_body = bytes(body)
direct_asr = False
tts_provider = self.tts_provider
gemini_tts = False
eleven_stt = path.endswith('/transcriptions') and self.stt_provider == 'elevenlabs'
if path.endswith('/transcriptions'):
from email.parser import BytesParser
from email.policy import default
@@ -120,49 +149,93 @@ class ComponentServer:
if path.endswith('/speech'):
payload = json.loads(forward_body)
model_name = payload.get('model', '')
gemini_tts = self.provider == 'gapgpt' and model_name == 'gemini-2.5-flash-preview-tts'
if gemini_tts:
from services.local_s2s.gapgpt_audio import speech_payload
url = 'https://api.gapgpt.app/v1/chat/completions'
forward_body = json.dumps(speech_payload(payload)).encode()
direct_tts = model_name.startswith(('openai/', 'gpt-', 'tts-'))
if direct_tts and model_name.startswith('openai/'):
payload['model'] = model_name.removeprefix('openai/')
forward_body = json.dumps(payload).encode()
else:
direct_tts = False
if direct_asr or direct_tts:
if ((direct_asr and not eleven_stt) or (direct_tts and tts_provider != 'elevenlabs')) and self.provider == 'split':
url = 'https://api.openai.com' + path
auth_key = os.environ.get('OPENAI_API_KEY', '')
if not auth_key:
raise ValueError('LOCAL_OPENAI_CREDENTIAL_REQUIRED')
eleven_tts = path.endswith('/speech') and tts_provider == 'elevenlabs'
if eleven_tts:
voice = payload.get('voice', '')
if not voice.isascii() or not voice.isalnum() or payload.get('response_format') != 'pcm':
raise ValueError('Invalid ElevenLabs speech request')
url = 'https://api.elevenlabs.io/v1/text-to-speech/' + voice + '?output_format=pcm_24000'
forward_body = json.dumps(dict(text=payload['input'], model_id=payload['model'],
language_code='fa', voice_settings=dict(speed=payload.get('speed', 1.0)))).encode()
gemini_tts = False
trace_phase('upstream_headers', provider='elevenlabs' if eleven_tts or eleven_stt else ('gapgpt' if self.provider == 'gapgpt' else ('openai' if direct_asr or direct_tts else 'openrouter')))
request = client.build_request('POST', url,
headers={'Authorization': 'Bearer ' + auth_key,
headers={**({'xi-api-key': self.tts_key} if eleven_tts else {'Authorization': 'Bearer ' + auth_key}),
'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'},
content=forward_body)
if eleven_stt:
from services.local_s2s.elevenlabs import transcription_request
request = transcription_request(request, self.stt_key)
# The owner closes the response independently, even if cancellation or a
# stalled stream prevents this operation from reaching normal completion.
if self.responsive and path.endswith('/transcriptions') and not direct_asr:
if self.provider == 'split' and self.responsive and path.endswith('/transcriptions') and not direct_asr and not eleven_stt:
from services.local_s2s.responsiveness import transcription_request
request = transcription_request(request)
began = self.loop.time()
result = await client.send(request, stream=True)
header_ms = round((self.loop.time() - began) * 1000)
trace_phase('upstream_headers_received', upstream_status=result.status_code)
response.append(result)
if result.status_code != 200:
print(json.dumps(dict(stage="component_error", component=path.rsplit("/", 1)[-1], status=result.status_code)), flush=True)
trace_phase('upstream_status_rejected')
await self._error(writer, 502)
return
if gemini_tts:
from services.local_s2s.gapgpt_audio import decode_pcm
if (result.headers.get('content-type', '').split(';')[0] != 'application/json'
or result.headers.get('content-encoding', 'identity') != 'identity'):
raise ValueError('Invalid GapGPT speech media')
envelope = bytearray()
async for part in result.aiter_bytes():
envelope.extend(part)
if len(envelope) > LIMITS[path][1] * 4 // 3 + 65536:
raise ValueError('GapGPT speech capacity')
pcm = decode_pcm(json.loads(envelope), LIMITS[path][1])
result = httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=pcm)
media = result.headers.get('content-type', '').split(';')[0]
expected = ('audio/pcm', 'application/octet-stream') if path.endswith('/speech') else ('application/json', 'text/event-stream')
if media not in expected or result.headers.get('content-encoding', 'identity') != 'identity':
trace_phase('upstream_media_rejected')
await self._error(writer, 502)
return
if self.strict_grounding and path == '/v1/chat/completions':
from services.local_s2s.grounding import guard_response
envelope = bytearray()
async for part in result.aiter_bytes():
envelope.extend(part)
if len(envelope) > LIMITS[path][1]:
raise ValueError('Grounded response capacity')
guarded = guard_response(bytes(envelope), media, json.loads(forward_body).get('messages', []))
result = httpx.Response(200, headers={'content-type': media}, content=guarded)
await self._write(writer, ('HTTP/1.1 200 OK\r\nContent-Type: ' + media +
'\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n').encode('ascii'))
total = 0
# No 8192-byte accumulation: small SSE/PCM arrivals stay observable.
trace_phase('upstream_body')
async for raw in result.aiter_bytes():
if self.responsive and raw and total == 0:
print(json.dumps(dict(stage='component_first_byte', component=path.rsplit('/',1)[-1],
headers_ms=header_ms, first_body_ms=round((self.loop.time()-began)*1000))),flush=True)
total += len(raw)
trace_phase('upstream_body', response_bytes=total)
if total > LIMITS[path][1]:
raise ValueError('Response capacity')
for offset in range(0, len(raw), 8192):
@@ -171,6 +244,7 @@ class ComponentServer:
if not total:
raise ValueError('Empty component response')
await self._write(writer, b'0\r\n\r\n')
trace_phase('completed', outcome='completed')
async def _close_owned(self, writer, tasks, client, response):
writer.close()
@@ -197,6 +271,11 @@ class ComponentServer:
async def _serve(self, reader, writer, deadline):
client, tasks, response = None, [], []
began = self.loop.time()
state = dict(stage='component_request', component_request_id=uuid4().hex,
component='unknown', phase='request_headers', outcome='rejected',
timeout_ms=round(self.timeout * 1000), inactivity_ms=round(self.inactivity * 1000))
token = REQUEST_TRACE.set(state)
try:
async with asyncio.timeout_at(deadline):
# Header acquisition has its own short bound, including partial headers.
@@ -213,6 +292,7 @@ class ComponentServer:
if method != 'POST' or path not in LIMITS or version not in ('HTTP/1.0', 'HTTP/1.1'):
await self._error(writer, 403)
return
trace_phase('request_body', component=path.rsplit('/', 1)[-1])
request_limit, _ = LIMITS[path]
size = int(fields.get('content-length', '-1'))
if 'transfer-encoding' in fields or not 0 < size <= request_limit:
@@ -231,6 +311,7 @@ class ComponentServer:
if half_close not in (None, 'receive-response'):
await self._error(writer, 400)
return
state['outcome'] = 'failed'
self.counts[path] += 1 # one admitted provider attempt, including failed probes
client = httpx.AsyncClient(transport=self.transport, timeout=httpx.Timeout(self.inactivity, connect=self.inactivity),
follow_redirects=False, trust_env=False)
@@ -241,21 +322,33 @@ class ComponentServer:
if forwarding in done:
forwarding.result()
else:
state['outcome'] = 'downstream_disconnected'
self.counts['disconnected'] += 1
except EvaluationBudgetExhausted:
state['outcome'] = 'budget_rejected'
self.counts['budget_rejected'] += 1
await self._error(writer, 429)
except TimeoutError:
state['outcome'] = 'total_or_local_timeout'
self.counts['expired'] += 1
except asyncio.CancelledError:
state['outcome'] = 'cancelled'
self.counts['cancelled'] += 1
raise
except (ValueError, OSError, UnicodeError, asyncio.IncompleteReadError,
asyncio.LimitOverrunError, httpx.HTTPError):
asyncio.LimitOverrunError, httpx.HTTPError) as exc:
known = (httpx.ReadTimeout, httpx.ConnectTimeout, httpx.WriteTimeout, httpx.PoolTimeout,
httpx.RemoteProtocolError, httpx.ConnectError, ValueError, OSError)
state['error_type'] = next((kind.__name__ for kind in known if isinstance(exc, kind)), 'transport_error')
self.counts['failures'] += 1
finally:
# No successful terminal chunk is fabricated on any failure path.
await self._close_owned(writer, tasks, client, response)
try:
await self._close_owned(writer, tasks, client, response)
finally:
state['elapsed_ms'] = round((self.loop.time() - began) * 1000)
print(json.dumps(state), flush=True)
REQUEST_TRACE.reset(token)
def shutdown(self):
if self.loop is not None and self.loop.is_running():
+32
View File
@@ -0,0 +1,32 @@
"""Native ElevenLabs STT mapping; keep the original bounded audio bytes."""
from email.parser import BytesParser
from email.policy import default
import httpx
def transcription_request(request, key):
message = BytesParser(policy=default).parsebytes(
('Content-Type: ' + request.headers.get('content-type', '') + '\r\n\r\n').encode() + request.content)
if not message.is_multipart():
raise ValueError('Multipart transcription required')
parts = {}
for part in message.iter_parts():
name = part.get_param('name', header='content-disposition')
if name in parts:
raise ValueError('Repeated transcription field')
parts[name] = part
try:
model = parts['model'].get_payload(decode=True).decode('ascii')
language = parts['language'].get_payload(decode=True).decode('ascii') if 'language' in parts else 'fa'
audio = parts['file'].get_payload(decode=True)
except (KeyError, UnicodeError, AttributeError):
raise ValueError('Invalid transcription fields') from None
if not model or not audio or language != 'fa':
raise ValueError('Invalid transcription fields')
result = httpx.Request('POST', 'https://api.elevenlabs.io/v1/speech-to-text',
headers={'xi-api-key': key, 'Accept-Encoding': 'identity'},
data=dict(model_id=model, language_code=language, tag_audio_events='false',
diarize='false', timestamps_granularity='none'),
files={'file': ('audio.wav', audio, parts['file'].get_content_type())})
result.read()
return result
+19 -5
View File
@@ -36,7 +36,7 @@ def build_runtime(config, stop):
import speech_to_speech.TTS.openai_compatible_handler as native_tts
from services.local_s2s.request_policy import install_tts_speed
install_tts_speed(native_tts, config.local_s2s_tts_speed)
if config.local_s2s_responsive:
if config.local_s2s_responsive and config.local_s2s_stt_provider == 'upstream':
import speech_to_speech.STT.openai_compatible_handler as native_stt
from services.local_s2s.responsiveness import install_stt_policy
install_stt_policy(native_stt)
@@ -66,6 +66,17 @@ def build_runtime(config, stop):
raise
def engine_credential(name, parser):
credential_file = os.environ.get(name + '_FILE')
try:
key = Path(credential_file).read_text().strip() if credential_file else os.environ.get(name, '')
except OSError:
parser.error(name + '_FILE is unreadable.')
if not key:
parser.error(name + ' is required in the engine only.')
return key
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--allow-paid-startup', action='store_true')
@@ -91,11 +102,14 @@ def main():
logging.disable(logging.CRITICAL)
os.environ['HF_HUB_OFFLINE'] = '1'
os.environ['NLTK_DATA'] = root
key = os.environ.get('OPENROUTER_API_KEY', '')
if not key:
parser.error('OPENROUTER_API_KEY is required in the engine only.')
credential = 'GAPGPT_API_KEY' if config.local_s2s_component_provider == 'gapgpt' else 'OPENROUTER_API_KEY'
key = engine_credential(credential, parser)
eleven_key = engine_credential('ELEVENLABS_API_KEY', parser) if 'elevenlabs' in (config.local_s2s_tts_provider, config.local_s2s_stt_provider) else None
return run_owned(lambda stop: build_runtime(config, stop), key, config.local_s2s_request_timeout_seconds,
component_options={'responsive': True} if config.local_s2s_responsive else None)
component_options={'responsive': config.local_s2s_responsive, 'provider': config.local_s2s_component_provider,
'tts_provider': config.local_s2s_tts_provider, 'tts_key': eleven_key,
'stt_provider': config.local_s2s_stt_provider, 'stt_key': eleven_key,
'strict_grounding': config.local_s2s_strict_grounding})
if __name__ == '__main__':
+8
View File
@@ -1,4 +1,5 @@
"""Versioned extension for the pinned engine; no history-repair capability."""
import os
from copy import deepcopy
from queue import Queue, Full
from app.modules.voice.local_s2s import effective_identity
@@ -31,10 +32,17 @@ def active_components(unit, expected):
tts=dict(backend='openai', model=tts.model, voice=tts.voice,
response_format=tts.response_format, sample_rate=tts.sample_rate),
request_timeout_seconds=stt.timeout)
if 'provider' in expected['stt']:
actual['stt']['provider'] = os.environ.get('LOCAL_S2S_STT_PROVIDER', 'upstream')
if 'provider' in expected['tts']:
actual['tts']['provider'] = os.environ.get('LOCAL_S2S_TTS_PROVIDER', 'upstream')
if 'upstream_provider' in expected:
actual['upstream_provider'] = os.environ.get('LOCAL_S2S_COMPONENT_PROVIDER', 'split')
if 'speed' in expected['tts']:
actual['tts']['speed'] = tts.speed
if 'temperature' in expected['stt']:
actual['stt'].update(temperature=stt.gen_kwargs.get('temperature'), prompt=stt.gen_kwargs.get('prompt'))
if 'stream_batch_sentences' in expected['llm']:
actual['llm']['stream_batch_sentences'] = llm.stream_batch_sentences
if (actual != expected or tts.timeout != stt.timeout or llm.request_timeout_s != stt.timeout
or stt.base_url != 'http://127.0.0.1:8766/v1' or tts.base_url != stt.base_url
+34
View File
@@ -0,0 +1,34 @@
"""GapGPT Gemini TTS audio envelope to the existing bounded PCM contract."""
import base64
import binascii
from io import BytesIO
import wave
def speech_payload(payload):
return dict(model=payload['model'], stream=False, modalities=['audio'],
audio=dict(voice=payload['voice'], format='pcm16'),
messages=[dict(role='user', content=(
'Read aloud only the following text in its original language. '
f"Speak at {payload.get('speed', 1.0)} times normal pace. Text: " + payload['input']))])
def decode_pcm(payload, limit):
try:
choice, = payload['choices']
if choice['finish_reason'] != 'stop':
raise ValueError('Incomplete speech')
encoded = choice['message']['audio']['data']
if not isinstance(encoded, str) or len(encoded) > 4 * ((limit + 44 + 2) // 3):
raise ValueError('Speech capacity')
data = base64.b64decode(encoded, validate=True)
if data.startswith(b'RIFF'):
with wave.open(BytesIO(data), 'rb') as audio:
if (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) != (1, 2, 24000):
raise ValueError('Speech format')
data = audio.readframes(limit // 2 + 1)
if not data or len(data) % 2 or len(data) > limit:
raise ValueError('Speech capacity')
return data
except (KeyError, TypeError, binascii.Error, wave.Error, EOFError) as exc:
raise ValueError('Invalid GapGPT speech response') from None
+76
View File
@@ -0,0 +1,76 @@
"""Fail-closed, extractive answer gate before any local answer reaches TTS."""
import json
import unicodedata
FALLBACK = 'اطلاعات کافی برای پاسخ به این سؤال در مدارک بازیابی‌شده ندارم.'
SAFE = {FALLBACK, 'سلام، بفرمایید.', 'سلام.', 'لطفاً موضوع درخواستتان را مشخص کنید.', 'لطفاً نام شهرک و نوع قرارداد را مشخص کنید.'}
def normalized(value):
return ' '.join(unicodedata.normalize('NFC', value).split()).strip(' .،؛:!?؟«»"')
def evidence(messages):
# Prior turns and assistant prose are never current evidence.
start=max((i for i,m in enumerate(messages) if m.get('role')=='user'),default=len(messages))
calls={};sources={};reported=[]
for message in messages[start+1:]:
if message.get('role')=='assistant':
for call in message.get('tool_calls') or []:
calls[call.get('id')]=call.get('function',{})
elif message.get('role')=='tool':
function=calls.get(message.get('tool_call_id'),{})
try:result=json.loads(message.get('content',''))
except (ValueError,TypeError):continue
if not isinstance(result,dict) or result.get('status')!='ok':continue
if function.get('name') in ('search_knowledge','reuse_last_evidence'):
for source in result.get('sources',[]):
if isinstance(source,dict) and isinstance(source.get('text'),str):sources[source.get('source_ref')]=source['text']
elif function.get('name')=='report_used_sources':
try:reported=json.loads(function.get('arguments','{}')).get('source_refs',[])
except (ValueError,TypeError):reported=[]
return [sources[ref] for ref in reported if isinstance(ref,str) and ref in sources]
def safe_text(answer,messages):
if answer in SAFE:return answer
candidate=normalized(answer)
if not candidate:return FALLBACK
passages=evidence(messages)
for passage in passages:
# FAQ questions are not evidence of their own premise.
answer_only=passage.split('پاسخ:',1)[-1] if 'سؤال:' in passage else passage
if candidate in normalized(answer_only):return answer
# For one cited FAQ, use its actual answer rather than a generated paraphrase.
# Do not choose another source, infer relevance from rank, or synthesize facts.
if len(passages)==1 and 'سؤال:' in passages[0] and 'پاسخ:' in passages[0]:
literal=passages[0].split('پاسخ:',1)[1].strip()
if literal and len(literal)<=1200:return literal
return FALLBACK
def guard_response(raw,media,messages):
if media=='application/json':
data=json.loads(raw)
for choice in data.get('choices',[]):
message=choice['message']
message['content']=None if message.get('tool_calls') else safe_text(message.get('content') or '',messages)
return json.dumps(data,ensure_ascii=False).encode()
packets=[];done=False
for line in raw.decode('utf-8').splitlines():
if not line.startswith('data:'):continue
payload=line[5:].strip()
if payload=='[DONE]':done=True;continue
packets.append(json.loads(payload))
if not done or not packets:raise ValueError('Incomplete grounded response')
choices=[c for p in packets for c in p.get('choices',[])]
if any(c.get('delta',{}).get('tool_calls') for c in choices):
for c in choices:c.get('delta',{}).pop('content',None)
return (''.join('data: '+json.dumps(p,ensure_ascii=False)+'\n\n' for p in packets)+'data: [DONE]\n\n').encode()
answer=''.join(c.get('delta',{}).get('content') or '' for c in choices)
safe=safe_text(answer,messages)
first=packets[0]
base={key:first[key] for key in ('id','object','created','model') if key in first}
content=dict(base,choices=[dict(index=0,delta=dict(role='assistant',content=safe),finish_reason=None)])
finish=dict(base,choices=[dict(index=0,delta={},finish_reason='stop')])
return ('data: '+json.dumps(content,ensure_ascii=False)+'\n\ndata: '+json.dumps(finish)+'\n\ndata: [DONE]\n\n').encode()