Stage 4: honest health, explicit error policy, event-bus integrity
Engine mode is now explicit: USE_MOCK_SIP=true is the only way to get the mock engine; an unconfigured trunk fails startup with guidance instead of silently degrading. Root-caused why the engine always ran mock: nested pydantic-settings never read .env (no env_file on the sub-settings classes) — all 8 now declare it. /health stops lying: reports engine mode (sippy|mock), a live DB SELECT 1, trunk registration state with reason, and TTS/STT availability from their last real request; "healthy" now requires ready + db + sippy + registered trunk. Error policy: leaf services (tts/transcription/llm_client) raise and track availability; call-loop callers catch, publish EventType.ERROR naming the failed service, and apply an explicit fallback. Persistence writes get one bounded 3x exponential retry, then an ERROR log — no more silent data loss. Event bus: a full subscriber queue drops its oldest event (counted) instead of silently evicting the subscription; subscribe(replay_last=N) delivers the advertised history replay, used by /ws/events (25). Receptionist correctness: a matched TAKE_MESSAGE rule beats the LLM; voicemail polls for early hangup and stops/transcribes/hangs up in finally; RecordingSession finally keeps its leg_ids so taps detach. Dead code removed: models/contact.py + Contact table, dtmf_buffer, transcribe_stream stub, SMS stub in notification.py. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,6 +27,8 @@ class TranscriptionService:
|
||||
def __init__(self, settings: SpeachesSettings):
|
||||
self.settings = settings
|
||||
self._client: Optional[httpx.AsyncClient] = None
|
||||
# Last-known reachability, surfaced by /health (None = no requests yet)
|
||||
self.available: Optional[bool] = None
|
||||
|
||||
async def _get_client(self) -> httpx.AsyncClient:
|
||||
"""Get or create the HTTP client."""
|
||||
@@ -60,6 +62,9 @@ class TranscriptionService:
|
||||
# Convert raw PCM to WAV format for the API
|
||||
wav_data = self._pcm_to_wav(audio_data)
|
||||
|
||||
# Raises on failure — callers decide the per-call fallback and
|
||||
# publish a service-error event; swallowing here made a down
|
||||
# Speaches look like "the AI is deciding badly".
|
||||
try:
|
||||
response = await client.post(
|
||||
"/v1/audio/transcriptions",
|
||||
@@ -72,44 +77,13 @@ class TranscriptionService:
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
text = response.text.strip()
|
||||
logger.debug(f"Transcription: '{text}'")
|
||||
return text
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"Speaches API error: {e.response.status_code} {e.response.text}")
|
||||
return ""
|
||||
except httpx.ConnectError:
|
||||
logger.error(f"Cannot connect to Speaches at {self.settings.url}")
|
||||
return ""
|
||||
except Exception as e:
|
||||
logger.error(f"Transcription failed: {e}")
|
||||
return ""
|
||||
|
||||
async def transcribe_stream(
|
||||
self,
|
||||
audio_data: bytes,
|
||||
language: str = "en",
|
||||
):
|
||||
"""
|
||||
Stream transcription — for real-time results.
|
||||
|
||||
Uses Speaches streaming endpoint if available,
|
||||
falls back to chunked transcription.
|
||||
|
||||
Yields:
|
||||
str: Partial transcription chunks
|
||||
"""
|
||||
# For now, do chunked transcription
|
||||
# TODO: Implement WebSocket streaming when Speaches supports it
|
||||
chunk_size = 16000 * 2 * 3 # 3 seconds of 16kHz 16-bit mono
|
||||
|
||||
for i in range(0, len(audio_data), chunk_size):
|
||||
chunk = audio_data[i:i + chunk_size]
|
||||
if len(chunk) > 0:
|
||||
text = await self.transcribe(chunk, language)
|
||||
if text:
|
||||
yield text
|
||||
except Exception:
|
||||
self.available = False
|
||||
raise
|
||||
self.available = True
|
||||
text = response.text.strip()
|
||||
logger.debug(f"Transcription: '{text}'")
|
||||
return text
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Close the HTTP client."""
|
||||
|
||||
Reference in New Issue
Block a user