Files
baji-vc/gateway/gateway.py
T

831 lines
45 KiB
Python

import asyncio
import contextlib
import hashlib
import io
import json
import os
import secrets
import time
import wave
from contextlib import asynccontextmanager
from pathlib import Path
import httpx
import numpy as np
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, HTTPException
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
import uuid
from history import History
from face_context import FaceContext
from reply_emotion import SYSTEM_FRAGMENT, parse_reply
from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply
from action_protocol import ActionPlans, negotiate, configured_packs
from guest_sessions import GuestSessions, COOKIE
from tts_debug import DebugStore
from persona_resolver import resolve_persona
from segmentation import Segmenter
from llm_provider import LLMProvider
from app import EXPECTED_HASH
from protocol import WavStream, pack, unpack
from vad import Config, Silero, VadSession
ROOT = Path(__file__).resolve().parent
VERSION = '0.8.0'
DEFAULT_VOICE_ID = '9a97272c-3919-5606-9c8f-9552ab602528'
ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.0.0.1:5011'}
@asynccontextmanager
async def lifespan(app):
token = os.environ.get('LAN_GATEWAY_TOKEN', '')
if len(token) < 32: raise RuntimeError('missing gateway token')
provider = LLMProvider()
app.state.llm_structured_output = provider.structured_output
app.state.llm_model = provider.model
app.state.llm_time_zone = provider.clock.zone.key
app.state.expression_prepare = provider.expression_prepare
path = ROOT / 'models/silero_vad.onnx'
if hashlib.sha256(path.read_bytes()).hexdigest() != EXPECTED_HASH: raise RuntimeError('model checksum')
app.state.model = await asyncio.to_thread(Silero, path)
app.state.token = token
app.state.guests = GuestSessions()
app.state.guest_enabled = os.environ.get('LAN_GUEST_ENABLED', '1') != '0'
app.state.lan_open = os.environ.get('LAN_OPEN_MODE', '0') == '1'
app.state.remote_log = []
app.state.remote_reports = []
app.state.busy = False
app.state.history = History(ROOT / '.runtime/history.sqlite3')
await app.state.history.initialize()
app.state.debug = await asyncio.to_thread(DebugStore, ROOT / '.runtime/tts-debug')
app.state.lvbu = json.loads((ROOT / '.runtime/personas/lvbu.json').read_text())
app.state.lore = json.loads((ROOT / 'personas/lvbu.lorebook.json').read_text())
async with httpx.AsyncClient(timeout=30, trust_env=False, limits=httpx.Limits(max_connections=4, max_keepalive_connections=4)) as client:
app.state.client = client
response = await client.get('http://192.168.31.61:5002/v1/voices')
response.raise_for_status()
app.state.voices = [{'id': v['id'], 'source': v.get('source', 'registry'), 'default': v['id'] == DEFAULT_VOICE_ID} for v in response.json().get('voices', []) if v.get('status') == 'active'][:64]
if not any(v['id'] == DEFAULT_VOICE_ID for v in app.state.voices): raise RuntimeError('registered default voice unavailable')
yield
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
class UncachedStaticFiles(StaticFiles):
async def get_response(self, path, scope):
response = await super().get_response(path, scope)
response.headers['Cache-Control'] = 'no-store'
return response
app.mount('/static', UncachedStaticFiles(directory=ROOT / 'web'), name='static')
@app.get('/')
async def index():
return FileResponse(ROOT / 'web/index.html', headers={'Cache-Control': 'no-store'})
@app.get('/debug')
async def debug_page():
return FileResponse(ROOT / 'web/debug.html', headers={'Cache-Control':'no-store'})
def load_active_profile():
path = ROOT / '.runtime' / 'active_profile.json'
try:
data = json.loads(path.read_text(encoding='utf-8'))
return data if isinstance(data, dict) else None
except (OSError, ValueError):
return None
def open_key(connection):
if not getattr(app.state, 'lan_open', False) or not connection.client or not GuestSessions.lan(connection.client.host): return None
key = 'lan:' + connection.client.host
if not app.state.guests.get(key):
app.state.guests.sessions[key] = {'expires': time.time() + app.state.guests.ttl, 'conversations': set()}
return key
def guest_key(connection):
key = connection.cookies.get(COOKIE)
if not getattr(app.state, 'guest_enabled', False) or not connection.client or not GuestSessions.lan(connection.client.host): return None
return key if app.state.guests.get(key) else None
@app.post('/session/bootstrap')
async def bootstrap(request: Request):
if not getattr(app.state, 'guest_enabled', False) or not request.client or not GuestSessions.lan(request.client.host): raise HTTPException(403)
if request.headers.get('origin') not in ORIGINS or request.headers.get('content-type', '').split(';')[0] != 'application/json': raise HTTPException(403)
if 'https://' + request.headers.get('host', '') != request.headers.get('origin'): raise HTTPException(403)
body = await request.body()
if len(body) > 1024: raise HTTPException(413)
try:
if not isinstance(json.loads(body), dict): raise ValueError()
except (ValueError, TypeError): raise HTTPException(400)
key = guest_key(request)
if not key:
try: key = app.state.guests.create()
except ValueError: raise HTTPException(429)
from fastapi.responses import JSONResponse
response = JSONResponse({'status':'ok','expires_in':max(0,int(app.state.guests.get(key)['expires']-time.time()))})
response.set_cookie(COOKIE,key,max_age=max(0,int(app.state.guests.get(key)['expires']-time.time())),secure=True,httponly=True,samesite='strict')
return response
@app.post('/session/logout')
async def logout(request: Request):
if request.headers.get('origin') not in ORIGINS: raise HTTPException(403)
app.state.guests.revoke(request.cookies.get(COOKIE))
from fastapi.responses import JSONResponse
response=JSONResponse({'status':'logged_out'});response.delete_cookie(COOKIE,secure=True,httponly=True,samesite='strict');return response
@app.get('/health')
async def health():
return {'status': 'ok', 'version': VERSION, 'codec': 'pcm16', 'opus': False, 'busy': app.state.busy,
'llm_model': getattr(app.state, 'llm_model', 'unknown'),
'llm_time_zone': getattr(app.state, 'llm_time_zone', 'unknown'),
'expression_prepare': getattr(app.state, 'expression_prepare', False),
'llm_structured_output': getattr(app.state, 'llm_structured_output', 'prompt'), 'stt': 'batch SenseVoice', 'tts': 'per-turn full text / single streaming generator VoxCPM2', 'voice_mode_default': 'continuous_voice', 'default_voice_id': DEFAULT_VOICE_ID}
@app.post('/debug/log')
async def debug_log_post(request: Request):
if not getattr(app.state, 'lan_open', False) or not request.client or not GuestSessions.lan(request.client.host): raise HTTPException(403)
raw = await request.body()
if len(raw) > 4096: raise HTTPException(413)
try:
data = json.loads(raw)
except (ValueError, UnicodeDecodeError):
raise HTTPException(400)
if not isinstance(data, dict) or not isinstance(data.get('message'), str): raise HTTPException(400)
entry = {'ts': data.get('timestamp_ms', 0), 'tag': str(data.get('tag', ''))[:32], 'msg': str(data['message'])[:500], 'from': request.client.host}
app.state.remote_log.append(entry)
if len(app.state.remote_log) > 200: app.state.remote_log = app.state.remote_log[-100:]
return {'status': 'ok'}
@app.get('/debug/log')
async def debug_log_get(request: Request):
if not getattr(app.state, 'lan_open', False) or not request.client or not GuestSessions.lan(request.client.host): raise HTTPException(403)
return {'entries': app.state.remote_log[-100:]}
@app.post('/debug/report')
async def debug_report_post(request: Request):
if not getattr(app.state, 'lan_open', False) or not request.client or not GuestSessions.lan(request.client.host): raise HTTPException(403)
raw = await request.body()
if len(raw) > 2097152: raise HTTPException(413)
try:
data = json.loads(raw)
except (ValueError, UnicodeDecodeError):
raise HTTPException(400)
if not isinstance(data, dict) or data.get('type') != 'diagnostic_report': raise HTTPException(400)
entry = {'received_at': time.time(), 'from': request.client.host, 'report': data}
app.state.remote_reports.append(entry)
if len(app.state.remote_reports) > 20: app.state.remote_reports = app.state.remote_reports[-10:]
return {'status': 'ok', 'entries_received': len(data.get('logs', []))}
@app.get('/debug/report')
async def debug_report_get(request: Request):
if not getattr(app.state, 'lan_open', False) or not request.client or not GuestSessions.lan(request.client.host): raise HTTPException(403)
return {'reports': app.state.remote_reports[-10:]}
@app.post('/debug/download')
async def debug_download(request: Request):
admin = secrets.compare_digest(request.headers.get('authorization', ''), 'Bearer ' + app.state.token)
owner = guest_key(request)
if not admin and not owner: raise HTTPException(403)
if request.headers.get('origin') not in ORIGINS: raise HTTPException(403)
raw = await request.body()
if len(raw) > 2048: raise HTTPException(413)
try:
data = json.loads(raw)
cid = str(uuid.UUID(data['conversation_id']))
if not admin: app.state.guests.own(owner, cid)
path = await asyncio.to_thread(app.state.debug.authorized, data['debug_id'], cid, data['kind'])
except (ValueError, KeyError, FileNotFoundError): raise HTTPException(404)
return FileResponse(path, filename=path.name, headers={'Cache-Control':'no-store'})
class Dialogue:
def __init__(self, ws, model, client, history=None, conversation_id=None):
self.ws, self.client = ws, client
self.llm_provider = LLMProvider()
self.history = history
self.conversation_id = conversation_id
self.run_id = None
self.voice_mode = 'continuous_voice'
self.voice_id = DEFAULT_VOICE_ID
self.voice_locked = False
self.debug_store = None
self.debug_enabled = True
self.debug_captures = {}
self.persona = 'default'
self.persona_rules = ''
self.answers = {}
self.contexts = {}
self.face_context = FaceContext()
self.face_messages = {}
self.pending_drained = None
self.connection_generation = secrets.token_hex(16)
self.owner = secrets.token_hex(16)
self.action_plans = ActionPlans(self.owner, self.connection_generation)
self.action_capability = None
self.action_expiry_task = None
self.action_holding = False
self.followup_pending = None
self.capture_offset = 0
self.received_samples = 0
self.vad = VadSession(model, Config(max_session_seconds=600))
self.lock = asyncio.Lock()
self.turn = 0
self.event_seq = 0
self.down_seq = 0
self.up_seq = 0
self.task = None
self.cancelled_tasks = set()
self.listening = False
self.mode = 'auto'
self.barge = True
self.capture = bytearray()
self.base = 0
self.start = None
self.wall = time.monotonic()
self.closed = False
self.playback_waiting = False
self.auth_check = lambda: True
async def event(self, event_type, turn=None, **fields):
async with self.lock:
if turn is not None and turn != self.turn: return
if not self.auth_check(): raise ValueError('guest expired')
self.event_seq += 1
await asyncio.wait_for(self.ws.send_json({'type': event_type, 'turn_id': self.turn if turn is None else turn, 'seq': self.event_seq, 'server_ms': round((time.monotonic() - self.wall) * 1000, 3), **fields}), 5)
async def audio(self, turn, pcm):
async with self.lock:
if turn != self.turn: return
if not self.auth_check(): raise ValueError('guest expired')
self.down_seq += 1
await asyncio.wait_for(self.ws.send_bytes(pack(2, turn, self.down_seq, pcm)), 5)
async def invalidate(self, reason, preserve_vad=False):
old_turn = self.turn
self.action_plans.clear()
self.action_holding = False
self.followup_pending = None
expiry = self.action_expiry_task
self.action_expiry_task = None
if expiry and expiry is not asyncio.current_task(): expiry.cancel()
self.turn += 1
if reason == 'new_turn':
self.face_context.advance_capture(old_turn, self.turn)
else:
self.face_context.clear()
self.face_messages.clear()
self.pending_drained = None
old = self.task
previous_run = self.run_id
self.run_id = None
self.task = None
if previous_run and self.history:
await self.history.interrupt(previous_run)
if old and not old.done():
old.cancel()
self.cancelled_tasks.add(old)
old.add_done_callback(self.cancelled_tasks.discard)
self.start = None
self.capture.clear()
self.base = 0
if not preserve_vad:
self.capture_offset = self.received_samples
self.vad.reset()
self.playback_waiting = False
self.up_seq = 0
self.down_seq = 0
await self.event('abort', reason=reason, accepted_input_samples=self.received_samples)
async def listen(self, mode, enabled=True, barge=True, start_windows=3):
if mode not in ('auto', 'manual'): raise ValueError('listen mode')
if enabled:
await self.invalidate('listen_start')
self.listening, self.mode, self.barge = True, mode, bool(barge)
self.up_seq = 0
self.received_samples = 0
self.capture_offset = 0
self.vad = VadSession(self.vad.model, Config(start_windows=int(start_windows)))
self.start = 0 if mode == 'manual' else None
await self.event('listen', state='start', mode=mode, barge_in=self.barge)
else:
self.listening = False
if mode == 'manual' and self.capture:
await self.submit(bytes(self.capture), len(self.capture) // 2)
await self.event('listen', state='stop', mode=mode)
async def input(self, frame):
if self.action_holding: return # Drop all stale input; no capture/VAD/ASR buffering.
turn, seq, pcm = unpack(frame, 1)
if turn != self.turn: return
if not self.listening: raise ValueError('not listening')
if seq != self.up_seq + 1: raise ValueError('sequence gap')
self.up_seq = seq
self.received_samples += len(pcm) // 2
responding = (self.task is not None and not self.task.done()) or self.playback_waiting
if responding and not self.barge:
return
self.capture.extend(pcm)
if len(self.capture) > 960000 + 32000: raise ValueError('capture limit')
if self.mode == 'manual':
if len(self.capture) >= 960000:
self.listening = False
await self.submit(bytes(self.capture[:960000]), 480000)
return
events = await asyncio.to_thread(self.vad.feed, pcm)
for ev in events:
if ev['type'] == 'speech.start':
if responding:
if not self.barge: continue
saved = bytes(self.capture)
history_start = ev['preroll_start_sample']
saved_vad = self.vad
saved_base = self.base
await self.invalidate('voice_barge_in', preserve_vad=True)
self.vad = saved_vad
self.capture.extend(saved)
self.start = history_start
self.base = saved_base
self.up_seq = 0
await self.event('listen', state='start', mode='auto', barge_in=True)
return
self.start = ev['preroll_start_sample']
await self.event('vad', event={k: v for k, v in ev.items() if 'base64' not in k})
if ev['type'] == 'speech.end' and self.start is not None:
end = ev['sample']
left = max(0, self.start - self.base) * 2
right = max(0, end - self.base) * 2
speech = bytes(self.capture[left:right])
await self.submit(speech, end)
return
if self.start is None:
keep = min(len(self.capture), 12000)
drop = len(self.capture) - keep
del self.capture[:drop]
self.base += drop // 2
async def submit(self, pcm, end_sample):
if not pcm or len(pcm) > 960000: return
absolute_end = self.capture_offset + end_sample
await self.invalidate('new_turn')
turn = self.turn
self.run_id = str(uuid.uuid4())
await self.event('capture.end', turn, end_sample=absolute_end, input_samples=len(pcm) // 2)
self.task = asyncio.create_task(self.run(turn, pcm))
async def send_history(self):
if self.history:
await self.event('history', conversation_id=self.conversation_id, messages=await self.history.rows(self.conversation_id))
async def change_history(self, action):
await self.invalidate('history_' + action)
self.listening = False
if self.cancelled_tasks:
await asyncio.gather(*list(self.cancelled_tasks), return_exceptions=True)
if action == 'clear':
await self.history.clear(self.conversation_id)
elif action == 'new':
self.conversation_id = await self.history.conversation()
await self.send_history()
async def request_drained(self, turn):
if turn != self.turn or not self.playback_waiting: return
if self.task is not None and not self.task.done():
# tts.stop may reach Android before history/debug finalization completes.
self.pending_drained = turn
else:
await self.drained()
async def drained(self):
self.pending_drained = None
self.playback_waiting = False
if self.followup_pending and self.followup_pending[0] == self.turn:
_, rid, text = self.followup_pending
self.followup_pending = None
if self.history: await self.history.spoken(self.conversation_id, rid, text)
if self.history and self.run_id:
await self.history.drained(self.run_id)
await self.send_history()
ticket = self.action_plans.drained(self.turn)
if ticket is not None:
self.action_holding = True
self.capture.clear(); self.start = None; self.vad.reset()
await self.event('action.plan', action_id=ticket.id, kind='dance', pack_sha256=ticket.pack_sha,
ttl_ms=max(0, int((ticket.expires-time.monotonic())*1000)))
return
if not self.barge:
self.capture.clear(); self.start = None; self.base = 0
self.capture_offset = self.received_samples
self.vad.reset()
await self.event('listen', state='resumed', mode=self.mode)
async def run(self, turn, pcm):
metrics = {'debug_enabled_for_turn': self.debug_enabled}
began = time.perf_counter()
rid = self.run_id or str(uuid.uuid4())
self.answers[turn] = ''
status = 'failed'
recorded = False
try:
async with asyncio.timeout(90):
wav = io.BytesIO()
with wave.open(wav, 'wb') as file:
file.setnchannels(1); file.setsampwidth(2); file.setframerate(16000); file.writeframes(pcm)
before = time.perf_counter()
async with asyncio.timeout(30):
result = await self.client.post('http://192.168.31.61:5001/v1/audio/transcriptions', files={'file': ('speech.wav', wav.getvalue(), 'audio/wav')})
result.raise_for_status()
metrics['stt_ms'] = round((time.perf_counter() - before) * 1000, 2)
text = result.json().get('text', '').strip()
if turn != self.turn: return
await self.event('stt', turn, state='final', text=text)
if not text:
self.face_context.clear()
await self.event('listen', turn, state='resumed', mode=self.mode)
return
# Snapshot after ASR: no camera wait, no persistent/history context.
face_message = self.face_context.take(turn)
if face_message is not None: self.face_messages[turn] = [face_message]
metrics['face_cue_used'] = face_message is not None
metrics['face_context'] = self.face_context.diagnostics()
text = text[:2000]
if self.history:
recorded = True
await self.history.begin(self.conversation_id, rid, text)
self.contexts[turn] = await self.history.context(self.conversation_id, rid)
if turn != self.turn: return
await self.send_history()
self.playback_waiting = True
await self.event('tts', turn, state='start', sample_rate=48000, codec='pcm16', frame_duration=20)
queue = asyncio.Queue(maxsize=2)
async with asyncio.TaskGroup() as group:
group.create_task(self.generate(turn, text, queue, metrics, began))
group.create_task(self.synthesize(turn, queue, metrics, began))
metrics['total_ms'] = round((time.perf_counter() - began) * 1000, 2)
await self.event('metrics', turn, values=metrics)
await self.event('tts', turn, state='stop')
status = 'completed'
except asyncio.CancelledError:
status = 'interrupted'
raise
except Exception:
await self.event('error', turn, code='backend_failed', message='Backend timeout, format or synthesis failure')
await self.event('tts', turn, state='stop')
finally:
if turn == self.turn and status != 'completed':
self.action_plans.clear()
answer = self.answers.pop(turn, '')
self.contexts.pop(turn, None)
self.face_messages.pop(turn, None)
capture = self.debug_captures.pop(turn, None)
if capture:
capture.meta['metrics'] = metrics
debug_id = await asyncio.to_thread(capture.finalize, status if turn == self.turn else 'interrupted')
if not self.closed: await self.event('debug.saved', debug_id=debug_id, captured_turn=turn)
if recorded:
await self.history.finish(rid, answer, status if turn == self.turn else 'interrupted')
if turn == self.turn and not self.closed:
await self.send_history()
if turn == self.turn and not self.closed and self.pending_drained == turn:
await self.drained()
async def generate(self, turn, text, queue, metrics, began):
request_start = time.perf_counter()
metrics.update(voice_mode=self.voice_mode, voice_id=self.voice_id, tts_request_count=0)
# Exactly one initial system: Qwen's deployed template rejects a second system.
system = '以下角色设定只约束reply字段的可朗读正文。\n' + self.persona_rules + ''.join(
'\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT + '\n' + ACTION_FRAGMENT + '\n网关实际可用动作:' + ('dance' if self.action_capability else '无')
messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}]
url, headers, body = self.llm_provider.request(messages, max_tokens=160, action_plan=True)
metrics['llm_request_count'] = 1
raw_body = ''
prefix = ExpressionPrefix(turn)
prepare_enabled = self.llm_provider.expression_prepare
finish_reason = 'not_provided'
usage = {}
async with asyncio.timeout(30):
async with self.client.stream('POST', url, headers=headers, json=body) as response:
response.raise_for_status()
event_data = []
async for line in response.aiter_lines():
if turn != self.turn: return
if line.startswith('data:'): event_data.append(line[5:].lstrip())
if line != '' or not event_data: continue
raw = '\n'.join(event_data); event_data = []
if raw == '[DONE]': break
data = json.loads(raw)
reported_usage = data.get('usage')
if isinstance(reported_usage, dict):
for key in ('prompt_tokens', 'completion_tokens', 'total_tokens'):
value = reported_usage.get(key)
if type(value) is int and 0 <= value <= 10_000_000: usage[key] = value
for choice in data.get('choices', []):
reported_finish = choice.get('finish_reason')
if reported_finish is not None:
finish_reason = reported_finish if reported_finish in ('stop', 'length', 'content_filter', 'tool_calls', 'function_call') else 'unknown'
delta = choice.get('delta', {}).get('content') or ''
if not delta: continue
metrics.setdefault('llm_first_token_ms', round((time.perf_counter() - request_start) * 1000, 2))
raw_body += delta
candidate = prefix.feed(delta, self.turn)
if candidate is not None and prepare_enabled:
metrics['expression_prepare_ms'] = round((time.perf_counter()-request_start)*1000, 2)
await self.event('reply.emotion.prepare', turn, emotion=candidate[0], intensity=candidate[1], preload_only=True)
if len(raw_body) > 8192: raise ValueError('structured reply limit')
if turn != self.turn: return
if not raw_body.strip(): raise ValueError('empty LLM body')
parse_start = time.perf_counter()
plan = parse_action_reply(raw_body, finish_reason, bool(self.action_capability))
result = plan.speech
metrics['action_reason'] = plan.action_reason
metrics['expression_prepare_mode'] = 'schema_prefix_preload' if prepare_enabled else 'full_reply'
if prepare_enabled and prefix.candidate and not prefix.consistent(plan, self.turn):
await self.event('reply.emotion.prepare.cancel', turn, reason='final_invalid')
if plan.action == 'dance':
ticket = self.action_plans.create(turn, plan.after, self.action_capability)
self.action_expiry_task = asyncio.create_task(self.expire_action(ticket.id, turn))
metrics.update(reply_emotion_reason=result.reason, reply_parse_branch=result.parse_branch,
reply_emotion=result.emotion, reply_intensity=result.intensity,
llm_finish_reason=finish_reason, llm_usage=usage, llm_max_tokens=body['max_tokens'],
llm_structured_output=self.llm_provider.structured_output)
metrics['reply_parse_ms'] = round((time.perf_counter() - parse_start) * 1000, 2)
metrics['reply_emotion_source'] = result.source
metrics['llm_first_body_ms'] = round((time.perf_counter() - request_start) * 1000, 2)
metrics['structured_wait_ms'] = round(metrics['llm_first_body_ms'] - metrics.get('llm_first_token_ms', 0), 2)
metrics['llm_finished_ms'] = round((time.perf_counter() - began) * 1000, 2)
# Only the extracted reply enters events, persistent history and the single TTS generator.
self.answers[turn] = result.reply
await self.event('llm', turn, text=result.reply)
await self.event('reply.emotion', turn, emotion=result.emotion, intensity=result.intensity, source=result.source, reason=result.reason, parse_branch=result.parse_branch,
finish_reason=finish_reason, usage=usage)
await self.event('llm.finished', turn, voice_mode=self.voice_mode, llm_finished_ms=metrics['llm_finished_ms'])
async def enqueue(fragment):
if fragment:
metrics.setdefault('first_fragment_ms', round((time.perf_counter() - began) * 1000, 2))
await queue.put(fragment)
# A validated reply is a single synthesis input in every voice mode.
await enqueue(result.reply)
await queue.put(None)
async def expire_action(self, action_id, turn):
try:
ticket = self.action_plans.ticket
if ticket is None: return
await asyncio.sleep(max(0, ticket.expires-time.monotonic()))
if turn == self.turn and self.action_plans.ticket and self.action_plans.ticket.id == action_id:
await self.invalidate('action_timeout')
await self.event('action.cancel', action_id=action_id, reason='timeout')
await self.event('listen', state='resumed', mode=self.mode)
except asyncio.CancelledError:
pass
async def action_status(self, data):
status, after = self.action_plans.status(data, self.turn, self.owner, self.connection_generation)
if status in ('cancelled', 'failed'):
await self.invalidate('action_cancelled')
await self.event('listen', state='resumed', mode=self.mode)
elif status == 'completed':
await self.invalidate('action_followup')
turn = self.turn
self.run_id = str(uuid.uuid4())
await self.event('speech.start', turn, origin='after_action')
self.task = asyncio.create_task(self.speak_followup(turn, after))
async def speak_followup(self, turn, speech):
began = time.perf_counter()
rid = self.run_id
metrics = {'llm_request_count': 0, 'tts_request_count': 0, 'origin': 'after_action'}
try:
self.playback_waiting = True
await self.event('tts', turn, state='start', sample_rate=48000, codec='pcm16', frame_duration=20)
await self.event('llm', turn, text=speech.reply)
await self.event('reply.emotion', turn, emotion=speech.emotion, intensity=speech.intensity,
source=speech.source, reason=speech.reason, parse_branch=speech.parse_branch)
queue = asyncio.Queue(2)
await queue.put(speech.reply); await queue.put(None)
await self.synthesize(turn, queue, metrics, began)
if turn != self.turn: return
self.followup_pending = (turn, rid, speech.reply)
await self.event('metrics', turn, values=metrics)
await self.event('tts', turn, state='stop')
except asyncio.CancelledError:
raise
except Exception:
self.followup_pending = None
await self.event('error', turn, code='after_synthesis_failed', message='Action followup synthesis failed')
await self.event('tts', turn, state='stop')
finally:
capture = self.debug_captures.pop(turn, None)
if capture:
await asyncio.to_thread(capture.finalize, 'completed' if self.followup_pending else 'interrupted')
if turn == self.turn and not self.closed and self.pending_drained == turn:
await self.drained()
async def synthesize(self, turn, queue, metrics, began):
sentence = 0
previous_end = None
previous_pcm = None
metrics['tts_segments'] = []
while True:
ready_ahead = not queue.empty()
text = await queue.get()
if text is None: return
if turn != self.turn: return
sentence += 1
await self.event('tts', turn, state='sentence_start', text=text, sentence_id=sentence)
parser = WavStream()
pending = bytearray()
request_start = time.perf_counter()
segment = {'sentence_id': sentence, 'text_chars': len(text), 'ready_ahead': ready_ahead, 'request_ms': round((request_start - began) * 1000, 2), 'schedule_gap_ms': round((request_start - previous_end) * 1000, 2) if previous_end else 0, 'first_pcm_ms': None, 'first_voiced_ms': None, 'pcm_arrival_gap_ms': None}
audio_bytes = 0
last_chunk = None
segment.update(pcm_chunks=0, first_chunk_audio_ms=None, max_chunk_audio_ms=0, max_chunk_interarrival_ms=0)
metrics['tts_request_count'] = metrics.get('tts_request_count', 0) + 1
await self.event('voice.metrics', turn, voice_mode=self.voice_mode, voice_id=self.voice_id, tts_request_count=metrics['tts_request_count'])
if self.debug_store and metrics.get('debug_enabled_for_turn', self.debug_enabled) and turn not in self.debug_captures:
self.debug_captures[turn] = await asyncio.to_thread(self.debug_store.create, {'run_id':self.run_id,'conversation_id':self.conversation_id,'turn_id':turn,'voice_id':self.voice_id,'voice_mode':self.voice_mode,'persona':self.persona,'tts_requests':[]})
capture = self.debug_captures.get(turn)
if capture:
capture.meta['tts_requests'].append({'input_chars':len(text),'parameters':{'model':'openbmb/VoxCPM2','voice':self.voice_id,'stream':True},'request_number':sentence})
async with asyncio.timeout(30):
async with self.client.stream('POST', 'http://192.168.31.61:5002/v1/audio/speech', json={'model': 'openbmb/VoxCPM2', 'input': text, 'voice': self.voice_id, 'stream': True}) as response:
response.raise_for_status()
async for block in response.aiter_bytes():
if turn != self.turn: return
pcm = parser.feed(block)
if pcm:
now = time.perf_counter()
if capture: capture.enqueue(pcm, (now-began)*1000, sentence)
audio_bytes += len(pcm)
chunk_ms = len(pcm) / 96
segment['pcm_chunks'] += 1
if segment['first_chunk_audio_ms'] is None: segment['first_chunk_audio_ms'] = round(chunk_ms, 2)
segment['max_chunk_audio_ms'] = max(segment['max_chunk_audio_ms'], round(chunk_ms, 2))
if last_chunk is not None: segment['max_chunk_interarrival_ms'] = max(segment['max_chunk_interarrival_ms'], round((now - last_chunk) * 1000, 2))
last_chunk = now
if segment['first_pcm_ms'] is None:
segment['first_pcm_ms'] = round((now - request_start) * 1000, 2)
segment['pcm_arrival_gap_ms'] = round((now - previous_pcm) * 1000, 2) if previous_pcm else None
previous_pcm = now
if segment['first_voiced_ms'] is None and np.any(np.abs(np.frombuffer(pcm, dtype='<i2').astype(np.int32)) > 327):
segment['first_voiced_ms'] = round((now - request_start) * 1000, 2)
if 'tts_first_pcm_ms' not in metrics:
metrics['tts_first_pcm_ms'] = round((time.perf_counter() - request_start) * 1000, 2)
metrics['capture_to_first_pcm_ms'] = round((time.perf_counter() - began) * 1000, 2)
if 'tts_first_voiced_block_ms' not in metrics and np.any(np.abs(np.frombuffer(pcm, dtype='<i2').astype(np.int32)) > 327):
metrics['tts_first_voiced_block_ms'] = round((time.perf_counter() - request_start) * 1000, 2)
metrics['capture_to_voiced_block_ms'] = round((time.perf_counter() - began) * 1000, 2)
pending.extend(pcm)
while len(pending) >= 1920:
await self.audio(turn, bytes(pending[:1920])); del pending[:1920]
parser.finish()
if not audio_bytes: raise ValueError('empty TTS PCM')
if pending: await self.audio(turn, bytes(pending))
previous_end = time.perf_counter()
seconds = audio_bytes / 96000
segment.update(total_ms=round((previous_end - request_start) * 1000, 2), audio_seconds=round(seconds, 4), rtf=round((previous_end - request_start) / seconds, 4) if seconds else None)
if len(metrics['tts_segments']) < 16: metrics['tts_segments'].append(segment)
await self.event('tts.metrics', turn, values=segment)
async def close(self):
self.closed = True
self.action_plans.clear()
self.followup_pending = None
self.action_holding = False
if self.action_expiry_task: self.action_expiry_task.cancel()
self.turn += 1
tasks = list(self.cancelled_tasks)
if self.action_expiry_task: tasks.append(self.action_expiry_task)
if self.task: tasks.append(self.task)
for task in tasks: task.cancel()
if tasks: await asyncio.gather(*tasks, return_exceptions=True)
if self.history and self.run_id:
await self.history.interrupt(self.run_id)
self.face_context.clear(); self.face_messages.clear()
self.capture.clear(); self.vad.reset()
@app.websocket('/ws/dialogue')
async def dialogue(ws: WebSocket):
if ws.headers.get('origin') not in ORIGINS:
await ws.close(code=1008); return
if app.state.busy:
await ws.close(code=1013); return
app.state.busy = True
session = None
try:
await ws.accept()
owner = guest_key(ws) or open_key(ws)
if not owner:
raw = await asyncio.wait_for(ws.receive_text(), 5)
if len(raw) > 2048: raise ValueError('auth size')
auth = json.loads(raw)
if not isinstance(auth, dict) or auth.get('type') != 'auth' or not isinstance(auth.get('token'), str) or not secrets.compare_digest(auth['token'], app.state.token):
raise ValueError('auth')
await ws.send_json({'type': 'auth', 'state': 'ok', 'method':'guest_cookie' if owner else 'admin_bearer'})
raw = await asyncio.wait_for(ws.receive_text(), 5)
if len(raw) > 2048: raise ValueError('hello size')
hello = json.loads(raw)
if hello.get('type') != 'hello' or hello.get('codec') != 'pcm16' or hello.get('sample_rate') != 16000 or hello.get('frame_duration') != 20:
raise ValueError('hello supports pcm16 mono 16k 20ms only')
profile = load_active_profile() if hello.get('persona', 'default') == 'default' else None
persona = profile.get('persona', 'default') if profile else hello.get('persona', 'default')
resolved = resolve_persona(ROOT, persona, [v['id'] for v in app.state.voices])
requested = None if resolved['fresh_conversation'] else hello.get('conversation_id')
if owner and requested: app.state.guests.own(owner, requested)
cid = await app.state.history.conversation(requested)
if owner and not requested: app.state.guests.bind(owner, cid)
synthesis_mode = hello.get('synthesis_mode', 'balanced')
Segmenter(synthesis_mode)
session = Dialogue(ws, app.state.model, app.state.client, app.state.history, cid)
session.synthesis_mode = synthesis_mode
session.owner = owner or 'admin'
session.action_plans = ActionPlans(session.owner, session.connection_generation)
session.action_capability = negotiate(hello, configured_packs())
if owner: session.auth_check = lambda: bool(app.state.guests.get(owner))
voice_mode = hello.get('voice_mode', 'continuous_voice')
if voice_mode not in ('continuous_voice', 'fragment'): raise ValueError('voice mode')
session.voice_mode = voice_mode
voice_id = hello.get('voice_id', DEFAULT_VOICE_ID)
if profile and profile.get('voice_id'): voice_id = profile['voice_id']
if voice_id not in [v['id'] for v in app.state.voices]: raise ValueError('voice not active')
session.persona = persona
session.persona_rules = resolved['rules']
if resolved['locked']:
voice_id = resolved['voice_id']
session.voice_id = voice_id
session.debug_store = app.state.debug
session.debug_enabled = hello.get('tts_debug', True) is True
await session.event('hello', action_protocol=1, action_available=bool(session.action_capability), context_face_cue_version=1, reply_emotion_version=1, llm_structured_output=session.llm_provider.structured_output, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices)
await session.send_history()
started = time.monotonic()
while time.monotonic() - started < 600:
message = await asyncio.wait_for(ws.receive(), 60)
if message['type'] == 'websocket.disconnect': break
if owner:
app.state.guests.own(owner, session.conversation_id)
if message.get('bytes') is not None:
await session.input(message['bytes'])
else:
raw = message.get('text') or ''
if len(raw) > 4096: raise ValueError('control size')
data = json.loads(raw)
if not isinstance(data, dict): raise ValueError('control object')
if data.get('type') == 'context.face_cue':
if len(raw.encode('utf-8')) > 512:
session.face_context.clear('input_limit')
else:
session.face_context.update(data, session.turn)
elif data.get('type') == 'debug':
action = data.get('action', 'list')
if action == 'set': session.debug_enabled = data.get('enabled') is True
elif action == 'mark': await asyncio.to_thread(app.state.debug.mark, data['debug_id'], session.conversation_id)
elif action != 'list': raise ValueError('debug action')
await session.event('debug.list', enabled=session.debug_enabled, items=await asyncio.to_thread(app.state.debug.list, session.conversation_id))
elif data.get('type') == 'voice':
if session.voice_locked or session.persona != 'default': raise ValueError('voice locked for session/persona')
if data.get('voice_id') not in [v['id'] for v in app.state.voices]: raise ValueError('voice not active')
session.voice_id = data['voice_id']
await session.event('voice', voice_id=session.voice_id, source='registered_reference', locked=False)
elif data.get('type') == 'listen':
session.voice_locked = True
await session.event('voice', voice_id=session.voice_id, source='registered_reference', locked=True)
await session.listen(data.get('mode', 'auto'), data.get('state') == 'start', data.get('barge_in', True) is True, data.get('start_windows', 3))
elif data.get('type') == 'abort':
await session.invalidate('client_abort')
elif data.get('type') == 'history':
if data.get('conversation_id') != session.conversation_id: raise ValueError('conversation mismatch')
action = data.get('action', 'get')
if action in ('new', 'clear'):
if owner and action == 'new' and len(app.state.guests.get(owner)['conversations']) >= 20: raise ValueError('conversation limit')
await session.change_history(action)
if owner and action == 'new': app.state.guests.bind(owner, session.conversation_id)
elif action == 'get': await session.send_history()
else: raise ValueError('history action')
elif data.get('type') == 'playback.drained':
await session.request_drained(data.get('turn_id'))
elif data.get('type') == 'action.status':
await session.action_status(data)
elif data.get('type') == 'ping': await session.event('pong')
else: raise ValueError('control')
except (WebSocketDisconnect, RuntimeError):
pass
except (ValueError, TypeError, KeyError, asyncio.TimeoutError):
with contextlib.suppress(Exception): await ws.close(code=1008)
finally:
if session: await session.close()
app.state.busy = False