fix: 简化消息发送流程,直接发送完整回复
This commit is contained in:
55
main_v2.py
55
main_v2.py
@@ -60,8 +60,13 @@ class ConnectionManager:
|
|||||||
for connection in self.active_connections[user_id]:
|
for connection in self.active_connections[user_id]:
|
||||||
try:
|
try:
|
||||||
await connection.send_json(message)
|
await connection.send_json(message)
|
||||||
except:
|
logger.info(f"发送消息到用户 {user_id}: {message.get('type', 'unknown')}")
|
||||||
pass
|
except Exception as e:
|
||||||
|
logger.error(f"发送消息失败: {e}")
|
||||||
|
|
||||||
|
async def ping(self, user_id: str):
|
||||||
|
"""发送心跳ping"""
|
||||||
|
await self.send_to_user(user_id, {"type": "ping"})
|
||||||
|
|
||||||
|
|
||||||
manager = ConnectionManager()
|
manager = ConnectionManager()
|
||||||
@@ -661,13 +666,6 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
|||||||
|
|
||||||
# 使用非流式调用LLM(简化版本,确保稳定)
|
# 使用非流式调用LLM(简化版本,确保稳定)
|
||||||
try:
|
try:
|
||||||
# 先发送思考开始
|
|
||||||
if agent_config['agent'].get('enable_thinking') and enable_thinking:
|
|
||||||
await websocket.send_json({
|
|
||||||
"type": "thinking_start",
|
|
||||||
"conversation_id": conversation_id
|
|
||||||
})
|
|
||||||
|
|
||||||
# 调用LLM(非流式)
|
# 调用LLM(非流式)
|
||||||
response, thinking_content = await llm_service.chat(
|
response, thinking_content = await llm_service.chat(
|
||||||
messages=history,
|
messages=history,
|
||||||
@@ -676,33 +674,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
|||||||
enable_thinking=enable_thinking
|
enable_thinking=enable_thinking
|
||||||
)
|
)
|
||||||
|
|
||||||
# 发送思考内容
|
logger.info(f"LLM响应: response长度={len(response)}, thinking长度={len(thinking_content) if thinking_content else 0}")
|
||||||
if thinking_content:
|
|
||||||
await websocket.send_json({
|
|
||||||
"type": "thinking_content",
|
|
||||||
"conversation_id": conversation_id,
|
|
||||||
"content": thinking_content
|
|
||||||
})
|
|
||||||
|
|
||||||
# 发送思考结束
|
|
||||||
await websocket.send_json({
|
|
||||||
"type": "thinking_end",
|
|
||||||
"conversation_id": conversation_id,
|
|
||||||
"content": thinking_content
|
|
||||||
})
|
|
||||||
|
|
||||||
# 直接发送完整回复
|
|
||||||
await websocket.send_json({
|
|
||||||
"type": "content_stream",
|
|
||||||
"conversation_id": conversation_id,
|
|
||||||
"text": response
|
|
||||||
})
|
|
||||||
|
|
||||||
# 发送完成通知
|
|
||||||
await websocket.send_json({
|
|
||||||
"type": "stream_end",
|
|
||||||
"conversation_id": conversation_id
|
|
||||||
})
|
|
||||||
|
|
||||||
# 保存AI回复
|
# 保存AI回复
|
||||||
assistant_msg = conv_service.add_message(
|
assistant_msg = conv_service.add_message(
|
||||||
@@ -715,7 +687,8 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
|||||||
model_used=agent_config['provider'].get('default_model')
|
model_used=agent_config['provider'].get('default_model')
|
||||||
)
|
)
|
||||||
|
|
||||||
await manager.send_to_user(MAIN_USER_ID, {
|
# 发送完整回复(包含思考内容)
|
||||||
|
await websocket.send_json({
|
||||||
"type": "assistant_message",
|
"type": "assistant_message",
|
||||||
"conversation_id": conversation_id,
|
"conversation_id": conversation_id,
|
||||||
"message": {
|
"message": {
|
||||||
@@ -730,6 +703,14 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
logger.info(f"AI回复已发送: conversation_id={conversation_id}")
|
||||||
|
|
||||||
|
# 启用发送按钮
|
||||||
|
await websocket.send_json({
|
||||||
|
"type": "stream_end",
|
||||||
|
"conversation_id": conversation_id
|
||||||
|
})
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"LLM调用失败: {e}")
|
logger.error(f"LLM调用失败: {e}")
|
||||||
await websocket.send_json({
|
await websocket.send_json({
|
||||||
|
|||||||
@@ -364,6 +364,7 @@
|
|||||||
|
|
||||||
// 处理WebSocket消息
|
// 处理WebSocket消息
|
||||||
function handleWebSocketMessage(data) {
|
function handleWebSocketMessage(data) {
|
||||||
|
console.log('收到消息:', data.type);
|
||||||
switch (data.type) {
|
switch (data.type) {
|
||||||
case 'history':
|
case 'history':
|
||||||
displayHistory(data.messages);
|
displayHistory(data.messages);
|
||||||
@@ -385,22 +386,10 @@
|
|||||||
currentAgentId = data.agent_id;
|
currentAgentId = data.agent_id;
|
||||||
console.log('Agent已切换:', data.agent_name);
|
console.log('Agent已切换:', data.agent_name);
|
||||||
break;
|
break;
|
||||||
// 流式输出处理
|
case 'ping':
|
||||||
case 'thinking_start':
|
// 心跳,忽略
|
||||||
createStreamingMessage('thinking');
|
|
||||||
break;
|
|
||||||
case 'thinking_stream':
|
|
||||||
appendStreamText('thinking', data.text);
|
|
||||||
break;
|
|
||||||
case 'thinking_end':
|
|
||||||
collapseThinking(data.content);
|
|
||||||
createStreamingMessage('content');
|
|
||||||
break;
|
|
||||||
case 'content_stream':
|
|
||||||
appendStreamText('content', data.text);
|
|
||||||
break;
|
break;
|
||||||
case 'stream_end':
|
case 'stream_end':
|
||||||
finishStreaming();
|
|
||||||
document.getElementById('sendBtn').disabled = false;
|
document.getElementById('sendBtn').disabled = false;
|
||||||
break;
|
break;
|
||||||
case 'user_message':
|
case 'user_message':
|
||||||
@@ -411,8 +400,9 @@
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 'assistant_message':
|
case 'assistant_message':
|
||||||
// 流式完成后,更新最终消息(添加Agent信息等)
|
// 直接显示完整回复
|
||||||
updateFinalMessage(data.message);
|
appendMessage('assistant', data.message.content, data.message.source, data.message.thinking_content, data.message.agent_name);
|
||||||
|
document.getElementById('sendBtn').disabled = false;
|
||||||
break;
|
break;
|
||||||
case 'error':
|
case 'error':
|
||||||
showError(data.message);
|
showError(data.message);
|
||||||
@@ -421,109 +411,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建流式消息容器
|
|
||||||
function createStreamingMessage(type) {
|
|
||||||
const container = document.getElementById('messagesContainer');
|
|
||||||
container.querySelector('.welcome')?.remove();
|
|
||||||
|
|
||||||
const existingStream = document.getElementById('streaming-message');
|
|
||||||
if (existingStream && type === 'content') return; // 回答区域已存在
|
|
||||||
|
|
||||||
const div = document.createElement('div');
|
|
||||||
div.id = 'streaming-message';
|
|
||||||
div.className = 'message assistant';
|
|
||||||
|
|
||||||
if (type === 'thinking') {
|
|
||||||
div.innerHTML = `
|
|
||||||
<div class="message-avatar">🤔</div>
|
|
||||||
<div class="message-content">
|
|
||||||
<div class="thinking-stream" id="thinking-stream" style="background:#f8f9fa;border-left:3px solid #667eea;padding:12px;font-size:14px;color:#667eea;">
|
|
||||||
<strong>💭 思考过程</strong><br>
|
|
||||||
<span id="thinking-text"></span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
} else {
|
|
||||||
div.innerHTML = `
|
|
||||||
<div class="message-avatar">🤖</div>
|
|
||||||
<div class="message-content">
|
|
||||||
<div id="thinking-collapsed" style="display:none;"></div>
|
|
||||||
<span id="content-text"></span>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
}
|
|
||||||
container.appendChild(div);
|
|
||||||
container.scrollTop = container.scrollHeight;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 追加流式文本
|
|
||||||
function appendStreamText(type, text) {
|
|
||||||
const textEl = document.getElementById(type === 'thinking' ? 'thinking-text' : 'content-text');
|
|
||||||
if (textEl) {
|
|
||||||
textEl.textContent += text;
|
|
||||||
const container = document.getElementById('messagesContainer');
|
|
||||||
container.scrollTop = container.scrollHeight;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 折叠思考内容
|
|
||||||
function collapseThinking(content) {
|
|
||||||
const streamEl = document.getElementById('thinking-stream');
|
|
||||||
if (streamEl) {
|
|
||||||
// 创建折叠版本
|
|
||||||
const collapsedDiv = document.getElementById('thinking-collapsed');
|
|
||||||
if (collapsedDiv) {
|
|
||||||
collapsedDiv.style.display = 'block';
|
|
||||||
collapsedDiv.innerHTML = `
|
|
||||||
<div class="thinking-collapsed" onclick="toggleThinkingBlock(this)" style="cursor:pointer;background:#f0f0f0;padding:8px 12px;border-radius:4px;margin-bottom:8px;font-size:13px;color:#667eea;">
|
|
||||||
<i class="ri-lightbulb-line"></i> 思考过程 <span class="toggle-hint">(点击展开)</span>
|
|
||||||
</div>
|
|
||||||
<div class="thinking-expanded" style="display:none;background:#f8f9fa;border-left:3px solid #667eea;padding:12px;font-size:14px;margin-bottom:12px;">
|
|
||||||
${formatContent(content)}
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
}
|
|
||||||
streamEl.style.display = 'none';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 展开/折叠思考内容
|
|
||||||
function toggleThinkingBlock(el) {
|
|
||||||
const expanded = el.parentElement.querySelector('.thinking-expanded');
|
|
||||||
const hint = el.querySelector('.toggle-hint');
|
|
||||||
if (expanded.style.display === 'none') {
|
|
||||||
expanded.style.display = 'block';
|
|
||||||
hint.textContent = '(点击折叠)';
|
|
||||||
} else {
|
|
||||||
expanded.style.display = 'none';
|
|
||||||
hint.textContent = '(点击展开)';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 完成流式输出
|
|
||||||
function finishStreaming() {
|
|
||||||
const streamMsg = document.getElementById('streaming-message');
|
|
||||||
if (streamMsg) {
|
|
||||||
streamMsg.id = ''; // 移除临时ID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 更新最终消息(添加Agent信息)
|
|
||||||
function updateFinalMessage(msg) {
|
|
||||||
const messages = document.querySelectorAll('.message.assistant');
|
|
||||||
const lastMsg = messages[messages.length - 1];
|
|
||||||
if (lastMsg && msg.agent_name) {
|
|
||||||
const contentDiv = lastMsg.querySelector('.message-content');
|
|
||||||
if (contentDiv && !contentDiv.querySelector('.agent-info')) {
|
|
||||||
const agentInfo = document.createElement('div');
|
|
||||||
agentInfo.className = 'agent-info';
|
|
||||||
agentInfo.style.cssText = 'font-size:12px;color:#999;margin-top:8px;';
|
|
||||||
agentInfo.innerHTML = `<i class="ri-robot-line"></i> ${msg.agent_name}`;
|
|
||||||
contentDiv.appendChild(agentInfo);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 显示错误
|
// 显示错误
|
||||||
function showError(msg) {
|
function showError(msg) {
|
||||||
const container = document.getElementById('messagesContainer');
|
const container = document.getElementById('messagesContainer');
|
||||||
|
|||||||
Reference in New Issue
Block a user