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:
@@ -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():
|
||||
|
||||
Reference in New Issue
Block a user