added llm to tts connection
Browse files- python-services/llm_server.py +376 -1
python-services/llm_server.py
CHANGED
|
@@ -6,10 +6,15 @@ import os
|
|
| 6 |
import time
|
| 7 |
import logging
|
| 8 |
import asyncio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from typing import List, Optional, Dict, Any
|
| 10 |
from fastapi import FastAPI, HTTPException
|
| 11 |
from fastapi.middleware.cors import CORSMiddleware
|
| 12 |
-
from fastapi.responses import JSONResponse
|
| 13 |
from pydantic import BaseModel
|
| 14 |
|
| 15 |
# Internal Domain Layer Imports
|
|
@@ -44,6 +49,24 @@ MODEL_FAST = "llama-3.1-8b-instant"
|
|
| 44 |
MODEL_HEAVY = "llama-3.3-70b-versatile"
|
| 45 |
FALLBACK_MODEL_FIREWORKS = "accounts/fireworks/models/llama-v3p1-8b-instruct"
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
# ββ FastAPI App Configuration ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
app = FastAPI(
|
| 49 |
title="The Brain β Voice LLM Call Center Agent",
|
|
@@ -83,6 +106,88 @@ class EndSessionRequest(BaseModel):
|
|
| 83 |
session_id: str
|
| 84 |
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
# ββ REST API Router Endpoints ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 87 |
|
| 88 |
@app.post("/session/start")
|
|
@@ -284,6 +389,276 @@ async def chat(req: ChatRequest):
|
|
| 284 |
})
|
| 285 |
|
| 286 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
@app.post("/session/end")
|
| 288 |
async def end_session(req: EndSessionRequest):
|
| 289 |
"""Closes down session trackers and outputs permanent call summaries."""
|
|
|
|
| 6 |
import time
|
| 7 |
import logging
|
| 8 |
import asyncio
|
| 9 |
+
import re
|
| 10 |
+
import base64
|
| 11 |
+
import json
|
| 12 |
+
import threading
|
| 13 |
+
import httpx
|
| 14 |
from typing import List, Optional, Dict, Any
|
| 15 |
from fastapi import FastAPI, HTTPException
|
| 16 |
from fastapi.middleware.cors import CORSMiddleware
|
| 17 |
+
from fastapi.responses import JSONResponse, StreamingResponse
|
| 18 |
from pydantic import BaseModel
|
| 19 |
|
| 20 |
# Internal Domain Layer Imports
|
|
|
|
| 49 |
MODEL_HEAVY = "llama-3.3-70b-versatile"
|
| 50 |
FALLBACK_MODEL_FIREWORKS = "accounts/fireworks/models/llama-v3p1-8b-instruct"
|
| 51 |
|
| 52 |
+
# ββ TTS Space Bridge Configuration ββββββββββββββββββββββββββββββββββββββββββ
|
| 53 |
+
# URL is read from env so it can be overridden without a code deploy.
|
| 54 |
+
TTS_SPACE_URL = os.getenv("TTS_SPACE_URL", "https://voice-tts-tts.hf.space")
|
| 55 |
+
TTS_SYNTHESISE_TIMEOUT = 15.0 # seconds per sentence request
|
| 56 |
+
|
| 57 |
+
# Multi-script sentence boundary detector.
|
| 58 |
+
# Captures a run of non-terminator characters followed by one or more
|
| 59 |
+
# sentence-ending punctuation marks, then optional whitespace / end-of-string.
|
| 60 |
+
# Terminators covered:
|
| 61 |
+
# . ! ? β English / Turkish / Latin
|
| 62 |
+
# \u06d4 \u061f β Urdu (Ϋ) / Arabic-Urdu (Ψ)
|
| 63 |
+
# \u0964 β Devanagari / Bengali danda (ΰ₯€)
|
| 64 |
+
SENTENCE_END_RE = re.compile(
|
| 65 |
+
r'[^.!?\u06d4\u061f\u0964\n]+[.!?\u06d4\u061f\u0964]+(?:\s|$)'
|
| 66 |
+
r'|[^.!?\u06d4\u061f\u0964\n]*\n',
|
| 67 |
+
re.UNICODE,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
# ββ FastAPI App Configuration ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 71 |
app = FastAPI(
|
| 72 |
title="The Brain β Voice LLM Call Center Agent",
|
|
|
|
| 106 |
session_id: str
|
| 107 |
|
| 108 |
|
| 109 |
+
# ββ TTS Bridge Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 110 |
+
|
| 111 |
+
def _extract_sentences(buffer: str) -> tuple[list[str], str]:
|
| 112 |
+
"""
|
| 113 |
+
Scan the rolling token buffer for complete sentences using SENTENCE_END_RE.
|
| 114 |
+
Returns (completed_sentences, leftover_text) so the caller can continue
|
| 115 |
+
accumulating tokens into the leftover portion.
|
| 116 |
+
"""
|
| 117 |
+
sentences: list[str] = []
|
| 118 |
+
last_end = 0
|
| 119 |
+
for m in SENTENCE_END_RE.finditer(buffer):
|
| 120 |
+
sentence = buffer[m.start():m.end()].strip()
|
| 121 |
+
if sentence:
|
| 122 |
+
sentences.append(sentence)
|
| 123 |
+
last_end = m.end()
|
| 124 |
+
return sentences, buffer[last_end:]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
async def _fire_tts(sentence: str, language: str, gender: str) -> Optional[bytes]:
|
| 128 |
+
"""
|
| 129 |
+
Asynchronously POST a single sentence to the deployed TTS Space.
|
| 130 |
+
Endpoint: POST {TTS_SPACE_URL}/synthesise
|
| 131 |
+
Payload: {"text": str, "language": str, "gender": str}
|
| 132 |
+
Returns raw audio bytes (audio/mpeg) on success, None on any failure.
|
| 133 |
+
"""
|
| 134 |
+
sentence = sentence.strip()
|
| 135 |
+
if not sentence:
|
| 136 |
+
return None
|
| 137 |
+
try:
|
| 138 |
+
async with httpx.AsyncClient(timeout=TTS_SYNTHESISE_TIMEOUT) as client:
|
| 139 |
+
resp = await client.post(
|
| 140 |
+
f"{TTS_SPACE_URL}/synthesise",
|
| 141 |
+
json={"text": sentence, "language": language, "gender": gender},
|
| 142 |
+
)
|
| 143 |
+
if resp.status_code == 200:
|
| 144 |
+
logger.info(f"TTS β lang={language} chars={len(sentence)}")
|
| 145 |
+
return resp.content
|
| 146 |
+
logger.warning(
|
| 147 |
+
f"TTS Space returned HTTP {resp.status_code}: {resp.text[:120]}"
|
| 148 |
+
)
|
| 149 |
+
return None
|
| 150 |
+
except httpx.TimeoutException:
|
| 151 |
+
logger.error(
|
| 152 |
+
f"TTS request timed out ({TTS_SYNTHESISE_TIMEOUT}s): {sentence[:60]!r}"
|
| 153 |
+
)
|
| 154 |
+
return None
|
| 155 |
+
except Exception as exc:
|
| 156 |
+
logger.error(f"TTS request error: {exc}")
|
| 157 |
+
return None
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _start_groq_stream_thread(
|
| 161 |
+
params: dict,
|
| 162 |
+
q: asyncio.Queue,
|
| 163 |
+
loop: asyncio.AbstractEventLoop,
|
| 164 |
+
) -> None:
|
| 165 |
+
"""
|
| 166 |
+
Spawns a daemon thread that calls Groq's synchronous streaming API
|
| 167 |
+
and forwards each content chunk onto the asyncio Queue via
|
| 168 |
+
loop.call_soon_threadsafe so the async event generator can consume it.
|
| 169 |
+
|
| 170 |
+
Events pushed onto the queue:
|
| 171 |
+
("token", str) β a streamed content chunk from the LLM
|
| 172 |
+
("done", None) β stream finished cleanly
|
| 173 |
+
("error", str) β exception message from the stream
|
| 174 |
+
"""
|
| 175 |
+
def _run() -> None:
|
| 176 |
+
try:
|
| 177 |
+
stream = groq.chat.completions.create(**{**params, "stream": True})
|
| 178 |
+
for chunk in stream:
|
| 179 |
+
delta = chunk.choices[0].delta
|
| 180 |
+
if delta and delta.content:
|
| 181 |
+
loop.call_soon_threadsafe(
|
| 182 |
+
q.put_nowait, ("token", delta.content)
|
| 183 |
+
)
|
| 184 |
+
loop.call_soon_threadsafe(q.put_nowait, ("done", None))
|
| 185 |
+
except Exception as exc:
|
| 186 |
+
loop.call_soon_threadsafe(q.put_nowait, ("error", str(exc)))
|
| 187 |
+
|
| 188 |
+
threading.Thread(target=_run, daemon=True, name="groq-stream-worker").start()
|
| 189 |
+
|
| 190 |
+
|
| 191 |
# ββ REST API Router Endpoints ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 192 |
|
| 193 |
@app.post("/session/start")
|
|
|
|
| 389 |
})
|
| 390 |
|
| 391 |
|
| 392 |
+
@app.post("/chat/stream")
|
| 393 |
+
async def chat_stream(req: ChatRequest):
|
| 394 |
+
"""
|
| 395 |
+
Streaming LLM β TTS bridge endpoint using Server-Sent Events (SSE).
|
| 396 |
+
|
| 397 |
+
Architecture
|
| 398 |
+
------------
|
| 399 |
+
1. Groq streaming runs in a daemon thread (_start_groq_stream_thread).
|
| 400 |
+
2. Tokens are forwarded onto an asyncio.Queue so the async generator
|
| 401 |
+
can consume them without blocking the event loop.
|
| 402 |
+
3. Each token is appended to a rolling buffer. When SENTENCE_END_RE
|
| 403 |
+
finds a complete sentence, _fire_tts() immediately fires an async
|
| 404 |
+
httpx POST to the TTS Space β while the LLM is still generating
|
| 405 |
+
the rest of the response (the "live speaking" effect).
|
| 406 |
+
4. On Groq failure the endpoint transparently falls back to Fireworks
|
| 407 |
+
(non-streaming) before surfacing an error to the client.
|
| 408 |
+
|
| 409 |
+
SSE event schema (each event is a JSON object on a `data:` line):
|
| 410 |
+
{"type": "token", "text": "..."} β raw LLM token
|
| 411 |
+
{"type": "audio", "sentence": "...", "audio_b64": "...", "lang": "..."}
|
| 412 |
+
β base64 audio/mpeg
|
| 413 |
+
{"type": "done", "full_text": "...", "language": "...", ...}
|
| 414 |
+
β final metadata
|
| 415 |
+
{"type": "error", "detail": "..."} β fatal error
|
| 416 |
+
"""
|
| 417 |
+
if not req.message or not req.message.strip():
|
| 418 |
+
raise HTTPException(status_code=400, detail="Content payload cannot be empty.")
|
| 419 |
+
if len(req.message) > 2000:
|
| 420 |
+
raise HTTPException(status_code=400, detail="Maximum payload exceeds 2000 characters.")
|
| 421 |
+
|
| 422 |
+
# ββ 1. Session resolution (mirrors /chat) βββββββββββββββββββββββββββββββββ
|
| 423 |
+
session = manager.get_session(req.session_id)
|
| 424 |
+
if not session:
|
| 425 |
+
session = manager.create_session(
|
| 426 |
+
company_name=req.company_name or "Our Company",
|
| 427 |
+
agent_name=req.agent_name or "Sara",
|
| 428 |
+
agent_gender="female",
|
| 429 |
+
session_id=req.session_id,
|
| 430 |
+
)
|
| 431 |
+
logger.warning(f"[stream] Emergency session created: {session.session_id}")
|
| 432 |
+
|
| 433 |
+
# ββ 2. Language detection + prompt assembly βββββββββββββββββββββββββββββββ
|
| 434 |
+
detected_language = session.process_user_message(req.message)
|
| 435 |
+
if detected_language == "hi":
|
| 436 |
+
detected_language = "ur"
|
| 437 |
+
|
| 438 |
+
new_summary = req.currentSummary or ""
|
| 439 |
+
if len(session.messages) > 6:
|
| 440 |
+
messages_to_summarize = session.messages[:-6]
|
| 441 |
+
session.messages = session.messages[-6:]
|
| 442 |
+
new_summary = await generate_summary(new_summary, messages_to_summarize)
|
| 443 |
+
|
| 444 |
+
system_prompt = build_system_prompt(
|
| 445 |
+
company_name=session.company_name,
|
| 446 |
+
agent_name=session.agent_name,
|
| 447 |
+
agent_gender=session.agent_gender,
|
| 448 |
+
language=detected_language,
|
| 449 |
+
document_context=session.document_context,
|
| 450 |
+
custom_rules=session.custom_rules,
|
| 451 |
+
collected_caller_info=session.caller_info.to_dict(),
|
| 452 |
+
input_text=req.message,
|
| 453 |
+
)
|
| 454 |
+
session.add_message("user", req.message)
|
| 455 |
+
|
| 456 |
+
optimized_payload = [{"role": "system", "content": system_prompt}]
|
| 457 |
+
if new_summary:
|
| 458 |
+
optimized_payload.append({
|
| 459 |
+
"role": "system",
|
| 460 |
+
"content": f"Summary of earlier conversation context for your memory bank: {new_summary}",
|
| 461 |
+
})
|
| 462 |
+
optimized_payload.extend(session.get_history_for_api())
|
| 463 |
+
|
| 464 |
+
# ββ 3. Token Governor (mirrors /chat) βββββββββββββββββββββββββββββββββββββ
|
| 465 |
+
duration_minutes = (
|
| 466 |
+
(time.time() * 1000 - req.sessionStart) / 60000
|
| 467 |
+
) if req.sessionStart else 0
|
| 468 |
+
estimated_tokens = estimate_payload_tokens(optimized_payload)
|
| 469 |
+
max_response_tokens: Optional[int] = None
|
| 470 |
+
|
| 471 |
+
if duration_minutes >= DURATION_THRESHOLD_MINUTES or estimated_tokens > TOKEN_THRESHOLD:
|
| 472 |
+
logger.warning(
|
| 473 |
+
f"[stream] Token Governor triggered. "
|
| 474 |
+
f"Tokens={estimated_tokens}, Duration={duration_minutes:.1f}m"
|
| 475 |
+
)
|
| 476 |
+
cleaned_history = [
|
| 477 |
+
{"role": m["role"], "content": strip_formatting(m["content"])}
|
| 478 |
+
for m in session.get_history_for_api()
|
| 479 |
+
]
|
| 480 |
+
concise_control = {
|
| 481 |
+
"role": "system",
|
| 482 |
+
"content": (
|
| 483 |
+
"Token Governor Active: Reply ultra-concisely. "
|
| 484 |
+
"No markdown, no filler. 1-2 short sentences max."
|
| 485 |
+
),
|
| 486 |
+
}
|
| 487 |
+
short_sys = [
|
| 488 |
+
m for m in optimized_payload
|
| 489 |
+
if m.get("role") == "system" and len(m.get("content", "")) < 400
|
| 490 |
+
]
|
| 491 |
+
optimized_payload = [concise_control] + short_sys
|
| 492 |
+
if new_summary:
|
| 493 |
+
optimized_payload.append({
|
| 494 |
+
"role": "system",
|
| 495 |
+
"content": f"Summary of earlier conversation context for your memory bank: {new_summary}",
|
| 496 |
+
})
|
| 497 |
+
optimized_payload.extend(cleaned_history)
|
| 498 |
+
max_response_tokens = 120
|
| 499 |
+
|
| 500 |
+
# ββ 4. Model selection (mirrors /chat) ββββββββββββββββββββββββββββββββββββ
|
| 501 |
+
intent = await session.classify_intent(req.message, detected_language)
|
| 502 |
+
primary_model = (
|
| 503 |
+
MODEL_HEAVY
|
| 504 |
+
if (intent == "heavy" or needs70B(req.message, detected_language))
|
| 505 |
+
else MODEL_FAST
|
| 506 |
+
)
|
| 507 |
+
inference_params: Dict[str, Any] = {
|
| 508 |
+
"model": primary_model,
|
| 509 |
+
"messages": optimized_payload,
|
| 510 |
+
"temperature": 0.4,
|
| 511 |
+
"top_p": 0.95,
|
| 512 |
+
}
|
| 513 |
+
if max_response_tokens:
|
| 514 |
+
inference_params["max_tokens"] = max_response_tokens
|
| 515 |
+
|
| 516 |
+
# Resolve TTS gender from session (TTS Space accepts "female" | "male")
|
| 517 |
+
tts_gender = session.agent_gender if session.agent_gender in ("female", "male") else "female"
|
| 518 |
+
start_timestamp = time.time()
|
| 519 |
+
|
| 520 |
+
# ββ 5. SSE event generator ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 521 |
+
async def event_generator():
|
| 522 |
+
loop = asyncio.get_running_loop()
|
| 523 |
+
q: asyncio.Queue = asyncio.Queue()
|
| 524 |
+
full_text_parts: list[str] = []
|
| 525 |
+
buffer = ""
|
| 526 |
+
|
| 527 |
+
def _sse(data: dict) -> str:
|
| 528 |
+
"""Format a dict as an SSE data frame."""
|
| 529 |
+
return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
| 530 |
+
|
| 531 |
+
async def _synthesise_and_emit(sentence: str) -> Optional[str]:
|
| 532 |
+
"""
|
| 533 |
+
Fire TTS for one sentence.
|
| 534 |
+
Returns a ready-to-yield SSE audio event string, or None if TTS failed.
|
| 535 |
+
"""
|
| 536 |
+
audio_bytes = await _fire_tts(sentence, detected_language, tts_gender)
|
| 537 |
+
if audio_bytes:
|
| 538 |
+
return _sse({
|
| 539 |
+
"type": "audio",
|
| 540 |
+
"sentence": sentence,
|
| 541 |
+
"audio_b64": base64.b64encode(audio_bytes).decode("utf-8"),
|
| 542 |
+
"lang": detected_language,
|
| 543 |
+
})
|
| 544 |
+
return None
|
| 545 |
+
|
| 546 |
+
# Kick off the Groq streaming daemon thread
|
| 547 |
+
_start_groq_stream_thread(inference_params, q, loop)
|
| 548 |
+
|
| 549 |
+
try:
|
| 550 |
+
while True:
|
| 551 |
+
event_type, data = await q.get()
|
| 552 |
+
|
| 553 |
+
# ββ Groq stream error: attempt Fireworks non-stream fallback ββ
|
| 554 |
+
if event_type == "error":
|
| 555 |
+
if fireworks is not None:
|
| 556 |
+
logger.warning(
|
| 557 |
+
"[stream] Groq stream error β activating Fireworks fallback"
|
| 558 |
+
)
|
| 559 |
+
try:
|
| 560 |
+
fb_params = {**inference_params, "model": FALLBACK_MODEL_FIREWORKS}
|
| 561 |
+
fb_loop = asyncio.get_running_loop()
|
| 562 |
+
fb_resp = await fb_loop.run_in_executor(
|
| 563 |
+
None,
|
| 564 |
+
lambda: fireworks.chat.completions.create(**fb_params),
|
| 565 |
+
)
|
| 566 |
+
fallback_text = fb_resp.choices[0].message.content.strip()
|
| 567 |
+
full_text_parts.append(fallback_text)
|
| 568 |
+
yield _sse({"type": "token", "text": fallback_text})
|
| 569 |
+
# Dispatch TTS for each sentence in the fallback block
|
| 570 |
+
fb_sentences, _ = _extract_sentences(fallback_text + " ")
|
| 571 |
+
for sent in fb_sentences:
|
| 572 |
+
audio_event = await _synthesise_and_emit(sent)
|
| 573 |
+
if audio_event:
|
| 574 |
+
yield audio_event
|
| 575 |
+
except Exception as fb_exc:
|
| 576 |
+
logger.error(f"[stream] Fireworks fallback failed: {fb_exc}")
|
| 577 |
+
yield _sse({"type": "error", "detail": str(fb_exc)})
|
| 578 |
+
return
|
| 579 |
+
else:
|
| 580 |
+
yield _sse({"type": "error", "detail": data})
|
| 581 |
+
return
|
| 582 |
+
break
|
| 583 |
+
|
| 584 |
+
# ββ Stream finished: flush any trailing buffer content βββββββββ
|
| 585 |
+
elif event_type == "done":
|
| 586 |
+
remainder = buffer.strip()
|
| 587 |
+
if remainder:
|
| 588 |
+
full_text_parts.append(remainder)
|
| 589 |
+
yield _sse({"type": "token", "text": remainder})
|
| 590 |
+
audio_event = await _synthesise_and_emit(remainder)
|
| 591 |
+
if audio_event:
|
| 592 |
+
yield audio_event
|
| 593 |
+
break
|
| 594 |
+
|
| 595 |
+
# ββ Normal token: accumulate + detect sentence boundaries ββββββ
|
| 596 |
+
else:
|
| 597 |
+
token: str = data
|
| 598 |
+
full_text_parts.append(token)
|
| 599 |
+
yield _sse({"type": "token", "text": token})
|
| 600 |
+
buffer += token
|
| 601 |
+
|
| 602 |
+
completed_sentences, buffer = _extract_sentences(buffer)
|
| 603 |
+
for sentence in completed_sentences:
|
| 604 |
+
audio_event = await _synthesise_and_emit(sentence)
|
| 605 |
+
if audio_event:
|
| 606 |
+
yield audio_event
|
| 607 |
+
|
| 608 |
+
except asyncio.CancelledError:
|
| 609 |
+
logger.warning(
|
| 610 |
+
f"[stream] Client disconnected mid-stream: {session.session_id}"
|
| 611 |
+
)
|
| 612 |
+
return
|
| 613 |
+
|
| 614 |
+
# ββ 6. Finalise session state βββββββββββββββββββββββββββββββββββββββββ
|
| 615 |
+
full_text = "".join(full_text_parts).strip()
|
| 616 |
+
session.add_message("assistant", full_text)
|
| 617 |
+
|
| 618 |
+
# Hot-path CRM extraction (mirrors /chat)
|
| 619 |
+
if not session.caller_info.name:
|
| 620 |
+
extracted_name = extract_name_from_text(
|
| 621 |
+
req.message, language=detected_language
|
| 622 |
+
)
|
| 623 |
+
if extracted_name:
|
| 624 |
+
session.caller_info.name = extracted_name
|
| 625 |
+
|
| 626 |
+
if not session.caller_info.phone:
|
| 627 |
+
extracted_phone = extract_phone_from_text(req.message)
|
| 628 |
+
if extracted_phone:
|
| 629 |
+
session.caller_info.phone = extracted_phone
|
| 630 |
+
|
| 631 |
+
elapsed_ms = int((time.time() - start_timestamp) * 1000)
|
| 632 |
+
logger.info(
|
| 633 |
+
f"[stream] Complete. "
|
| 634 |
+
f"ID={session.session_id} | Model={primary_model} "
|
| 635 |
+
f"| Latency={elapsed_ms}ms | Lang={detected_language}"
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
# Final metadata event β same shape as /chat JSON response
|
| 639 |
+
yield _sse({
|
| 640 |
+
"type": "done",
|
| 641 |
+
"session_id": session.session_id,
|
| 642 |
+
"full_text": full_text,
|
| 643 |
+
"language": detected_language,
|
| 644 |
+
"language_locked": session.language_detector.is_locked(),
|
| 645 |
+
"turn_count": session.turn_count,
|
| 646 |
+
"caller_info": session.caller_info.to_dict(),
|
| 647 |
+
"activeSummary": new_summary,
|
| 648 |
+
"elapsed_ms": elapsed_ms,
|
| 649 |
+
})
|
| 650 |
+
|
| 651 |
+
return StreamingResponse(
|
| 652 |
+
event_generator(),
|
| 653 |
+
media_type="text/event-stream",
|
| 654 |
+
headers={
|
| 655 |
+
"Cache-Control": "no-cache",
|
| 656 |
+
"X-Accel-Buffering": "no", # Disable Nginx response buffering
|
| 657 |
+
"Connection": "keep-alive",
|
| 658 |
+
},
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
|
| 662 |
@app.post("/session/end")
|
| 663 |
async def end_session(req: EndSessionRequest):
|
| 664 |
"""Closes down session trackers and outputs permanent call summaries."""
|