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,
ChatMessagesListResponse
)
from utils.response import success_response
router = APIRouter()
@router.post("/report", response_model=ChatMessage)
@router.post("/report", summary="Report a new chat message")
async def report_message(
request: ReportChatMessageRequest,
db: AsyncSession = Depends(get_db),
@ -39,10 +39,11 @@ async def report_message(
Returns:
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(
agent_id: str,
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
)
return ChatMessagesListResponse(
return success_response(data=ChatMessagesListResponse(
messages=messages,
next_cursor=next_cursor,
has_more=has_more
)
))

View file

@ -125,6 +125,10 @@ async def get_my_voices(
name=voice.name,
desc=voice.desc,
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

View file

@ -19,7 +19,7 @@ class ChatRole(enum.Enum):
class ReportChatMessageRequest(BaseModel):
"""Request schema for reporting a chat message from dialogue server"""
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")
@ -27,7 +27,7 @@ class ChatMessage(BaseModel):
"""Response schema for a single chat message"""
message_id: str
agent_id: str
role: ChatRole
role: int # 1: user, 2: agent
content: List[MessageBody]
created_at: datetime

View file

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

View file

@ -73,7 +73,7 @@ class ChatService:
db=db,
message_id=message_id,
agent_id=request.agent_id,
role=request.role.value,
role=request.role,
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.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()

View file

@ -45,6 +45,8 @@ def load_config():
select_llm_module = config["selected_module"]["LLM"]
if os.environ.get("REGION") == "LOCAL" and select_llm_module == "GroqLLM":
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"):
# config = get_config_from_api(custom_config)
# else:

View file

@ -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
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_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,
@ -872,9 +882,26 @@ class ConnectionHandler:
self.dialogue.update_system_message(self.prompt)
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.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请求
if depth == 0:
self.sentence_id = str(uuid.uuid4().hex)
@ -894,11 +921,11 @@ class ConnectionHandler:
response_message = []
try:
# 使用带记忆的对话
# use dialogue with memory (use text for memory query)
memory_str = None
if self.memory is not None:
future = asyncio.run_coroutine_threadsafe(
self.memory.query_memory(query), self.loop
self.memory.query_memory(query_text), self.loop
)
memory_str = future.result()
@ -1111,7 +1138,8 @@ class ConnectionHandler:
if self.executor is None:
continue
# 提交任务到线程池
self.executor.submit(self._process_report, *item)
# self.executor.submit(self._process_report, *item)
self._process_report(*item)
except Exception as e:
self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
except queue.Empty:
@ -1121,11 +1149,11 @@ class ConnectionHandler:
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:
# 执行上报(传入二进制数据)
report(self, type, text, audio_data, report_time)
# 执行上报(传入二进制数据和附件)
report(self, role, text, audio_data, report_time, attachments)
except Exception as e:
self.logger.bind(tag=TAG).error(f"上报处理异常: {e}")
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.handle.sendAudioHandle import send_stt_message, SentenceType
from core.providers.tts.dto.dto import SentenceType, ContentType, TTSMessageDTO
from typing import List, Dict, Any
TAG = __name__
@ -38,8 +39,16 @@ async def resume_vad_detection(conn):
conn.just_woken_up = False
async def startToChat(conn, text):
# 检查输入是否是JSON格式(包含说话人信息)
async def startToChat(conn, text: str, multimodal_content: List[Dict[str, Any]] | None = None):
"""
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
actual_text = text
@ -86,9 +95,13 @@ async def startToChat(conn, text):
# 如果意图已被处理,不再进行聊天
return
# 意图未被处理,继续常规聊天流程,使用实际文本内容
# 意图未被处理,继续常规聊天流程
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):

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
上报功能包括:
1. 每个连接对象拥有自己的上报队列和处理线程
2. 上报线程的生命周期与连接对象绑定
3. 使用ConnectionHandler.enqueue_tts_report方法进行上报
具体实现请参考core/connection.py中的相关代码。
See core/connection.py for implementation details.
"""
import re
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__
# 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: str, opus_data: List[bytes] | None = None, report_time: int = 0, attachments: List[Dict[str, Any]] | None = None):
"""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)
attachments: Optional list of attachments (multimodal content), format:
[
{"type": "image", "url": "https://..."},
{"type": "file", "url": "https://..."}
]
"""
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
})
# 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"聊天记录上报失败: {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 (TTS never has attachments)
conn.report_queue.put((2, clean_text, opus_data, int(time.time()), None))
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()), None))
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:
def enqueue_asr_report(conn, text, opus_data, attachments=None):
"""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, audio data, and attachments
# Queue format: (role, text, opus_data, timestamp, attachments)
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(
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:
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(
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:
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
from typing import Dict, Any
from typing import Dict, Any, List
from core.handle.receiveAudioHandle import handleAudioMessage, startToChat
from core.handle.reportHandle import enqueue_asr_report
@ -10,6 +10,54 @@ from core.utils.util import remove_punctuation_and_length
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):
"""Listen消息处理器"""
@ -57,7 +105,18 @@ class ListenTextMessageHandler(TextMessageHandler):
enqueue_asr_report(conn, "嘿,你好呀", [])
await startToChat(conn, "嘿,你好呀")
else:
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
enqueue_asr_report(conn, original_text, [])
# 否则需要LLM对文字内容进行答复
await startToChat(conn, original_text)
# check if there are attachments(eg. images, files) in text mode
attachments = msg_json.get("attachments", [])
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 core.handle.textHandler.abortMessageHandler import AbortTextMessageHandler
from core.handle.textHandler.attachmentMessageHandler import AttachmentTextMessageHandler
from core.handle.textHandler.helloMessageHandler import HelloTextMessageHandler
from core.handle.textHandler.iotMessageHandler import IotTextMessageHandler
from core.handle.textHandler.listenMessageHandler import ListenTextMessageHandler
@ -27,6 +28,7 @@ class TextMessageHandlerRegistry:
IotTextMessageHandler(),
McpTextMessageHandler(),
ServerTextMessageHandler(),
AttachmentTextMessageHandler(),
]
for handler in handlers:

View file

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

View file

@ -1,9 +1,19 @@
import httpx
import openai
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 core.utils.util import check_model_key
from core.providers.llm.base import LLMProviderBase
from types import SimpleNamespace
TAG = __name__
logger = setup_logging()
@ -50,72 +60,84 @@ class LLMProvider(LLMProviderBase):
def response(self, session_id, dialogue, **kwargs):
try:
responses = self.client.chat.completions.create(
responses = self.client.responses.create(
model=self.model_name,
messages=dialogue,
input=dialogue,
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),
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:
try:
# 检查是否存在有效的choice且content不为空
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
if isinstance(chunk, ResponseTextDeltaEvent):
yield chunk.delta
except Exception as e:
try:
error_msg = repr(e)[:200]
error_msg = repr(e)
except:
error_msg = "encoding error"
logger.bind(tag=TAG).error(f"Error in response generation: {error_msg}")
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:
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:
# 检查是否存在有效的choice且content不为空
if getattr(chunk, "choices", None):
content = chunk.choices[0].delta.content
tool_calls = chunk.choices[0].delta.tool_calls
yield content, tool_calls
# 存在 CompletionUsage 消息时,生成 Token 消耗 log
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
usage_info = getattr(chunk, "usage", None)
logger.bind(tag=TAG).debug(
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
f"共计 {getattr(usage_info, 'total_tokens', '未知')}"
)
if isinstance(chunk, ResponseOutputItemAddedEvent):
if chunk.item.type == "function_call":
yield None, [SimpleNamespace(
id=chunk.item.call_id,
type="function",
function=SimpleNamespace(
name=chunk.item.name,
),
)]
elif isinstance(chunk, ResponseFunctionCallArgumentsDeltaEvent):
yield None, [SimpleNamespace(
function=SimpleNamespace(
arguments=chunk.item.arguments,
),
)]
elif isinstance(chunk, ResponseTextDeltaEvent):
yield chunk.delta, None
except Exception as e:
try:
error_msg = repr(e)[:200]
error_msg = repr(e)
except:
error_msg = "encoding error"
logger.bind(tag=TAG).error(f"Error in function call streaming: {error_msg}")

View file

@ -1,6 +1,6 @@
import uuid
import re
from typing import List, Dict
from typing import List, Dict, Union, Any
from datetime import datetime
@ -8,11 +8,28 @@ class Message:
def __init__(
self,
role: str,
content: str = None,
content: Union[str, List[Dict[str, Any]]] = None,
uniq_id: str = None,
tool_calls=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.role = role
self.content = content

View file

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