From b4a02ec689f3f7176e4d4db8fe8bbb92dd8b3dd0 Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 26 Nov 2025 11:07:21 +0800 Subject: [PATCH] feat: report history --- main/xiaozhi-server/app.py | 7 +- .../config/live_agent_api_client.py | 169 ++++++++++++-- main/xiaozhi-server/core/connection.py | 24 +- .../core/handle/reportHandle.py | 217 ++++++++++-------- main/xiaozhi-server/custom_config.yaml | 1 + 5 files changed, 284 insertions(+), 134 deletions(-) diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py index bc6f0b545..5b3fc73d6 100644 --- a/main/xiaozhi-server/app.py +++ b/main/xiaozhi-server/app.py @@ -9,7 +9,7 @@ from core.utils.util import get_local_ip, validate_mcp_endpoint from core.http_server import SimpleHttpServer from core.websocket_server import WebSocketServer from core.utils.util import check_ffmpeg_installed - +from config.live_agent_api_client import init_live_agent_api, live_agent_api_safe_close TAG = __name__ logger = setup_logging() @@ -46,6 +46,9 @@ async def main(): check_ffmpeg_installed() config = load_config() + if config.get("read_config_from_live_agent_api", False): + init_live_agent_api(config) + # auth_key优先级:配置文件server.auth_key > manager-api.secret > 自动生成 # auth_key用于jwt认证,比如视觉分析接口的jwt认证、ota接口的token生成与websocket认证 # 获取配置文件中的auth_key @@ -122,6 +125,8 @@ async def main(): except asyncio.CancelledError: print("任务被取消,清理资源中...") finally: + if config.get("read_config_from_live_agent_api", False): + live_agent_api_safe_close() # 取消所有任务(关键修复点) stdin_task.cancel() ws_task.cancel() diff --git a/main/xiaozhi-server/config/live_agent_api_client.py b/main/xiaozhi-server/config/live_agent_api_client.py index 412a167d5..dcd326c6f 100644 --- a/main/xiaozhi-server/config/live_agent_api_client.py +++ b/main/xiaozhi-server/config/live_agent_api_client.py @@ -1,43 +1,104 @@ +""" +Live Agent API Client - Singleton HTTP client for live-agent-api +Features: +1. Singleton pattern ensures global unique httpx.Client instance +2. Connection pool reuse for better performance +3. Thread-safe for concurrent requests +""" + +import os import httpx from config.logger import setup_logging -from typing import Optional +from typing import Optional, List, Dict logger = setup_logging() -def get_agent_config_from_api(agent_id: str, config: dict) -> Optional[dict]: + +class LiveAgentApiClient: + """Singleton HTTP client for live-agent-api""" + _instance = None + _client: httpx.Client = None + _base_url: str = None + + def __new__(cls, config: dict = None): + """Singleton pattern ensures global unique instance""" + if cls._instance is None: + if config is None: + raise ValueError("Config required for first initialization") + cls._instance = super().__new__(cls) + cls._init_client(config) + return cls._instance + + @classmethod + def _init_client(cls, config: dict): + """Initialize persistent connection pool""" + live_api_config = config.get("live-agent-api", {}) + cls._base_url = live_api_config.get("url", "http://live-agent-api:8080/api/live_agent/v1") + timeout = live_api_config.get("timeout", 30) + + cls._client = httpx.Client( + base_url=cls._base_url, + headers={ + "User-Agent": f"XiaozhiServer/1.0 (PID:{os.getpid()})", + "Accept": "application/json", + "Content-Type": "application/json", + }, + timeout=timeout, + ) + logger.info(f"LiveAgentApiClient initialized: {cls._base_url}") + + @classmethod + def _request(cls, method: str, endpoint: str, **kwargs) -> dict: + """Send HTTP request and handle response""" + endpoint = endpoint.lstrip("/") + response = cls._client.request(method, endpoint, **kwargs) + response.raise_for_status() + return response.json() + + @classmethod + def safe_close(cls): + """Safely close connection pool""" + if cls._client: + cls._client.close() + cls._client = None + cls._instance = None + logger.info("LiveAgentApiClient closed") + + +def init_live_agent_api(config: dict): + """Initialize the singleton client (call once at startup)""" + LiveAgentApiClient(config) + + +def get_agent_config_from_api(agent_id: str, config: dict = None) -> Optional[dict]: """ Get agent configuration from live-agent-api Args: agent_id: Agent ID - config: System config containing live-agent-api URL + config: System config (optional if client already initialized) Returns: Agent config dict or None if failed """ - - live_api_config = config.get("live-agent-api", {}) - base_url = live_api_config.get("url", "http://live-agent-api:8080/api/live_agent/v1") - timeout = live_api_config.get("timeout", 10) - - url = f"{base_url}/internal/agents/{agent_id}/config" - try: - with httpx.Client(timeout=timeout) as client: - response = client.request("GET", url) - response.raise_for_status() - result = response.json() - - # Extract data from success_response format - if result.get("code") == 200 and "data" in result: - agent_config = result["data"] - logger.info(f"Successfully fetched agent config for agent_id={agent_id}") - return agent_config - else: - logger.error(f"Invalid response format from live-agent-api: {result}") + # Ensure client is initialized + if LiveAgentApiClient._instance is None: + if config is None: + logger.error("LiveAgentApiClient not initialized and no config provided") return None - + LiveAgentApiClient(config) + + result = LiveAgentApiClient._request("GET", f"/internal/agents/{agent_id}/config") + + if result.get("code") == 200 and "data" in result: + logger.info(f"Successfully fetched agent config for agent_id={agent_id}") + return result["data"] + else: + logger.error(f"Invalid response format from live-agent-api: {result}") + return None + except httpx.HTTPStatusError as e: if e.response.status_code == 404: logger.error(f"Agent not found: agent_id={agent_id}") @@ -46,4 +107,64 @@ def get_agent_config_from_api(agent_id: str, config: dict) -> Optional[dict]: return None except Exception as e: logger.error(f"Failed to fetch agent config for {agent_id}: {e}") - return None \ No newline at end of file + return None + + +def report_chat_message( + agent_id: str, + role: int, + content_items: List[Dict[str, str]], + config: dict = None +) -> Optional[dict]: + """ + Report chat message to live-agent-api + + Args: + agent_id: Agent ID + role: 1=user, 2=agent + content_items: List of message parts, format: + [ + {"message_type": "text", "message_content": "Hello"}, + {"message_type": "audio", "message_content": "base64_opus_data"}, + {"message_type": "image", "message_content": "s3_url"}, + {"message_type": "file", "message_content": "s3_url"} + ] + config: System config (optional if client already initialized) + + Returns: + Response dict or None if failed + """ + try: + # Ensure client is initialized + if LiveAgentApiClient._instance is None: + if config is None: + logger.error("LiveAgentApiClient not initialized and no config provided") + return None + LiveAgentApiClient(config) + + payload = { + "agent_id": agent_id, + "role": role, + "content": content_items + } + + result = LiveAgentApiClient._request("POST", "/chat/report", json=payload) + + if result.get("code") == 200: + logger.debug(f"Successfully reported message for agent_id={agent_id}, role={role}") + return result.get("data") + else: + logger.error(f"Failed to report message: {result}") + return None + + except httpx.HTTPStatusError as e: + logger.error(f"HTTP error reporting message: {e}, response: {e.response.text}") + return None + except Exception as e: + logger.error(f"Failed to report message for {agent_id}: {e}") + return None + + +def live_agent_api_safe_close(): + """Safe close for shutdown""" + LiveAgentApiClient.safe_close() diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 961ca6115..917b513d2 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -96,9 +96,10 @@ class ConnectionHandler: # 添加上报线程池 self.report_queue = queue.Queue() self.report_thread = None - # 未来可以通过修改此处,调节asr的上报和tts的上报,目前默认都开启 - self.report_asr_enable = self.read_config_from_api - self.report_tts_enable = self.read_config_from_api + # Enable report for both manager-api and live-agent-api modes + self._report_enabled = self.read_config_from_api or self.read_config_from_live_agent_api + self.report_asr_enable = self._report_enabled + self.report_tts_enable = self._report_enabled # 依赖的组件 self.vad = None @@ -500,8 +501,9 @@ class ConnectionHandler: self.logger.bind(tag=TAG).info("系统提示词已增强更新") def _init_report_threads(self): - """初始化ASR和TTS上报线程""" - if not self.read_config_from_api or self.need_bind: + """Initialize chat message report thread for live-agent-api""" + # Only enable for live-agent-api mode + if not self.read_config_from_live_agent_api or self.need_bind: return if self.chat_history_conf == 0: return @@ -510,7 +512,7 @@ class ConnectionHandler: target=self._report_worker, daemon=True ) self.report_thread.start() - self.logger.bind(tag=TAG).info("TTS上报线程已启动") + self.logger.bind(tag=TAG).info("Chat report thread started") def _initialize_tts(self): """ @@ -817,10 +819,13 @@ class ConnectionHandler: asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop) def _initialize_agent_config(self): - """initialize agent config""" + """initialize agent config from live-agent-api""" if not self.read_config_from_live_agent_api: return private_config = get_agent_config_from_api(self.agent_id, self.config) + if not private_config: + self.logger.bind(tag=TAG).error(f"Failed to get agent config for {self.agent_id}") + return # self.logger.bind(tag=TAG).info(f"private_config: {private_config}") # self.logger.bind(tag=TAG).info(f"self.config: {self.config}") self.config["TTS"]["FishSpeech"]["reference_id"] = private_config["voice_id"] @@ -829,6 +834,11 @@ class ConnectionHandler: self._voice_closing = private_config["voice_closing"] self._language = private_config["language"] + # Set chat history config for live-agent-api mode + # 0: disable, 1: text only, 2: text + audio + live_api_config = self.config.get("live-agent-api", {}) + self.chat_history_conf = live_api_config.get("chat_history_conf", 2) + init_llm, init_tts, init_memory, init_intent = ( True, True, diff --git a/main/xiaozhi-server/core/handle/reportHandle.py b/main/xiaozhi-server/core/handle/reportHandle.py index 7b30f79c0..116dc9fd3 100644 --- a/main/xiaozhi-server/core/handle/reportHandle.py +++ b/main/xiaozhi-server/core/handle/reportHandle.py @@ -1,149 +1,162 @@ """ -TTS上报功能已集成到ConnectionHandler类中。 +Report features: +1. Each connection has its own report queue and processing thread +2. Report thread lifecycle bound to connection object +3. Use ConnectionHandler.enqueue_tts_report method for reporting -上报功能包括: -1. 每个连接对象拥有自己的上报队列和处理线程 -2. 上报线程的生命周期与连接对象绑定 -3. 使用ConnectionHandler.enqueue_tts_report方法进行上报 - -具体实现请参考core/connection.py中的相关代码。 +See core/connection.py for implementation details. """ +import re import time +import base64 -import opuslib_next - -from config.manage_api_client import report as manage_report +from config.live_agent_api_client import report_chat_message TAG = __name__ +# Regex pattern to match emotion tags anywhere in text +# Format: (emotion) e.g., "(happy)", "(sincere)", "(curious)" +# Matches: optional whitespace + (word) + optional whitespace +EMOTION_TAG_PATTERN = re.compile(r'\s*\([a-zA-Z_]+\)\s*') -def report(conn, type, text, opus_data, report_time): - """执行聊天记录上报操作 +def strip_emotion_tags(text: str) -> str: + """ + Remove all emotion tags from TTS text. + + Emotion tags are in format: (emotion) typically at the start of sentences. + Examples: + "(happy) Hello!" -> "Hello!" + "(sincere) That's great. (curious) What next?" -> "That's great. What next?" + "Hello (happy) world" -> "Hello world" + Args: - conn: 连接对象 - type: 上报类型,1为用户,2为智能体 - text: 合成文本 - opus_data: opus音频数据 - report_time: 上报时间 + text: Text with potential emotion tags + + Returns: + Text with all emotion tags removed + """ + if not text: + return text + + # Remove all emotion tags from the text + result = EMOTION_TAG_PATTERN.sub(' ', text) + # Clean up multiple spaces and trim + result = re.sub(r'\s+', ' ', result) + return result.strip() + + +def report(conn, role, text, opus_data, report_time): + """Execute chat message report to live-agent-api + + Args: + conn: Connection object + role: Message role, 1=user, 2=agent + text: Message text content + opus_data: Opus audio data (list of opus packets) + report_time: Report timestamp (currently unused, kept for compatibility) """ try: + # Build content items for new API format + content_items = [] + + # Add text content if exists + if text: + content_items.append({ + "message_type": "text", + "message_content": text + }) + + # Add audio content if exists (convert opus packets to base64) if opus_data: - audio_data = opus_to_wav(conn, opus_data) - else: - audio_data = None - # 执行上报 - manage_report( - mac_address=conn.device_id, - session_id=conn.session_id, - chat_type=type, - content=text, - audio=audio_data, - report_time=report_time, + # Concatenate all opus packets + opus_bytes = b"".join(opus_data) + # Convert to base64 + audio_base64 = base64.b64encode(opus_bytes).decode("utf-8") + content_items.append({ + "message_type": "audio", + "message_content": audio_base64 + }) + + # Skip if no content to report + if not content_items: + conn.logger.bind(tag=TAG).warning("No content to report, skipping") + return + + # Report to live-agent-api (client already initialized at startup) + report_chat_message( + agent_id=conn.agent_id, + role=role, + content_items=content_items ) + except Exception as e: - conn.logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}") - - -def opus_to_wav(conn, opus_data): - """将Opus数据转换为WAV格式的字节流 - - Args: - output_dir: 输出目录(保留参数以保持接口兼容) - opus_data: opus音频数据 - - Returns: - bytes: WAV格式的音频数据 - """ - decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 - pcm_data = [] - - for opus_packet in opus_data: - try: - pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms - pcm_data.append(pcm_frame) - except opuslib_next.OpusError as e: - conn.logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) - - if not pcm_data: - raise ValueError("没有有效的PCM数据") - - # 创建WAV文件头 - pcm_data_bytes = b"".join(pcm_data) - num_samples = len(pcm_data_bytes) // 2 # 16-bit samples - - # WAV文件头 - wav_header = bytearray() - wav_header.extend(b"RIFF") # ChunkID - wav_header.extend((36 + len(pcm_data_bytes)).to_bytes(4, "little")) # ChunkSize - wav_header.extend(b"WAVE") # Format - wav_header.extend(b"fmt ") # Subchunk1ID - wav_header.extend((16).to_bytes(4, "little")) # Subchunk1Size - wav_header.extend((1).to_bytes(2, "little")) # AudioFormat (PCM) - wav_header.extend((1).to_bytes(2, "little")) # NumChannels - wav_header.extend((16000).to_bytes(4, "little")) # SampleRate - wav_header.extend((32000).to_bytes(4, "little")) # ByteRate - wav_header.extend((2).to_bytes(2, "little")) # BlockAlign - wav_header.extend((16).to_bytes(2, "little")) # BitsPerSample - wav_header.extend(b"data") # Subchunk2ID - wav_header.extend(len(pcm_data_bytes).to_bytes(4, "little")) # Subchunk2Size - - # 返回完整的WAV数据 - return bytes(wav_header) + pcm_data_bytes + conn.logger.bind(tag=TAG).error(f"Chat message report failed: {e}") def enqueue_tts_report(conn, text, opus_data): - if not conn.read_config_from_api or conn.need_bind or not conn.report_tts_enable: + """Enqueue TTS data for reporting (Agent message) + + Args: + conn: Connection object + text: Synthesized text (may contain emotion tags) + opus_data: Opus audio data (list of opus packets) + """ + # Check if reporting is enabled for live-agent-api mode + if not conn.read_config_from_live_agent_api or conn.need_bind or not conn.report_tts_enable: return if conn.chat_history_conf == 0: return - """将TTS数据加入上报队列 - - Args: - conn: 连接对象 - text: 合成文本 - opus_data: opus音频数据 - """ + try: - # 使用连接对象的队列,传入文本和二进制数据而非文件路径 + # Remove emotion tags from text before reporting + clean_text = strip_emotion_tags(text) + + # Use connection's queue, pass text and binary data if conn.chat_history_conf == 2: - conn.report_queue.put((2, text, opus_data, int(time.time()))) + # Report with audio + conn.report_queue.put((2, clean_text, opus_data, int(time.time()))) conn.logger.bind(tag=TAG).debug( - f"TTS数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} " + f"TTS data enqueued: agent_id={conn.agent_id}, audio packets: {len(opus_data)}" ) else: - conn.report_queue.put((2, text, None, int(time.time()))) + # Report without audio (text only) + conn.report_queue.put((2, clean_text, None, int(time.time()))) conn.logger.bind(tag=TAG).debug( - f"TTS数据已加入上报队列: {conn.device_id}, 不上报音频" + f"TTS data enqueued: agent_id={conn.agent_id}, no audio" ) except Exception as e: - conn.logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}") + conn.logger.bind(tag=TAG).error(f"Failed to enqueue TTS report: {text}, {e}") def enqueue_asr_report(conn, text, opus_data): - if not conn.read_config_from_api or conn.need_bind or not conn.report_asr_enable: + """Enqueue ASR data for reporting (User message) + + Args: + conn: Connection object + text: Recognized text + opus_data: Opus audio data (list of opus packets) + """ + # Check if reporting is enabled for live-agent-api mode + if not conn.read_config_from_live_agent_api or conn.need_bind or not conn.report_asr_enable: return if conn.chat_history_conf == 0: return - """将ASR数据加入上报队列 - - Args: - conn: 连接对象 - text: 合成文本 - opus_data: opus音频数据 - """ + try: - # 使用连接对象的队列,传入文本和二进制数据而非文件路径 + # Use connection's queue, pass text and binary data if conn.chat_history_conf == 2: + # Report with audio conn.report_queue.put((1, text, opus_data, int(time.time()))) conn.logger.bind(tag=TAG).debug( - f"ASR数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} " + f"ASR data enqueued: agent_id={conn.agent_id}, audio packets: {len(opus_data)}" ) else: + # Report without audio (text only) conn.report_queue.put((1, text, None, int(time.time()))) conn.logger.bind(tag=TAG).debug( - f"ASR数据已加入上报队列: {conn.device_id}, 不上报音频" + f"ASR data enqueued: agent_id={conn.agent_id}, no audio" ) except Exception as e: - conn.logger.bind(tag=TAG).debug(f"加入ASR上报队列失败: {text}, {e}") + conn.logger.bind(tag=TAG).debug(f"Failed to enqueue ASR report: {text}, {e}") diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml index 65f76b5c4..4777fdd20 100644 --- a/main/xiaozhi-server/custom_config.yaml +++ b/main/xiaozhi-server/custom_config.yaml @@ -42,6 +42,7 @@ manager-api: live-agent-api: url: http://live-agent-api:8080/api/live_agent/v1 + chat_history_conf: 2 # MySQL配置(用于聊天记录和记忆关联) mysql: