Files
banban/talkingq-url/services/interruption_helper.py
2026-03-24 15:04:36 +08:00

79 lines
3.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import asyncio
from utils.logger import session_logger
from services.interrupt_handler import interrupt_handler
from services.tts_error_manager import tts_error_manager
class InterruptionHelper:
@staticmethod
async def notify_client_tts_error(device_id: str, session_id: str):
try:
if not await tts_error_manager.can_send_error(device_id, session_id):
session_logger.info(device_id, session_id, "已经发送过TTS_ERROR不再重复发送")
return False
from services.connection_manager import connection_manager
websocket = await connection_manager.get_connection(device_id)
if websocket and websocket.client_state.name == "CONNECTED":
await websocket.send_text("TTS_ERROR")
session_logger.info(device_id, session_id, "已通知客户端TTS错误")
return True
except Exception as e:
session_logger.error(device_id, session_id, f"发送TTS错误通知失败: {e}")
return False
@staticmethod
async def send_error_prompt_sound(device_id: str, session_id: str):
try:
from handlers.prompt_sound_handler import handle_prompt_sound_request
await handle_prompt_sound_request(device_id, "tts_error")
session_logger.info(device_id, session_id, "已发送错误提示音")
return True
except Exception as e:
session_logger.error(device_id, session_id, f"发送错误提示音失败: {e}")
return False
@staticmethod
async def handle_llm_timeout(device_id: str, session_id: str, llm_service=None):
session_key = (device_id, session_id)
await interrupt_handler.set_interrupt_state(session_key, True)
if llm_service and hasattr(llm_service, "closed"):
llm_service.closed = True
await InterruptionHelper.send_error_prompt_sound(device_id, session_id)
await InterruptionHelper.notify_client_tts_error(device_id, session_id)
session_logger.error(device_id, session_id, "已处理LLM超时")
@staticmethod
async def register_queue_cleanup(session_key: tuple, queue: asyncio.Queue):
if queue is None:
return
async def cleanup_queue():
try:
await queue.put(None)
while not queue.empty():
try:
queue.get_nowait()
queue.task_done()
except asyncio.QueueEmpty:
break
device_id, session_id = session_key
session_logger.info(device_id, session_id, "队列已清空")
except Exception as e:
device_id, session_id = session_key
session_logger.error(device_id, session_id, f"清空队列时出错: {e}")
await interrupt_handler.register_cleanup_handler(
session_key,
cleanup_queue,
priority=interrupt_handler.PRIORITY["QUEUE_CLEANUP"],
)