feat: implement logging and telemetry for enhanced observability
This commit is contained in:
+70
-39
@@ -22,6 +22,8 @@ import httpx
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from app.tts_cache import CacheIOError, TTSCache
|
||||
from app.telemetry import time_span, trace_span
|
||||
from app.logging_config import setup_logging, shutdown_logging, MAX_LOG_FILE_SIZE, BACKUP_COUNT
|
||||
from app.knowledge import KnowledgeBase, format_knowledge_context, resolve_knowledge_dir
|
||||
|
||||
load_dotenv()
|
||||
@@ -31,9 +33,25 @@ tts_cache = TTSCache(cache_dir=".tts_cache")
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
PROJECT_DIR = os.path.dirname(BASE_DIR)
|
||||
STATIC_DIR = os.path.join(BASE_DIR, "static")
|
||||
|
||||
logger = logging.getLogger("simple_call_center")
|
||||
|
||||
app = FastAPI(title="Simple Call Center")
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Startup: Initialize logging once with all configuration settings
|
||||
is_json = os.getenv("LOG_FORMAT", "text").lower() == "json"
|
||||
setup_logging(
|
||||
level=logging.INFO,
|
||||
json_format=is_json,
|
||||
log_file_path="logs/waterfall.log",
|
||||
max_bytes=MAX_LOG_FILE_SIZE,
|
||||
backup_count=BACKUP_COUNT,
|
||||
)
|
||||
yield
|
||||
# Shutdown: Cleanly flush queue to file on exit
|
||||
shutdown_logging()
|
||||
|
||||
app = FastAPI(title="Simple Call Center", lifespan=lifespan)
|
||||
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
|
||||
DEDUPLICATE_TRANSCRIPT_WINDOW_SECS = 4.0
|
||||
@@ -708,7 +726,8 @@ class VoiceSession:
|
||||
await self.respond_to_user(text)
|
||||
finally:
|
||||
self.mark_committed_transcript_done(text)
|
||||
|
||||
|
||||
@trace_span("VoiceSession.respond_to_user")
|
||||
async def respond_to_user(self, user_text: str) -> None:
|
||||
if openai_client is None:
|
||||
await self.send_json({"type": "error", "message": "OpenAI client is not configured."})
|
||||
@@ -749,15 +768,16 @@ class VoiceSession:
|
||||
if message.get("role") == "user"
|
||||
)
|
||||
retrieval_query = f"{retrieval_query} {user_text}".strip()
|
||||
kb_hits = (
|
||||
knowledge_base.search(
|
||||
retrieval_query,
|
||||
limit=settings.local_kb_max_results,
|
||||
min_score=settings.local_kb_min_score,
|
||||
with trace_span("knowledge_base_search"):
|
||||
kb_hits = (
|
||||
knowledge_base.search(
|
||||
retrieval_query,
|
||||
limit=settings.local_kb_max_results,
|
||||
min_score=settings.local_kb_min_score,
|
||||
)
|
||||
if settings.local_kb_enabled
|
||||
else []
|
||||
)
|
||||
if settings.local_kb_enabled
|
||||
else []
|
||||
)
|
||||
kb_context = format_knowledge_context(kb_hits)
|
||||
kb_context = prepare_model_context_text(kb_context)
|
||||
if kb_hits:
|
||||
@@ -793,21 +813,29 @@ class VoiceSession:
|
||||
}
|
||||
if settings.openai_reasoning_effort:
|
||||
request["reasoning"] = {"effort": settings.openai_reasoning_effort}
|
||||
|
||||
async with time_span("openai_llm_stream"):
|
||||
stream_start = time.perf_counter()
|
||||
first_token_received = False
|
||||
|
||||
stream = await openai_client.responses.create(**request)
|
||||
async for event in stream:
|
||||
event_type = getattr(event, "type", "")
|
||||
if event_type == "response.output_text.delta":
|
||||
delta = getattr(event, "delta", "")
|
||||
if delta:
|
||||
answer_parts.append(delta)
|
||||
elif event_type == "error":
|
||||
await self.send_json(
|
||||
{"type": "error", "message": getattr(event, "message", "OpenAI stream error")}
|
||||
)
|
||||
|
||||
answer = polish_assistant_answer("".join(answer_parts), user_text, self.conversation_language)
|
||||
answer = humanize_assistant_answer(answer, user_text, self.conversation_language)
|
||||
stream = await openai_client.responses.create(**request)
|
||||
async for event in stream:
|
||||
event_type = getattr(event, "type", "")
|
||||
if event_type == "response.output_text.delta":
|
||||
if not first_token_received:
|
||||
ttft_ms = (time.perf_counter() - stream_start) * 1000
|
||||
logger.info("WATERFALL | │ ├── OpenAI TTFT: %.2fms", ttft_ms)
|
||||
first_token_received = True
|
||||
delta = getattr(event, "delta", "")
|
||||
if delta:
|
||||
answer_parts.append(delta)
|
||||
elif event_type == "error":
|
||||
await self.send_json(
|
||||
{"type": "error", "message": getattr(event, "message", "OpenAI stream error")}
|
||||
)
|
||||
async with time_span("post_process_answer"):
|
||||
answer = polish_assistant_answer("".join(answer_parts), user_text, self.conversation_language)
|
||||
answer = humanize_assistant_answer(answer, user_text, self.conversation_language)
|
||||
await self.emit_assistant_answer(user_text, answer, tts_queue, tts_language)
|
||||
except Exception as exc:
|
||||
await self.send_json({"type": "error", "message": f"OpenAI error: {exc}"})
|
||||
@@ -841,6 +869,7 @@ class VoiceSession:
|
||||
if answer and not settings.streaming_tts_enabled:
|
||||
await self.synthesize_tts_http(answer, tts_language)
|
||||
|
||||
@trace_span("ElevenLabs.synthesize_tts_http")
|
||||
async def synthesize_tts_http(self, text: str, language_code: str | None = None) -> None:
|
||||
voice_id = settings.elevenlabs_voice_id
|
||||
tts_language = resolve_tts_language(language_code)
|
||||
@@ -862,19 +891,20 @@ class VoiceSession:
|
||||
async with tts_cache.lock(key):
|
||||
# Check cache
|
||||
try:
|
||||
cached_audio = await tts_cache.get(**cache_params)
|
||||
if cached_audio:
|
||||
logger.info("Using cached TTS audio for text: %s", prepared_text[:30])
|
||||
await self.send_json(
|
||||
{
|
||||
"type": "tts_audio",
|
||||
"audio": base64.b64encode(cached_audio).decode("ascii"),
|
||||
"format": audio_format_label(output_format),
|
||||
"sample_rate": audio_sample_rate(output_format),
|
||||
"mime_type": audio_mime_type(output_format),
|
||||
}
|
||||
)
|
||||
return
|
||||
async with time_span("tts_cache_check"):
|
||||
cached_audio = await tts_cache.get(**cache_params)
|
||||
if cached_audio:
|
||||
logger.info("Using cached TTS audio for text: %s", prepared_text[:30])
|
||||
await self.send_json(
|
||||
{
|
||||
"type": "tts_audio",
|
||||
"audio": base64.b64encode(cached_audio).decode("ascii"),
|
||||
"format": audio_format_label(output_format),
|
||||
"sample_rate": audio_sample_rate(output_format),
|
||||
"mime_type": audio_mime_type(output_format),
|
||||
}
|
||||
)
|
||||
return
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to read TTS cache: %s", exc)
|
||||
|
||||
@@ -900,7 +930,7 @@ class VoiceSession:
|
||||
payload["language_code"] = tts_language
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=60.0) as client:
|
||||
async with httpx.AsyncClient(timeout=60.0) as client, time_span("elevenlabs_api_post"):
|
||||
response = await client.post(
|
||||
f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}",
|
||||
params=params,
|
||||
@@ -914,7 +944,8 @@ class VoiceSession:
|
||||
|
||||
# Isolated write: I/O disk failures will not disrupt returning audio to user
|
||||
try:
|
||||
await tts_cache.put(audio_data=response.content, **cache_params)
|
||||
async with time_span("tts_cache_write"):
|
||||
await tts_cache.put(audio_data=response.content, **cache_params)
|
||||
except CacheIOError as exc:
|
||||
logger.error("Failed to write TTS audio to cache: %s", exc)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user