mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: report history
This commit is contained in:
parent
10ba28c2a8
commit
b4a02ec689
5 changed files with 284 additions and 134 deletions
|
|
@ -9,7 +9,7 @@ from core.utils.util import get_local_ip, validate_mcp_endpoint
|
||||||
from core.http_server import SimpleHttpServer
|
from core.http_server import SimpleHttpServer
|
||||||
from core.websocket_server import WebSocketServer
|
from core.websocket_server import WebSocketServer
|
||||||
from core.utils.util import check_ffmpeg_installed
|
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__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
@ -46,6 +46,9 @@ async def main():
|
||||||
check_ffmpeg_installed()
|
check_ffmpeg_installed()
|
||||||
config = load_config()
|
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优先级:配置文件server.auth_key > manager-api.secret > 自动生成
|
||||||
# auth_key用于jwt认证,比如视觉分析接口的jwt认证、ota接口的token生成与websocket认证
|
# auth_key用于jwt认证,比如视觉分析接口的jwt认证、ota接口的token生成与websocket认证
|
||||||
# 获取配置文件中的auth_key
|
# 获取配置文件中的auth_key
|
||||||
|
|
@ -122,6 +125,8 @@ async def main():
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
print("任务被取消,清理资源中...")
|
print("任务被取消,清理资源中...")
|
||||||
finally:
|
finally:
|
||||||
|
if config.get("read_config_from_live_agent_api", False):
|
||||||
|
live_agent_api_safe_close()
|
||||||
# 取消所有任务(关键修复点)
|
# 取消所有任务(关键修复点)
|
||||||
stdin_task.cancel()
|
stdin_task.cancel()
|
||||||
ws_task.cancel()
|
ws_task.cancel()
|
||||||
|
|
|
||||||
|
|
@ -1,39 +1,100 @@
|
||||||
|
"""
|
||||||
|
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
|
import httpx
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from typing import Optional
|
from typing import Optional, List, Dict
|
||||||
|
|
||||||
logger = setup_logging()
|
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
|
Get agent configuration from live-agent-api
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
agent_id: Agent ID
|
agent_id: Agent ID
|
||||||
config: System config containing live-agent-api URL
|
config: System config (optional if client already initialized)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Agent config dict or None if failed
|
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:
|
try:
|
||||||
with httpx.Client(timeout=timeout) as client:
|
# Ensure client is initialized
|
||||||
response = client.request("GET", url)
|
if LiveAgentApiClient._instance is None:
|
||||||
response.raise_for_status()
|
if config is None:
|
||||||
result = response.json()
|
logger.error("LiveAgentApiClient not initialized and no config provided")
|
||||||
|
return None
|
||||||
|
LiveAgentApiClient(config)
|
||||||
|
|
||||||
|
result = LiveAgentApiClient._request("GET", f"/internal/agents/{agent_id}/config")
|
||||||
|
|
||||||
# Extract data from success_response format
|
|
||||||
if result.get("code") == 200 and "data" in result:
|
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}")
|
logger.info(f"Successfully fetched agent config for agent_id={agent_id}")
|
||||||
return agent_config
|
return result["data"]
|
||||||
else:
|
else:
|
||||||
logger.error(f"Invalid response format from live-agent-api: {result}")
|
logger.error(f"Invalid response format from live-agent-api: {result}")
|
||||||
return None
|
return None
|
||||||
|
|
@ -47,3 +108,63 @@ def get_agent_config_from_api(agent_id: str, config: dict) -> Optional[dict]:
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to fetch agent config for {agent_id}: {e}")
|
logger.error(f"Failed to fetch agent config for {agent_id}: {e}")
|
||||||
return None
|
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()
|
||||||
|
|
|
||||||
|
|
@ -96,9 +96,10 @@ class ConnectionHandler:
|
||||||
# 添加上报线程池
|
# 添加上报线程池
|
||||||
self.report_queue = queue.Queue()
|
self.report_queue = queue.Queue()
|
||||||
self.report_thread = None
|
self.report_thread = None
|
||||||
# 未来可以通过修改此处,调节asr的上报和tts的上报,目前默认都开启
|
# Enable report for both manager-api and live-agent-api modes
|
||||||
self.report_asr_enable = self.read_config_from_api
|
self._report_enabled = self.read_config_from_api or self.read_config_from_live_agent_api
|
||||||
self.report_tts_enable = self.read_config_from_api
|
self.report_asr_enable = self._report_enabled
|
||||||
|
self.report_tts_enable = self._report_enabled
|
||||||
|
|
||||||
# 依赖的组件
|
# 依赖的组件
|
||||||
self.vad = None
|
self.vad = None
|
||||||
|
|
@ -500,8 +501,9 @@ class ConnectionHandler:
|
||||||
self.logger.bind(tag=TAG).info("系统提示词已增强更新")
|
self.logger.bind(tag=TAG).info("系统提示词已增强更新")
|
||||||
|
|
||||||
def _init_report_threads(self):
|
def _init_report_threads(self):
|
||||||
"""初始化ASR和TTS上报线程"""
|
"""Initialize chat message report thread for live-agent-api"""
|
||||||
if not self.read_config_from_api or self.need_bind:
|
# Only enable for live-agent-api mode
|
||||||
|
if not self.read_config_from_live_agent_api or self.need_bind:
|
||||||
return
|
return
|
||||||
if self.chat_history_conf == 0:
|
if self.chat_history_conf == 0:
|
||||||
return
|
return
|
||||||
|
|
@ -510,7 +512,7 @@ class ConnectionHandler:
|
||||||
target=self._report_worker, daemon=True
|
target=self._report_worker, daemon=True
|
||||||
)
|
)
|
||||||
self.report_thread.start()
|
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):
|
def _initialize_tts(self):
|
||||||
"""
|
"""
|
||||||
|
|
@ -817,10 +819,13 @@ class ConnectionHandler:
|
||||||
asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop)
|
asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop)
|
||||||
|
|
||||||
def _initialize_agent_config(self):
|
def _initialize_agent_config(self):
|
||||||
"""initialize agent config"""
|
"""initialize agent config from live-agent-api"""
|
||||||
if not self.read_config_from_live_agent_api:
|
if not self.read_config_from_live_agent_api:
|
||||||
return
|
return
|
||||||
private_config = get_agent_config_from_api(self.agent_id, self.config)
|
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"private_config: {private_config}")
|
||||||
# self.logger.bind(tag=TAG).info(f"self.config: {self.config}")
|
# self.logger.bind(tag=TAG).info(f"self.config: {self.config}")
|
||||||
self.config["TTS"]["FishSpeech"]["reference_id"] = private_config["voice_id"]
|
self.config["TTS"]["FishSpeech"]["reference_id"] = private_config["voice_id"]
|
||||||
|
|
@ -829,6 +834,11 @@ class ConnectionHandler:
|
||||||
self._voice_closing = private_config["voice_closing"]
|
self._voice_closing = private_config["voice_closing"]
|
||||||
self._language = private_config["language"]
|
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 = (
|
init_llm, init_tts, init_memory, init_intent = (
|
||||||
True,
|
True,
|
||||||
True,
|
True,
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
||||||
上报功能包括:
|
See core/connection.py for implementation details.
|
||||||
1. 每个连接对象拥有自己的上报队列和处理线程
|
|
||||||
2. 上报线程的生命周期与连接对象绑定
|
|
||||||
3. 使用ConnectionHandler.enqueue_tts_report方法进行上报
|
|
||||||
|
|
||||||
具体实现请参考core/connection.py中的相关代码。
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
import time
|
import time
|
||||||
|
import base64
|
||||||
|
|
||||||
import opuslib_next
|
from config.live_agent_api_client import report_chat_message
|
||||||
|
|
||||||
from config.manage_api_client import report as manage_report
|
|
||||||
|
|
||||||
TAG = __name__
|
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):
|
|
||||||
"""执行聊天记录上报操作
|
|
||||||
|
|
||||||
Args:
|
def strip_emotion_tags(text: str) -> str:
|
||||||
conn: 连接对象
|
|
||||||
type: 上报类型,1为用户,2为智能体
|
|
||||||
text: 合成文本
|
|
||||||
opus_data: opus音频数据
|
|
||||||
report_time: 上报时间
|
|
||||||
"""
|
"""
|
||||||
try:
|
Remove all emotion tags from TTS text.
|
||||||
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,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
conn.logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}")
|
|
||||||
|
|
||||||
|
Emotion tags are in format: (emotion) typically at the start of sentences.
|
||||||
def opus_to_wav(conn, opus_data):
|
Examples:
|
||||||
"""将Opus数据转换为WAV格式的字节流
|
"(happy) Hello!" -> "Hello!"
|
||||||
|
"(sincere) That's great. (curious) What next?" -> "That's great. What next?"
|
||||||
|
"Hello (happy) world" -> "Hello world"
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
output_dir: 输出目录(保留参数以保持接口兼容)
|
text: Text with potential emotion tags
|
||||||
opus_data: opus音频数据
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bytes: WAV格式的音频数据
|
Text with all emotion tags removed
|
||||||
"""
|
"""
|
||||||
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道
|
if not text:
|
||||||
pcm_data = []
|
return text
|
||||||
|
|
||||||
for opus_packet in opus_data:
|
# 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:
|
try:
|
||||||
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
|
# Build content items for new API format
|
||||||
pcm_data.append(pcm_frame)
|
content_items = []
|
||||||
except opuslib_next.OpusError as e:
|
|
||||||
conn.logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
|
|
||||||
|
|
||||||
if not pcm_data:
|
# Add text content if exists
|
||||||
raise ValueError("没有有效的PCM数据")
|
if text:
|
||||||
|
content_items.append({
|
||||||
|
"message_type": "text",
|
||||||
|
"message_content": text
|
||||||
|
})
|
||||||
|
|
||||||
# 创建WAV文件头
|
# Add audio content if exists (convert opus packets to base64)
|
||||||
pcm_data_bytes = b"".join(pcm_data)
|
if opus_data:
|
||||||
num_samples = len(pcm_data_bytes) // 2 # 16-bit samples
|
# 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
|
||||||
|
})
|
||||||
|
|
||||||
# WAV文件头
|
# Skip if no content to report
|
||||||
wav_header = bytearray()
|
if not content_items:
|
||||||
wav_header.extend(b"RIFF") # ChunkID
|
conn.logger.bind(tag=TAG).warning("No content to report, skipping")
|
||||||
wav_header.extend((36 + len(pcm_data_bytes)).to_bytes(4, "little")) # ChunkSize
|
return
|
||||||
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数据
|
# Report to live-agent-api (client already initialized at startup)
|
||||||
return bytes(wav_header) + pcm_data_bytes
|
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"Chat message report failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
def enqueue_tts_report(conn, text, opus_data):
|
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
|
return
|
||||||
if conn.chat_history_conf == 0:
|
if conn.chat_history_conf == 0:
|
||||||
return
|
return
|
||||||
"""将TTS数据加入上报队列
|
|
||||||
|
|
||||||
Args:
|
|
||||||
conn: 连接对象
|
|
||||||
text: 合成文本
|
|
||||||
opus_data: opus音频数据
|
|
||||||
"""
|
|
||||||
try:
|
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:
|
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(
|
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:
|
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(
|
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:
|
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):
|
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
|
return
|
||||||
if conn.chat_history_conf == 0:
|
if conn.chat_history_conf == 0:
|
||||||
return
|
return
|
||||||
"""将ASR数据加入上报队列
|
|
||||||
|
|
||||||
Args:
|
|
||||||
conn: 连接对象
|
|
||||||
text: 合成文本
|
|
||||||
opus_data: opus音频数据
|
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
# 使用连接对象的队列,传入文本和二进制数据而非文件路径
|
# Use connection's queue, pass text and binary data
|
||||||
if conn.chat_history_conf == 2:
|
if conn.chat_history_conf == 2:
|
||||||
|
# Report with audio
|
||||||
conn.report_queue.put((1, text, opus_data, int(time.time())))
|
conn.report_queue.put((1, text, opus_data, int(time.time())))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
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:
|
else:
|
||||||
|
# Report without audio (text only)
|
||||||
conn.report_queue.put((1, text, None, int(time.time())))
|
conn.report_queue.put((1, text, None, int(time.time())))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
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:
|
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}")
|
||||||
|
|
|
||||||
|
|
@ -42,6 +42,7 @@ manager-api:
|
||||||
|
|
||||||
live-agent-api:
|
live-agent-api:
|
||||||
url: http://live-agent-api:8080/api/live_agent/v1
|
url: http://live-agent-api:8080/api/live_agent/v1
|
||||||
|
chat_history_conf: 2
|
||||||
|
|
||||||
# MySQL配置(用于聊天记录和记忆关联)
|
# MySQL配置(用于聊天记录和记忆关联)
|
||||||
mysql:
|
mysql:
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue