初始化SessionContext,创建会话上下文,暂时开始作为参数注入

This commit is contained in:
Chingfeng Li 2025-09-10 10:30:56 +08:00
parent bc829d9ef0
commit ed698757ad
12 changed files with 70 additions and 15 deletions

View file

@ -10,6 +10,8 @@ import threading
import traceback import traceback
import subprocess import subprocess
import websockets import websockets
from core.session.session_context import SessionContext
from core.utils.util import ( from core.utils.util import (
extract_json_from_string, extract_json_from_string,
check_vad_update, check_vad_update,
@ -157,6 +159,8 @@ class ConnectionHandler:
# 初始化提示词管理器 # 初始化提示词管理器
self.prompt_manager = PromptManager(config, self.logger) self.prompt_manager = PromptManager(config, self.logger)
self.session_context = SessionContext(self.session_id)
async def handle_connection(self, ws): async def handle_connection(self, ws):
try: try:
# 获取并验证headers # 获取并验证headers
@ -212,9 +216,13 @@ class ConnectionHandler:
# 异步初始化 # 异步初始化
self.executor.submit(self._initialize_components) self.executor.submit(self._initialize_components)
self.session_context.device_id = self.device_id
self.session_context.client_ip = self.client_ip
self.session_context.last_activity_time = self.last_activity_time
try: try:
async for message in self.websocket: async for message in self.websocket:
await self._route_message(message) await self._route_message(message, self.session_context)
except websockets.exceptions.ConnectionClosed: except websockets.exceptions.ConnectionClosed:
self.logger.bind(tag=TAG).info("客户端断开连接") self.logger.bind(tag=TAG).info("客户端断开连接")
@ -272,10 +280,10 @@ class ConnectionHandler:
f"保存记忆后关闭连接失败: {close_error}" f"保存记忆后关闭连接失败: {close_error}"
) )
async def _route_message(self, message): async def _route_message(self, message, session_context: SessionContext):
"""消息路由""" """消息路由"""
if isinstance(message, str): if isinstance(message, str):
await handleTextMessage(self, message) await handleTextMessage(self, message, session_context)
elif isinstance(message, bytes): elif isinstance(message, bytes):
if self.vad is None: if self.vad is None:
return return

View file

@ -2,6 +2,8 @@ import time
import json import json
import random import random
import asyncio import asyncio
from core.session.session_context import SessionContext
from core.utils.dialogue import Message from core.utils.dialogue import Message
from core.utils.util import audio_to_data from core.utils.util import audio_to_data
from core.providers.tts.dto.dto import SentenceType from core.providers.tts.dto.dto import SentenceType
@ -28,13 +30,14 @@ wakeup_words_config = WakeupWordsConfig()
_wakeup_response_lock = asyncio.Lock() _wakeup_response_lock = asyncio.Lock()
async def handleHelloMessage(conn, msg_json): async def handleHelloMessage(conn, msg_json, session_context: SessionContext):
"""处理hello消息""" """处理hello消息"""
audio_params = msg_json.get("audio_params") audio_params = msg_json.get("audio_params")
if audio_params: if audio_params:
format = audio_params.get("format") format = audio_params.get("format")
conn.logger.bind(tag=TAG).info(f"客户端音频格式: {format}") conn.logger.bind(tag=TAG).info(f"客户端音频格式: {format}")
conn.audio_format = format conn.audio_format = format
session_context.audio_format = conn.audio_format
conn.welcome_msg["audio_params"] = audio_params conn.welcome_msg["audio_params"] = audio_params
features = msg_json.get("features") features = msg_json.get("features")
if features: if features:
@ -43,6 +46,7 @@ async def handleHelloMessage(conn, msg_json):
if features.get("mcp"): if features.get("mcp"):
conn.logger.bind(tag=TAG).info("客户端支持MCP") conn.logger.bind(tag=TAG).info("客户端支持MCP")
conn.mcp_client = MCPClient() conn.mcp_client = MCPClient()
session_context.mcp_client = conn.mcp_client
# 发送初始化 # 发送初始化
asyncio.create_task(send_mcp_initialize_message(conn)) asyncio.create_task(send_mcp_initialize_message(conn))
# 发送mcp消息,获取tools列表 # 发送mcp消息,获取tools列表

View file

@ -1,5 +1,6 @@
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
from core.handle.textMessageProcessor import TextMessageProcessor from core.handle.textMessageProcessor import TextMessageProcessor
from core.session.session_context import SessionContext
TAG = __name__ TAG = __name__
@ -9,6 +10,6 @@ message_registry = TextMessageHandlerRegistry()
# 创建全局消息处理器实例 # 创建全局消息处理器实例
message_processor = TextMessageProcessor(message_registry) message_processor = TextMessageProcessor(message_registry)
async def handleTextMessage(conn, message): async def handleTextMessage(conn, message, session_context: SessionContext):
"""处理文本消息""" """处理文本消息"""
await message_processor.process_message(conn, message) await message_processor.process_message(conn, message, session_context)

View file

@ -3,6 +3,7 @@ from typing import Dict, Any
from core.handle.abortHandle import handleAbortMessage from core.handle.abortHandle import handleAbortMessage
from core.handle.textMessageHandler import TextMessageHandler from core.handle.textMessageHandler import TextMessageHandler
from core.handle.textMessageType import TextMessageType from core.handle.textMessageType import TextMessageType
from core.session.session_context import SessionContext
class AbortTextMessageHandler(TextMessageHandler): class AbortTextMessageHandler(TextMessageHandler):
@ -12,5 +13,5 @@ class AbortTextMessageHandler(TextMessageHandler):
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:
return TextMessageType.ABORT return TextMessageType.ABORT
async def handle(self, conn, msg_json: Dict[str, Any]) -> None: async def handle(self, conn, msg_json: Dict[str, Any], session_context: SessionContext) -> None:
await handleAbortMessage(conn) await handleAbortMessage(conn)

View file

@ -3,6 +3,7 @@ from typing import Dict, Any
from core.handle.helloHandle import handleHelloMessage from core.handle.helloHandle import handleHelloMessage
from core.handle.textMessageHandler import TextMessageHandler from core.handle.textMessageHandler import TextMessageHandler
from core.handle.textMessageType import TextMessageType from core.handle.textMessageType import TextMessageType
from core.session.session_context import SessionContext
class HelloTextMessageHandler(TextMessageHandler): class HelloTextMessageHandler(TextMessageHandler):
@ -12,5 +13,5 @@ class HelloTextMessageHandler(TextMessageHandler):
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:
return TextMessageType.HELLO return TextMessageType.HELLO
async def handle(self, conn, msg_json: Dict[str, Any]) -> None: async def handle(self, conn, msg_json: Dict[str, Any], session_context: SessionContext) -> None:
await handleHelloMessage(conn, msg_json) await handleHelloMessage(conn, msg_json, session_context)

View file

@ -4,6 +4,7 @@ from typing import Dict, Any
from core.handle.textMessageHandler import TextMessageHandler from core.handle.textMessageHandler import TextMessageHandler
from core.handle.textMessageType import TextMessageType from core.handle.textMessageType import TextMessageType
from core.providers.tools.device_iot import handleIotStatus, handleIotDescriptors from core.providers.tools.device_iot import handleIotStatus, handleIotDescriptors
from core.session.session_context import SessionContext
class IotTextMessageHandler(TextMessageHandler): class IotTextMessageHandler(TextMessageHandler):
@ -13,7 +14,7 @@ class IotTextMessageHandler(TextMessageHandler):
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:
return TextMessageType.IOT return TextMessageType.IOT
async def handle(self, conn, msg_json: Dict[str, Any]) -> None: async def handle(self, conn, msg_json: Dict[str, Any], session_context: SessionContext) -> None:
if "descriptors" in msg_json: if "descriptors" in msg_json:
asyncio.create_task(handleIotDescriptors(conn, msg_json["descriptors"])) asyncio.create_task(handleIotDescriptors(conn, msg_json["descriptors"]))
if "states" in msg_json: if "states" in msg_json:

View file

@ -6,6 +6,7 @@ from core.handle.reportHandle import enqueue_asr_report
from core.handle.sendAudioHandle import send_stt_message, send_tts_message from core.handle.sendAudioHandle import send_stt_message, send_tts_message
from core.handle.textMessageHandler import TextMessageHandler from core.handle.textMessageHandler import TextMessageHandler
from core.handle.textMessageType import TextMessageType from core.handle.textMessageType import TextMessageType
from core.session.session_context import SessionContext
from core.utils.util import remove_punctuation_and_length from core.utils.util import remove_punctuation_and_length
TAG = __name__ TAG = __name__
@ -17,7 +18,7 @@ class ListenTextMessageHandler(TextMessageHandler):
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:
return TextMessageType.LISTEN return TextMessageType.LISTEN
async def handle(self, conn, msg_json: Dict[str, Any]) -> None: async def handle(self, conn, msg_json: Dict[str, Any], session_context: SessionContext) -> None:
if "mode" in msg_json: if "mode" in msg_json:
conn.client_listen_mode = msg_json["mode"] conn.client_listen_mode = msg_json["mode"]
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(

View file

@ -4,6 +4,7 @@ from typing import Dict, Any
from core.handle.textMessageHandler import TextMessageHandler from core.handle.textMessageHandler import TextMessageHandler
from core.handle.textMessageType import TextMessageType from core.handle.textMessageType import TextMessageType
from core.providers.tools.device_mcp import handle_mcp_message from core.providers.tools.device_mcp import handle_mcp_message
from core.session.session_context import SessionContext
class McpTextMessageHandler(TextMessageHandler): class McpTextMessageHandler(TextMessageHandler):
@ -13,7 +14,7 @@ class McpTextMessageHandler(TextMessageHandler):
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:
return TextMessageType.MCP return TextMessageType.MCP
async def handle(self, conn, msg_json: Dict[str, Any]) -> None: async def handle(self, conn, msg_json: Dict[str, Any], session_context: SessionContext) -> None:
if "payload" in msg_json: if "payload" in msg_json:
asyncio.create_task( asyncio.create_task(
handle_mcp_message(conn, conn.mcp_client, msg_json["payload"]) handle_mcp_message(conn, conn.mcp_client, msg_json["payload"])

View file

@ -5,6 +5,7 @@ from typing import Dict, Any
from core.handle.textMessageHandler import TextMessageHandler from core.handle.textMessageHandler import TextMessageHandler
from core.handle.textMessageType import TextMessageType from core.handle.textMessageType import TextMessageType
from core.providers.tools.device_mcp import handle_mcp_message from core.providers.tools.device_mcp import handle_mcp_message
from core.session.session_context import SessionContext
TAG = __name__ TAG = __name__
@ -15,7 +16,7 @@ class ServerTextMessageHandler(TextMessageHandler):
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:
return TextMessageType.SERVER return TextMessageType.SERVER
async def handle(self, conn, msg_json: Dict[str, Any]) -> None: async def handle(self, conn, msg_json: Dict[str, Any], session_context: SessionContext) -> None:
# 如果配置是从API读取的,则需要验证secret # 如果配置是从API读取的,则需要验证secret
if not conn.read_config_from_api: if not conn.read_config_from_api:
return return

View file

@ -2,6 +2,7 @@ from abc import abstractmethod, ABC
from typing import Dict, Any from typing import Dict, Any
from core.handle.textMessageType import TextMessageType from core.handle.textMessageType import TextMessageType
from core.session.session_context import SessionContext
TAG = __name__ TAG = __name__
@ -10,7 +11,7 @@ class TextMessageHandler(ABC):
"""消息处理器抽象基类""" """消息处理器抽象基类"""
@abstractmethod @abstractmethod
async def handle(self, conn, msg_json: Dict[str, Any]) -> None: async def handle(self, conn, msg_json: Dict[str, Any], session_context: SessionContext) -> None:
"""处理消息的抽象方法""" """处理消息的抽象方法"""
pass pass

View file

@ -1,6 +1,7 @@
import json import json
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
from core.session.session_context import SessionContext
TAG = __name__ TAG = __name__
@ -11,12 +12,14 @@ class TextMessageProcessor:
def __init__(self, registry: TextMessageHandlerRegistry): def __init__(self, registry: TextMessageHandlerRegistry):
self.registry = registry self.registry = registry
async def process_message(self, conn, message: str) -> None: async def process_message(self, conn, message: str, session_context: SessionContext) -> None:
"""处理消息的主入口""" """处理消息的主入口"""
try: try:
# 解析JSON消息 # 解析JSON消息
msg_json = json.loads(message) msg_json = json.loads(message)
conn.logger.bind(tag=TAG).info(session_context.as_dict())
# 处理JSON消息 # 处理JSON消息
if isinstance(msg_json, dict): if isinstance(msg_json, dict):
message_type = msg_json.get("type") message_type = msg_json.get("type")

View file

@ -0,0 +1,32 @@
import uuid
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class SessionContext:
# Session唯一标识
session_id: str
# 设备基本信息
device_id: Optional[str] = None
client_ip: Optional[str] = None
# 客户端状态相关
client_abort: Optional[bool] = False
client_is_speaking: Optional[bool] = False
client_listen_mode: Optional[str] = "auto"
last_activity_time: float = 0.0
def __init__(self, session_id: Optional[str] = None):
self.session_id = session_id or str(uuid.uuid4())
def __setattr__(self, key, value):
if hasattr(self, "session_id") and key == "session_id":
raise AttributeError("session_id is read-only and cannot be modified")
super().__setattr__(key, value)
def as_dict(self) -> dict:
return self.__dict__.copy()