Merge pull request #13 from Plaud-AI/feat/demo

feat: Add multimodal support for image and file attachments
This commit is contained in:
Harold-Guo 2025-11-26 19:01:25 +08:00 committed by GitHub
commit 91ab88daff
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 583 additions and 212 deletions

View file

@ -12,11 +12,11 @@ from schemas.chat import (
ChatMessage, ChatMessage,
ChatMessagesListResponse ChatMessagesListResponse
) )
from utils.response import success_response
router = APIRouter() router = APIRouter()
@router.post("/report", response_model=ChatMessage) @router.post("/report", summary="Report a new chat message")
async def report_message( async def report_message(
request: ReportChatMessageRequest, request: ReportChatMessageRequest,
db: AsyncSession = Depends(get_db), db: AsyncSession = Depends(get_db),
@ -39,10 +39,11 @@ async def report_message(
Returns: Returns:
Created message with S3 URLs Created message with S3 URLs
""" """
return await chat_service.report_message(db=db, s3=s3, request=request) message = await chat_service.report_message(db=db, s3=s3, request=request)
return success_response(data=message)
@router.get("/{agent_id}/messages", response_model=ChatMessagesListResponse) @router.get("/{agent_id}/messages", summary="Get chat messages for an agent")
async def get_agent_messages( async def get_agent_messages(
agent_id: str, agent_id: str,
cursor: Optional[str] = Query(None, description="Message ID (ULID) cursor for pagination"), cursor: Optional[str] = Query(None, description="Message ID (ULID) cursor for pagination"),
@ -98,9 +99,9 @@ async def get_agent_messages(
include_audio=include_audio include_audio=include_audio
) )
return ChatMessagesListResponse( return success_response(data=ChatMessagesListResponse(
messages=messages, messages=messages,
next_cursor=next_cursor, next_cursor=next_cursor,
has_more=has_more has_more=has_more
) ))

View file

@ -125,6 +125,10 @@ async def get_my_voices(
name=voice.name, name=voice.name,
desc=voice.desc, desc=voice.desc,
created_at=voice.created_at, created_at=voice.created_at,
samples=[AudioSample(
text=voice.sample_text,
audio=voice.sample_url
)] if voice.sample_text and voice.sample_url else None
)) ))
# Build response # Build response

View file

@ -19,7 +19,7 @@ class ChatRole(enum.Enum):
class ReportChatMessageRequest(BaseModel): class ReportChatMessageRequest(BaseModel):
"""Request schema for reporting a chat message from dialogue server""" """Request schema for reporting a chat message from dialogue server"""
agent_id: str = Field(..., max_length=50, description="Agent ID") agent_id: str = Field(..., max_length=50, description="Agent ID")
role: ChatRole = Field(..., description="1: user, 2: agent") role: int = Field(..., ge=1, le=2, description="1: user, 2: agent")
content: List[MessageBody] = Field(..., description="Message content parts") content: List[MessageBody] = Field(..., description="Message content parts")
@ -27,7 +27,7 @@ class ChatMessage(BaseModel):
"""Response schema for a single chat message""" """Response schema for a single chat message"""
message_id: str message_id: str
agent_id: str agent_id: str
role: ChatRole role: int # 1: user, 2: agent
content: List[MessageBody] content: List[MessageBody]
created_at: datetime created_at: datetime

View file

@ -30,9 +30,8 @@ class VoiceAddRequest(BaseModel):
class AudioSample(BaseModel): class AudioSample(BaseModel):
"""Audio sample""" """Audio sample"""
title: str text: Optional[str] = None
text: str audio: Optional[str] = None
audio: str
class LiveAgentVoice(BaseModel): class LiveAgentVoice(BaseModel):
"""Voice Entity for Live Agent""" """Voice Entity for Live Agent"""

View file

@ -73,7 +73,7 @@ class ChatService:
db=db, db=db,
message_id=message_id, message_id=message_id,
agent_id=request.agent_id, agent_id=request.agent_id,
role=request.role.value, role=request.role,
content=content_dicts content=content_dicts
) )

View file

@ -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()

View file

@ -45,6 +45,8 @@ def load_config():
select_llm_module = config["selected_module"]["LLM"] select_llm_module = config["selected_module"]["LLM"]
if os.environ.get("REGION") == "LOCAL" and select_llm_module == "GroqLLM": if os.environ.get("REGION") == "LOCAL" and select_llm_module == "GroqLLM":
config["LLM"][select_llm_module]["api_key"] = os.environ.get("GROQ_API_KEY") config["LLM"][select_llm_module]["api_key"] = os.environ.get("GROQ_API_KEY")
if os.environ.get("REGION") == "LOCAL" and select_llm_module == "OpenaiLLM":
config["LLM"][select_llm_module]["api_key"] = os.environ.get("OPENAI_API_KEY")
# if custom_config.get("manager-api", {}).get("url"): # if custom_config.get("manager-api", {}).get("url"):
# config = get_config_from_api(custom_config) # config = get_config_from_api(custom_config)
# else: # else:

View file

@ -1,42 +1,103 @@
"""
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")
# 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}")
return None 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: except httpx.HTTPStatusError as e:
if e.response.status_code == 404: if e.response.status_code == 404:
@ -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()

View file

@ -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,
@ -872,9 +882,26 @@ class ConnectionHandler:
self.dialogue.update_system_message(self.prompt) self.dialogue.update_system_message(self.prompt)
def chat(self, query, depth=0): def chat(self, query, depth=0):
"""
Process user message and generate response
Args:
query: User message, can be:
- str: Text content
- List[Dict]: Multimodal content
depth: Recursive depth, for function calling
"""
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}") self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
self.llm_finish_task = False self.llm_finish_task = False
# extract text content for memory query
if isinstance(query, list):
# multimodal content: extract text part
text_parts = [item.get("text", "") for item in query if item.get("type") == "text"]
query_text = " ".join(text_parts)
else:
query_text = query
# 为最顶层时新建会话ID和发送FIRST请求 # 为最顶层时新建会话ID和发送FIRST请求
if depth == 0: if depth == 0:
self.sentence_id = str(uuid.uuid4().hex) self.sentence_id = str(uuid.uuid4().hex)
@ -894,11 +921,11 @@ class ConnectionHandler:
response_message = [] response_message = []
try: try:
# 使用带记忆的对话 # use dialogue with memory (use text for memory query)
memory_str = None memory_str = None
if self.memory is not None: if self.memory is not None:
future = asyncio.run_coroutine_threadsafe( future = asyncio.run_coroutine_threadsafe(
self.memory.query_memory(query), self.loop self.memory.query_memory(query_text), self.loop
) )
memory_str = future.result() memory_str = future.result()
@ -1111,7 +1138,8 @@ class ConnectionHandler:
if self.executor is None: if self.executor is None:
continue continue
# 提交任务到线程池 # 提交任务到线程池
self.executor.submit(self._process_report, *item) # self.executor.submit(self._process_report, *item)
self._process_report(*item)
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}") self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
except queue.Empty: except queue.Empty:
@ -1121,11 +1149,11 @@ class ConnectionHandler:
self.logger.bind(tag=TAG).info("聊天记录上报线程已退出") self.logger.bind(tag=TAG).info("聊天记录上报线程已退出")
def _process_report(self, type, text, audio_data, report_time): def _process_report(self, role, text, audio_data, report_time, attachments=None):
"""处理上报任务""" """处理上报任务"""
try: try:
# 执行上报(传入二进制数据) # 执行上报(传入二进制数据和附件)
report(self, type, text, audio_data, report_time) report(self, role, text, audio_data, report_time, attachments)
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"上报处理异常: {e}") self.logger.bind(tag=TAG).error(f"上报处理异常: {e}")
finally: finally:

View file

@ -7,6 +7,7 @@ from core.handle.intentHandler import handle_user_intent
from core.utils.output_counter import check_device_output_limit from core.utils.output_counter import check_device_output_limit
from core.handle.sendAudioHandle import send_stt_message, SentenceType from core.handle.sendAudioHandle import send_stt_message, SentenceType
from core.providers.tts.dto.dto import SentenceType, ContentType, TTSMessageDTO from core.providers.tts.dto.dto import SentenceType, ContentType, TTSMessageDTO
from typing import List, Dict, Any
TAG = __name__ TAG = __name__
@ -38,8 +39,16 @@ async def resume_vad_detection(conn):
conn.just_woken_up = False conn.just_woken_up = False
async def startToChat(conn, text): async def startToChat(conn, text: str, multimodal_content: List[Dict[str, Any]] | None = None):
# 检查输入是否是JSON格式(包含说话人信息) """
start to chat
Args:
conn: Session Connection
text: Text content
multimodal_content: Optional multimodal content
"""
# check if input is JSON format (contains speaker information)
speaker_name = None speaker_name = None
actual_text = text actual_text = text
@ -86,9 +95,13 @@ async def startToChat(conn, text):
# 如果意图已被处理,不再进行聊天 # 如果意图已被处理,不再进行聊天
return return
# 意图未被处理,继续常规聊天流程,使用实际文本内容 # 意图未被处理,继续常规聊天流程
await send_stt_message(conn, actual_text) await send_stt_message(conn, actual_text)
conn.executor.submit(conn.chat, actual_text)
# if multimodal content is provided, use it, otherwise use text
# in multimodal content, text is included in the content list
chat_content = multimodal_content if multimodal_content else actual_text
conn.executor.submit(conn.chat, chat_content)
async def no_voice_close_connect(conn, have_voice): async def no_voice_close_connect(conn, have_voice):

View file

@ -1,149 +1,180 @@
""" """
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
from typing import List, Dict, Any
from config.live_agent_api_client import report_chat_message
import opuslib_next
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
try: result = EMOTION_TAG_PATTERN.sub(' ', text)
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms # Clean up multiple spaces and trim
pcm_data.append(pcm_frame) result = re.sub(r'\s+', ' ', result)
except opuslib_next.OpusError as e: return result.strip()
conn.logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
if not pcm_data:
raise ValueError("没有有效的PCM数据")
# 创建WAV文件头 def report(conn, role, text: str, opus_data: List[bytes] | None = None, report_time: int = 0, attachments: List[Dict[str, Any]] | None = None):
pcm_data_bytes = b"".join(pcm_data) """Execute chat message report to live-agent-api
num_samples = len(pcm_data_bytes) // 2 # 16-bit samples
# WAV文件头 Args:
wav_header = bytearray() conn: Connection object
wav_header.extend(b"RIFF") # ChunkID role: Message role, 1=user, 2=agent
wav_header.extend((36 + len(pcm_data_bytes)).to_bytes(4, "little")) # ChunkSize text: Message text content
wav_header.extend(b"WAVE") # Format opus_data: Opus audio data (list of opus packets)
wav_header.extend(b"fmt ") # Subchunk1ID report_time: Report timestamp (currently unused, kept for compatibility)
wav_header.extend((16).to_bytes(4, "little")) # Subchunk1Size attachments: Optional list of attachments (multimodal content), format:
wav_header.extend((1).to_bytes(2, "little")) # AudioFormat (PCM) [
wav_header.extend((1).to_bytes(2, "little")) # NumChannels {"type": "image", "url": "https://..."},
wav_header.extend((16000).to_bytes(4, "little")) # SampleRate {"type": "file", "url": "https://..."}
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 try:
wav_header.extend(b"data") # Subchunk2ID # Build content items for new API format
wav_header.extend(len(pcm_data_bytes).to_bytes(4, "little")) # Subchunk2Size content_items = []
# 返回完整的WAV数据 # Add text content if exists
return bytes(wav_header) + pcm_data_bytes if text:
content_items.append({
"message_type": "text",
"message_content": text
})
# Add audio content if exists (convert opus packets to base64)
if opus_data:
# 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
})
# Add attachments if exists (images and files)
if attachments:
for attachment in attachments:
att_type = attachment.get("type")
url = attachment.get("url")
if att_type and url:
content_items.append({
"message_type": att_type, # "image" or "file"
"message_content": url
})
# 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"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 (TTS never has attachments)
conn.report_queue.put((2, clean_text, opus_data, int(time.time()), None))
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()), None))
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, attachments=None):
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, audio data, and attachments
# Queue format: (role, text, opus_data, timestamp, attachments)
if conn.chat_history_conf == 2: if conn.chat_history_conf == 2:
conn.report_queue.put((1, text, opus_data, int(time.time()))) # Report with audio
conn.report_queue.put((1, text, opus_data, int(time.time()), attachments))
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)}, attachments: {len(attachments) if attachments else 0}"
) )
else: else:
conn.report_queue.put((1, text, None, int(time.time()))) # Report without audio (text only, but may have attachments)
conn.report_queue.put((1, text, None, int(time.time()), attachments))
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, attachments: {len(attachments) if attachments else 0}"
) )
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}")

View file

@ -0,0 +1,60 @@
from typing import Dict, Any
from core.handle.textMessageHandler import TextMessageHandler
from core.handle.textMessageType import TextMessageType
from core.utils.dialogue import Message
TAG = __name__
class AttachmentTextMessageHandler(TextMessageHandler):
"""Attachment Message Handler - process image and file attachments"""
@property
def message_type(self) -> TextMessageType:
return TextMessageType.ATTACHMENT
async def handle(self, conn, msg_json: Dict[str, Any]) -> None:
"""
Process attachment message and store it in dialogue
消息格式:
{
"type": "attachment",
"attachment_type": "image" | "file",
"url": "https://..."
}
"""
attachment_type = msg_json.get("attachment_type") # "image" or "file"
url = msg_json.get("url")
if not attachment_type or not url:
conn.logger.bind(tag=TAG).warning(
f"Invalid attachment message: missing attachment_type or url"
)
return
# Build multimodal content format (OpenAI compatible)
if attachment_type == "image":
content = [
{
"type": "image",
"image_url": {"url": url}
}
]
else:
# File type: store as custom format, LLM layer needs special handling
content = [
{
"type": "file",
"file_url": {"url": url}
}
]
# Store directly in dialogue
conn.dialogue.put(Message(role="user", content=content))
conn.logger.bind(tag=TAG).info(
f"Attachment stored in dialogue: type={attachment_type}, url={url}"
)

View file

@ -1,5 +1,5 @@
import time import time
from typing import Dict, Any from typing import Dict, Any, List
from core.handle.receiveAudioHandle import handleAudioMessage, startToChat from core.handle.receiveAudioHandle import handleAudioMessage, startToChat
from core.handle.reportHandle import enqueue_asr_report from core.handle.reportHandle import enqueue_asr_report
@ -10,6 +10,54 @@ from core.utils.util import remove_punctuation_and_length
TAG = __name__ TAG = __name__
def build_multimodal_content(text: str, attachments: List[Dict[str, str]]) -> List[Dict[str, Any]]:
"""
Build multimodal content (Groq/OpenAI Responses API format)
Args:
text: Text content
attachments: Attachments list, format:
[
{"type": "image", "url": "https://..."},
{"type": "file", "url": "https://..."}
]
Returns:
Responses API compatible multimodal content:
[
{"type": "input_text", "text": "..."},
{"type": "input_image", "image_url": "https://..."},
{"type": "input_file", "file_url": "https://..."}
]
"""
content = []
# add attachments(images first, let LLM "see" them first)
for attachment in attachments:
att_type = attachment.get("type")
url = attachment.get("url")
if not att_type or not url:
continue
if att_type == "image":
content.append({
"type": "input_image",
"image_url": url
})
elif att_type == "file":
content.append({
"type": "input_file",
"file_url": url
})
# add text content at last
if text:
content.append({"type": "input_text", "text": text})
return content
class ListenTextMessageHandler(TextMessageHandler): class ListenTextMessageHandler(TextMessageHandler):
"""Listen消息处理器""" """Listen消息处理器"""
@ -57,7 +105,18 @@ class ListenTextMessageHandler(TextMessageHandler):
enqueue_asr_report(conn, "嘿,你好呀", []) enqueue_asr_report(conn, "嘿,你好呀", [])
await startToChat(conn, "嘿,你好呀") await startToChat(conn, "嘿,你好呀")
else: else:
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据) # check if there are attachments(eg. images, files) in text mode
enqueue_asr_report(conn, original_text, []) attachments = msg_json.get("attachments", [])
# 否则需要LLM对文字内容进行答复
await startToChat(conn, original_text) if attachments:
# build multimodal content
multimodal_content = build_multimodal_content(original_text, attachments)
# report text data with attachments
enqueue_asr_report(conn, original_text, [], attachments)
# use multimodal content to chat
await startToChat(conn, original_text, multimodal_content)
else:
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
enqueue_asr_report(conn, original_text, [])
# 否则需要LLM对文字内容进行答复
await startToChat(conn, original_text)

View file

@ -1,6 +1,7 @@
from typing import Dict, Optional from typing import Dict, Optional
from core.handle.textHandler.abortMessageHandler import AbortTextMessageHandler from core.handle.textHandler.abortMessageHandler import AbortTextMessageHandler
from core.handle.textHandler.attachmentMessageHandler import AttachmentTextMessageHandler
from core.handle.textHandler.helloMessageHandler import HelloTextMessageHandler from core.handle.textHandler.helloMessageHandler import HelloTextMessageHandler
from core.handle.textHandler.iotMessageHandler import IotTextMessageHandler from core.handle.textHandler.iotMessageHandler import IotTextMessageHandler
from core.handle.textHandler.listenMessageHandler import ListenTextMessageHandler from core.handle.textHandler.listenMessageHandler import ListenTextMessageHandler
@ -27,6 +28,7 @@ class TextMessageHandlerRegistry:
IotTextMessageHandler(), IotTextMessageHandler(),
McpTextMessageHandler(), McpTextMessageHandler(),
ServerTextMessageHandler(), ServerTextMessageHandler(),
AttachmentTextMessageHandler(),
] ]
for handler in handlers: for handler in handlers:

View file

@ -9,3 +9,4 @@ class TextMessageType(Enum):
IOT = "iot" IOT = "iot"
MCP = "mcp" MCP = "mcp"
SERVER = "server" SERVER = "server"
ATTACHMENT = "attachment"

View file

@ -1,9 +1,19 @@
import httpx import httpx
import openai import openai
from openai.types import CompletionUsage from openai.types import CompletionUsage
from openai.types.responses import Response
from openai.types.responses import (
ResponseOutputItemAddedEvent,
ResponseOutputItemDoneEvent,
ResponseTextDeltaEvent,
ResponseFunctionCallArgumentsDeltaEvent,
ResponseFunctionCallArgumentsDoneEvent
)
from config.logger import setup_logging from config.logger import setup_logging
from core.utils.util import check_model_key from core.utils.util import check_model_key
from core.providers.llm.base import LLMProviderBase from core.providers.llm.base import LLMProviderBase
from types import SimpleNamespace
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
@ -50,72 +60,84 @@ class LLMProvider(LLMProviderBase):
def response(self, session_id, dialogue, **kwargs): def response(self, session_id, dialogue, **kwargs):
try: try:
responses = self.client.chat.completions.create( responses = self.client.responses.create(
model=self.model_name, model=self.model_name,
messages=dialogue, input=dialogue,
stream=True, stream=True,
max_tokens=kwargs.get("max_tokens", self.max_tokens), max_output_tokens=kwargs.get("max_tokens", self.max_tokens),
temperature=kwargs.get("temperature", self.temperature), temperature=kwargs.get("temperature", self.temperature),
top_p=kwargs.get("top_p", self.top_p), top_p=kwargs.get("top_p", self.top_p),
frequency_penalty=kwargs.get(
"frequency_penalty", self.frequency_penalty
),
) )
is_active = True
for chunk in responses: for chunk in responses:
try: if isinstance(chunk, ResponseTextDeltaEvent):
# 检查是否存在有效的choice且content不为空 yield chunk.delta
delta = (
chunk.choices[0].delta
if getattr(chunk, "choices", None)
else None
)
content = delta.content if hasattr(delta, "content") else ""
except IndexError:
content = ""
if content:
# 处理标签跨多个chunk的情况
if "<think>" in content:
is_active = False
content = content.split("<think>")[0]
if "</think>" in content:
is_active = True
content = content.split("</think>")[-1]
if is_active:
yield content
except Exception as e: except Exception as e:
try: try:
error_msg = repr(e)[:200] error_msg = repr(e)
except: except:
error_msg = "encoding error" error_msg = "encoding error"
logger.bind(tag=TAG).error(f"Error in response generation: {error_msg}") logger.bind(tag=TAG).error(f"Error in response generation: {error_msg}")
def response_with_functions(self, session_id, dialogue, functions=None): def response_with_functions(self, session_id, dialogue, functions=None):
tools = None
if functions:
tools = []
for f in functions:
if f.get("type") == "function" and "function" in f:
func = f["function"]
tools.append({
"type": "function",
"name": func["name"],
"description": func.get("description", ""),
"parameters": func.get("parameters", {}),
})
else:
# 已经是 Responses API 格式,移除不支持的字段
tool = {k: v for k, v in f.items() if k != "strict"}
tools.append(tool)
try: try:
stream = self.client.chat.completions.create( # 构建请求参数
model=self.model_name, messages=dialogue, stream=True, tools=functions request_params = {
) "model": self.model_name,
"input": dialogue,
"stream": True,
"max_output_tokens": self.max_tokens,
"temperature": self.temperature,
"top_p": self.top_p,
}
# 只有在有 tools 时才添加 tools 参数
if tools:
request_params["tools"] = tools
stream = self.client.responses.create(**request_params)
for chunk in stream: for chunk in stream:
# 检查是否存在有效的choice且content不为空 if isinstance(chunk, ResponseOutputItemAddedEvent):
if getattr(chunk, "choices", None): if chunk.item.type == "function_call":
content = chunk.choices[0].delta.content yield None, [SimpleNamespace(
tool_calls = chunk.choices[0].delta.tool_calls id=chunk.item.call_id,
yield content, tool_calls type="function",
# 存在 CompletionUsage 消息时,生成 Token 消耗 log function=SimpleNamespace(
elif isinstance(getattr(chunk, "usage", None), CompletionUsage): name=chunk.item.name,
usage_info = getattr(chunk, "usage", None) ),
logger.bind(tag=TAG).debug( )]
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')}," elif isinstance(chunk, ResponseFunctionCallArgumentsDeltaEvent):
f"输出 {getattr(usage_info, 'completion_tokens', '未知')}," yield None, [SimpleNamespace(
f"共计 {getattr(usage_info, 'total_tokens', '未知')}" function=SimpleNamespace(
) arguments=chunk.item.arguments,
),
)]
elif isinstance(chunk, ResponseTextDeltaEvent):
yield chunk.delta, None
except Exception as e: except Exception as e:
try: try:
error_msg = repr(e)[:200] error_msg = repr(e)
except: except:
error_msg = "encoding error" error_msg = "encoding error"
logger.bind(tag=TAG).error(f"Error in function call streaming: {error_msg}") logger.bind(tag=TAG).error(f"Error in function call streaming: {error_msg}")

View file

@ -1,6 +1,6 @@
import uuid import uuid
import re import re
from typing import List, Dict from typing import List, Dict, Union, Any
from datetime import datetime from datetime import datetime
@ -8,11 +8,28 @@ class Message:
def __init__( def __init__(
self, self,
role: str, role: str,
content: str = None, content: Union[str, List[Dict[str, Any]]] = None,
uniq_id: str = None, uniq_id: str = None,
tool_calls=None, tool_calls=None,
tool_call_id=None, tool_call_id=None,
): ):
"""
Message in Live Agent System
Args:
role: Message role (system, user, assistant, tool)
content: Message content, can be:
- str: Text content
- List[Dict]: Multimodal content
For example: [
{"type": "text", "text": "Please, describe this image."},
{"type": "image", "image": {"url": "https://..."}},
{"type": "file", "file": {"url": "https://..."}}
]
uniq_id: Message unique identifier
tool_calls: Tool call information
tool_call_id: Tool call ID
"""
self.uniq_id = uniq_id if uniq_id is not None else str(uuid.uuid4()) self.uniq_id = uniq_id if uniq_id is not None else str(uuid.uuid4())
self.role = role self.role = role
self.content = content self.content = content

View file

@ -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:
@ -537,6 +538,11 @@ LLM:
model_name: openai/gpt-oss-20b model_name: openai/gpt-oss-20b
base_url: https://api.groq.com/openai/v1 base_url: https://api.groq.com/openai/v1
api_key: your groq api key api_key: your groq api key
OpenaiLLM:
type: openai
model_name: gpt-4o
base_url: https://api.openai.com/v1
api_key: your openai api key
OllamaLLM: OllamaLLM:
# 定义LLM API类型 # 定义LLM API类型
type: ollama type: ollama
@ -1064,7 +1070,7 @@ TTS:
selected_module: selected_module:
VAD: SileroVAD VAD: SileroVAD
ASR: GroqASR ASR: GroqASR
LLM: GroqLLM LLM: OpenaiLLM
VLLM: ChatGLMVLLM VLLM: ChatGLMVLLM
TTS: FishSpeech TTS: FishSpeech
Memory: memu Memory: memu