mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: multimodal
This commit is contained in:
parent
b4a02ec689
commit
ed75996f97
14 changed files with 300 additions and 83 deletions
|
|
@ -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
|
||||||
)
|
))
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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:
|
||||||
|
|
|
||||||
|
|
@ -882,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)
|
||||||
|
|
@ -904,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()
|
||||||
|
|
||||||
|
|
@ -1131,11 +1148,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:
|
||||||
|
|
|
||||||
|
|
@ -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):
|
||||||
|
|
|
||||||
|
|
@ -10,9 +10,10 @@ See core/connection.py for implementation details.
|
||||||
import re
|
import re
|
||||||
import time
|
import time
|
||||||
import base64
|
import base64
|
||||||
|
from typing import List, Dict, Any
|
||||||
from config.live_agent_api_client import report_chat_message
|
from config.live_agent_api_client import report_chat_message
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
# Regex pattern to match emotion tags anywhere in text
|
# Regex pattern to match emotion tags anywhere in text
|
||||||
|
|
@ -47,7 +48,7 @@ def strip_emotion_tags(text: str) -> str:
|
||||||
return result.strip()
|
return result.strip()
|
||||||
|
|
||||||
|
|
||||||
def report(conn, role, text, opus_data, report_time):
|
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
|
"""Execute chat message report to live-agent-api
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
|
|
@ -56,6 +57,11 @@ def report(conn, role, text, opus_data, report_time):
|
||||||
text: Message text content
|
text: Message text content
|
||||||
opus_data: Opus audio data (list of opus packets)
|
opus_data: Opus audio data (list of opus packets)
|
||||||
report_time: Report timestamp (currently unused, kept for compatibility)
|
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:
|
try:
|
||||||
# Build content items for new API format
|
# Build content items for new API format
|
||||||
|
|
@ -79,6 +85,17 @@ def report(conn, role, text, opus_data, report_time):
|
||||||
"message_content": audio_base64
|
"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
|
# Skip if no content to report
|
||||||
if not content_items:
|
if not content_items:
|
||||||
conn.logger.bind(tag=TAG).warning("No content to report, skipping")
|
conn.logger.bind(tag=TAG).warning("No content to report, skipping")
|
||||||
|
|
@ -115,14 +132,14 @@ def enqueue_tts_report(conn, text, opus_data):
|
||||||
|
|
||||||
# Use connection's queue, pass text and binary data
|
# Use connection's queue, pass text and binary data
|
||||||
if conn.chat_history_conf == 2:
|
if conn.chat_history_conf == 2:
|
||||||
# Report with audio
|
# Report with audio (TTS never has attachments)
|
||||||
conn.report_queue.put((2, clean_text, opus_data, int(time.time())))
|
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 data enqueued: agent_id={conn.agent_id}, audio packets: {len(opus_data)}"
|
f"TTS data enqueued: agent_id={conn.agent_id}, audio packets: {len(opus_data)}"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# Report without audio (text only)
|
# Report without audio (text only)
|
||||||
conn.report_queue.put((2, clean_text, None, int(time.time())))
|
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 data enqueued: agent_id={conn.agent_id}, no audio"
|
f"TTS data enqueued: agent_id={conn.agent_id}, no audio"
|
||||||
)
|
)
|
||||||
|
|
@ -130,7 +147,7 @@ def enqueue_tts_report(conn, text, opus_data):
|
||||||
conn.logger.bind(tag=TAG).error(f"Failed to enqueue TTS report: {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):
|
||||||
"""Enqueue ASR data for reporting (User message)
|
"""Enqueue ASR data for reporting (User message)
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
|
|
@ -145,18 +162,19 @@ def enqueue_asr_report(conn, text, opus_data):
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Use connection's queue, pass text and binary data
|
# 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:
|
||||||
# Report with audio
|
# 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()), attachments))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
conn.logger.bind(tag=TAG).debug(
|
||||||
f"ASR data enqueued: agent_id={conn.agent_id}, audio packets: {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:
|
||||||
# Report without audio (text only)
|
# Report without audio (text only, but may have attachments)
|
||||||
conn.report_queue.put((1, text, None, int(time.time())))
|
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 data enqueued: agent_id={conn.agent_id}, no audio"
|
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"Failed to enqueue ASR report: {text}, {e}")
|
conn.logger.bind(tag=TAG).debug(f"Failed to enqueue ASR report: {text}, {e}")
|
||||||
|
|
|
||||||
|
|
@ -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}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
@ -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消息处理器"""
|
||||||
|
|
||||||
|
|
@ -56,6 +104,17 @@ class ListenTextMessageHandler(TextMessageHandler):
|
||||||
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
||||||
enqueue_asr_report(conn, "嘿,你好呀", [])
|
enqueue_asr_report(conn, "嘿,你好呀", [])
|
||||||
await startToChat(conn, "嘿,你好呀")
|
await startToChat(conn, "嘿,你好呀")
|
||||||
|
else:
|
||||||
|
# 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:
|
else:
|
||||||
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
||||||
enqueue_asr_report(conn, original_text, [])
|
enqueue_asr_report(conn, original_text, [])
|
||||||
|
|
|
||||||
|
|
@ -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:
|
||||||
|
|
|
||||||
|
|
@ -9,3 +9,4 @@ class TextMessageType(Enum):
|
||||||
IOT = "iot"
|
IOT = "iot"
|
||||||
MCP = "mcp"
|
MCP = "mcp"
|
||||||
SERVER = "server"
|
SERVER = "server"
|
||||||
|
ATTACHMENT = "attachment"
|
||||||
|
|
|
||||||
|
|
@ -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}")
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
|
||||||
|
|
@ -538,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
|
||||||
|
|
@ -1065,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
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue