Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8aa1f5fd88 | |||
| 813b4887ed | |||
| 3cbdddf773 | |||
| c0ed6cd505 | |||
| 25e92b1fb1 |
206
main_v2.py
206
main_v2.py
@@ -777,77 +777,11 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
if not message.strip():
|
||||
continue
|
||||
|
||||
# 获取Agent配置
|
||||
# 1. 获取Agent配置
|
||||
agent_config = agent_service.get_agent_config(current_agent_id)
|
||||
agent_tools = agent_config.get('agent', {}).get('tools', [])
|
||||
|
||||
# 检查是否需要执行搜索
|
||||
search_context = None
|
||||
if 'search' in agent_tools and 'search' not in disabled_tools:
|
||||
# 只要启用了搜索工具且未禁用,就执行搜索(不再依赖关键词检测)
|
||||
should_search = True
|
||||
|
||||
if should_search:
|
||||
# 执行搜索
|
||||
tool_service = ToolService(db)
|
||||
search_tool = tool_service.get_default_tool('search')
|
||||
|
||||
if search_tool and search_tool.config.get('api_key'):
|
||||
import httpx
|
||||
import time
|
||||
start_time = time.time()
|
||||
try:
|
||||
logger.info(f"执行搜索: query={message}")
|
||||
tavily_url = "https://api.tavily.com/search"
|
||||
config = search_tool.config
|
||||
payload = {
|
||||
"api_key": config.get('api_key'),
|
||||
"query": message,
|
||||
"max_results": config.get('max_results', 5),
|
||||
"search_depth": config.get('search_depth', 'basic')
|
||||
}
|
||||
|
||||
# 同步调用
|
||||
with httpx.Client(timeout=30) as client:
|
||||
resp = client.post(tavily_url, json=payload)
|
||||
search_result = resp.json()
|
||||
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
if search_result.get("results"):
|
||||
# 构建搜索上下文
|
||||
search_context = "\n\n【搜索结果】\n"
|
||||
for i, r in enumerate(search_result["results"][:5], 1):
|
||||
search_context += f"{i}. {r.get('title', 'N/A')}\n {r.get('content', r.get('snippet', 'N/A'))[:200]}\n 来源: {r.get('url', 'N/A')}\n"
|
||||
logger.info(f"搜索完成: {len(search_result['results'])} 条结果")
|
||||
|
||||
# 更新统计和日志
|
||||
tool_service.increment_stats(search_tool.id, True)
|
||||
tool_service.log_usage({
|
||||
'tool_id': search_tool.id,
|
||||
'tool_type': 'search',
|
||||
'query': message,
|
||||
'success': True,
|
||||
'result_summary': f'{len(search_result["results"])} results',
|
||||
'conversation_id': conversation_id,
|
||||
'agent_id': current_agent_id,
|
||||
'duration_ms': duration_ms
|
||||
})
|
||||
except Exception as e:
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
logger.error(f"搜索失败: {e}")
|
||||
tool_service.increment_stats(search_tool.id, False)
|
||||
tool_service.log_usage({
|
||||
'tool_id': search_tool.id,
|
||||
'tool_type': 'search',
|
||||
'query': message,
|
||||
'success': False,
|
||||
'error_message': str(e),
|
||||
'conversation_id': conversation_id,
|
||||
'duration_ms': duration_ms
|
||||
})
|
||||
|
||||
# 获取或创建会话
|
||||
# 2. 获取或创建会话(先有 conversation_id)
|
||||
if conversation_id:
|
||||
conversation = conv_service.get_conversation(conversation_id)
|
||||
else:
|
||||
@@ -858,7 +792,103 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
"conversation_id": conversation_id
|
||||
})
|
||||
|
||||
# 保存用户消息
|
||||
# 3. 广播用户消息(前端立即看到)
|
||||
await manager.send_to_user(MAIN_USER_ID, {
|
||||
"type": "user_message",
|
||||
"conversation_id": conversation_id,
|
||||
"message": {
|
||||
"id": None, # 临时,后面会保存
|
||||
"role": "user",
|
||||
"content": message,
|
||||
"source": "web",
|
||||
"created_at": datetime.utcnow().isoformat()
|
||||
}
|
||||
})
|
||||
|
||||
# 4. 执行搜索并发送搜索结果
|
||||
search_context = None
|
||||
logger.info(f"检查搜索条件: agent_tools={agent_tools}, disabled_tools={disabled_tools}")
|
||||
|
||||
if 'search' in agent_tools and 'search' not in disabled_tools:
|
||||
logger.info("搜索条件满足,开始执行搜索")
|
||||
|
||||
tool_service = ToolService(db)
|
||||
search_tool = tool_service.get_default_tool('search')
|
||||
logger.info(f"获取到搜索工具: {search_tool.name if search_tool else 'None'}")
|
||||
|
||||
if search_tool and search_tool.config.get('api_key'):
|
||||
import httpx
|
||||
import time
|
||||
start_time = time.time()
|
||||
try:
|
||||
logger.info(f"执行搜索: query={message}")
|
||||
tavily_url = "https://api.tavily.com/search"
|
||||
config = search_tool.config
|
||||
payload = {
|
||||
"api_key": config.get('api_key'),
|
||||
"query": message,
|
||||
"max_results": config.get('max_results', 5),
|
||||
"search_depth": config.get('search_depth', 'basic')
|
||||
}
|
||||
|
||||
with httpx.Client(timeout=30) as client:
|
||||
resp = client.post(tavily_url, json=payload)
|
||||
search_result = resp.json()
|
||||
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
if search_result.get("results"):
|
||||
# 构建搜索上下文(给LLM)
|
||||
max_for_llm = config.get('max_results', 5)
|
||||
search_context = "\n\n【搜索结果】\n"
|
||||
for i, r in enumerate(search_result["results"][:max_for_llm], 1):
|
||||
search_context += f"{i}. {r.get('title', 'N/A')}\n {r.get('content', r.get('snippet', 'N/A'))[:200]}\n 来源: {r.get('url', 'N/A')}\n"
|
||||
logger.info(f"搜索完成: {len(search_result['results'])} 条结果,使用 {min(len(search_result['results']), max_for_llm)} 条")
|
||||
|
||||
# 发送搜索结果给前端(按配置的数量)
|
||||
max_display = config.get('max_results', 5)
|
||||
search_results_for_client = [
|
||||
{
|
||||
"title": r.get('title', 'N/A'),
|
||||
"snippet": r.get('content', r.get('snippet', ''))[:150],
|
||||
"url": r.get('url', 'N/A')
|
||||
}
|
||||
for r in search_result["results"][:max_display]
|
||||
]
|
||||
await websocket.send_json({
|
||||
"type": "search_results",
|
||||
"conversation_id": conversation_id,
|
||||
"results": search_results_for_client,
|
||||
"query": message
|
||||
})
|
||||
|
||||
# 更新统计和日志
|
||||
tool_service.increment_stats(search_tool.id, True)
|
||||
tool_service.log_usage({
|
||||
'tool_id': search_tool.id,
|
||||
'tool_type': 'search',
|
||||
'query': message,
|
||||
'success': True,
|
||||
'result_summary': f'{len(search_result["results"])} results',
|
||||
'conversation_id': conversation_id,
|
||||
'agent_id': current_agent_id,
|
||||
'duration_ms': duration_ms
|
||||
})
|
||||
except Exception as e:
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
logger.error(f"搜索失败: {e}")
|
||||
tool_service.increment_stats(search_tool.id, False)
|
||||
tool_service.log_usage({
|
||||
'tool_id': search_tool.id,
|
||||
'tool_type': 'search',
|
||||
'query': message,
|
||||
'success': False,
|
||||
'error_message': str(e),
|
||||
'conversation_id': conversation_id,
|
||||
'duration_ms': duration_ms
|
||||
})
|
||||
|
||||
# 5. 保存用户消息到数据库
|
||||
user_msg = conv_service.add_message(
|
||||
conversation_id=conversation.id,
|
||||
role='user',
|
||||
@@ -866,22 +896,16 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
source='web'
|
||||
)
|
||||
|
||||
# 广播用户消息
|
||||
await manager.send_to_user(MAIN_USER_ID, {
|
||||
"type": "user_message",
|
||||
"conversation_id": conversation_id,
|
||||
"message": {
|
||||
"id": user_msg.id,
|
||||
"role": "user",
|
||||
"content": message,
|
||||
"source": "web",
|
||||
"created_at": user_msg.created_at.isoformat()
|
||||
}
|
||||
})
|
||||
# 6. 获取对话历史(包含刚保存的用户消息)
|
||||
history = conv_service.get_conversation_history(conversation_id, limit=agent_config['agent'].get('max_history', 20))
|
||||
|
||||
# 获取Agent配置
|
||||
agent_config = agent_service.get_agent_config(current_agent_id)
|
||||
# 7. 如果有搜索结果,添加到消息中
|
||||
if search_context:
|
||||
modified_system_prompt = agent_config['agent'].get('system_prompt', '') + "\n\n如果提供了搜索结果,请基于搜索结果回答用户问题,并注明信息来源。"
|
||||
agent_config['agent']['system_prompt'] = modified_system_prompt
|
||||
history.append({"role": "system", "content": f"以下是搜索到的相关信息,请参考这些内容回答用户问题:{search_context}"})
|
||||
|
||||
# 8. 调用LLM返回回复
|
||||
if not agent_config or not agent_config.get('provider'):
|
||||
await websocket.send_json({
|
||||
"type": "error",
|
||||
@@ -889,20 +913,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
})
|
||||
continue
|
||||
|
||||
# 获取对话历史
|
||||
history = conv_service.get_conversation_history(conversation_id, limit=agent_config['agent'].get('max_history', 20))
|
||||
|
||||
# 如果有搜索结果,添加到消息中
|
||||
if search_context:
|
||||
# 在系统提示中添加搜索结果说明
|
||||
modified_system_prompt = agent_config['agent'].get('system_prompt', '') + "\n\n如果提供了搜索结果,请基于搜索结果回答用户问题,并注明信息来源。"
|
||||
agent_config['agent']['system_prompt'] = modified_system_prompt
|
||||
# 将搜索结果作为系统消息添加到历史
|
||||
history.append({"role": "system", "content": f"以下是搜索到的相关信息,请参考这些内容回答用户问题:{search_context}"})
|
||||
|
||||
# 使用非流式调用LLM(简化版本,确保稳定)
|
||||
try:
|
||||
# 调用LLM(非流式)
|
||||
response, thinking_content = await llm_service.chat(
|
||||
messages=history,
|
||||
provider_config=agent_config['provider'],
|
||||
@@ -923,7 +934,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
model_used=agent_config['provider'].get('default_model')
|
||||
)
|
||||
|
||||
# 发送完整回复(包含思考内容)
|
||||
# 发送AI回复
|
||||
await websocket.send_json({
|
||||
"type": "assistant_message",
|
||||
"conversation_id": conversation_id,
|
||||
@@ -941,7 +952,6 @@ 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
|
||||
|
||||
@@ -126,6 +126,7 @@ class AgentService:
|
||||
'model_override': agent.model_override,
|
||||
'max_history': agent.max_history,
|
||||
'temperature_override': agent.temperature_override,
|
||||
'tools': agent.tools or [], # 工具列表
|
||||
'is_default': agent.is_default,
|
||||
'is_active': agent.is_active
|
||||
},
|
||||
@@ -531,7 +532,7 @@ class ToolService:
|
||||
|
||||
def get_usage_stats(self, days: int = 7) -> Dict:
|
||||
"""获取工具使用统计"""
|
||||
from datetime import timedelta
|
||||
from datetime import datetime, timedelta
|
||||
start_date = datetime.utcnow() - timedelta(days=days)
|
||||
|
||||
# 按工具类型统计
|
||||
|
||||
@@ -86,6 +86,17 @@
|
||||
.thinking-toggle { font-size: 12px; color: #667eea; }
|
||||
.thinking-content { margin-top: 12px; display: none; }
|
||||
.thinking-content.expanded { display: block; }
|
||||
.search-results-box { margin: 12px 0; padding: 10px 12px; background: linear-gradient(135deg, #f0f7ff 0%, #e8f4f8 100%); border-radius: 8px; border: 1px solid #d0e8f0; }
|
||||
.search-results-header { display: flex; align-items: center; justify-content: space-between; cursor: pointer; }
|
||||
.search-results-header h5 { margin: 0; font-size: 13px; color: #10a37f; display: flex; align-items: center; gap: 6px; }
|
||||
.search-results-toggle { font-size: 12px; color: #666; }
|
||||
.search-results-content { margin-top: 10px; display: none; }
|
||||
.search-results-content.expanded { display: block; }
|
||||
.search-result-item { margin-bottom: 8px; padding: 8px 10px; background: white; border-radius: 6px; border: 1px solid #eee; }
|
||||
.search-result-item:last-child { margin-bottom: 0; }
|
||||
.search-result-title { font-size: 13px; color: #10a37f; font-weight: 500; margin-bottom: 4px; }
|
||||
.search-result-snippet { font-size: 12px; color: #666; line-height: 1.4; }
|
||||
.search-result-url { font-size: 11px; color: #999; margin-top: 4px; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
/* Agent信息 */
|
||||
.agent-info { font-size: 12px; color: #999; margin-top: 8px; }
|
||||
@@ -269,9 +280,11 @@
|
||||
case 'stream_end': document.getElementById('sendBtn').disabled = false; break;
|
||||
case 'user_message':
|
||||
lastUserMessage = data.message.content; // 存储最后一条用户消息
|
||||
if (!isRegenerating) {
|
||||
// 如果是刚发送的消息,已经显示了,不再重复显示
|
||||
if (!isRegenerating && data.message.content !== lastSentMessage) {
|
||||
appendMessage('user', data.message.content);
|
||||
}
|
||||
lastSentMessage = null; // 清除标记
|
||||
// 注意:不要在这里重置 isRegenerating,要等 assistant_message 处理后再重置
|
||||
break;
|
||||
case 'assistant_message':
|
||||
@@ -286,6 +299,7 @@
|
||||
document.getElementById('sendBtn').disabled = false;
|
||||
break;
|
||||
case 'error': showError(data.message); document.getElementById('sendBtn').disabled = false; break;
|
||||
case 'search_results': displaySearchResults(data.results, data.query); break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -623,6 +637,66 @@
|
||||
container.appendChild(div);
|
||||
}
|
||||
|
||||
function displaySearchResults(results, query) {
|
||||
if (!results || results.length === 0) return;
|
||||
|
||||
const container = document.getElementById('messagesContainer');
|
||||
|
||||
// 找到最后一条用户消息
|
||||
const userMessages = container.querySelectorAll('.message.user');
|
||||
const lastUserMsg = userMessages[userMessages.length - 1];
|
||||
|
||||
if (!lastUserMsg) {
|
||||
// 没有用户消息,作为独立消息显示
|
||||
const div = document.createElement('div');
|
||||
div.className = 'message assistant';
|
||||
div.innerHTML = `<div class="message-avatar">🔍</div><div class="message-body">${buildSearchResultsHtml(results, query)}</div>`;
|
||||
container.appendChild(div);
|
||||
} else {
|
||||
// 在用户消息的 message-body 中追加搜索结果
|
||||
const msgBody = lastUserMsg.querySelector('.message-body');
|
||||
if (msgBody) {
|
||||
msgBody.innerHTML += buildSearchResultsHtml(results, query);
|
||||
}
|
||||
}
|
||||
|
||||
// 滚动到底部
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
|
||||
function buildSearchResultsHtml(results, query) {
|
||||
const resultId = 'sr-' + Date.now();
|
||||
let html = `<div class="search-results-box">
|
||||
<div class="search-results-header" onclick="toggleSearchResults('${resultId}')">
|
||||
<h5><i class="ri-search-line"></i> 搜索: ${escapeHtml(query.substring(0, 30))}${query.length > 30 ? '...' : ''} (${results.length}条结果)</h5>
|
||||
<span class="search-results-toggle" id="${resultId}-toggle">展开 <i class="ri-arrow-down-s-line"></i></span>
|
||||
</div>
|
||||
<div class="search-results-content" id="${resultId}">`;
|
||||
|
||||
for (const r of results) {
|
||||
html += `<div class="search-result-item">
|
||||
<div class="search-result-title">${escapeHtml(r.title)}</div>
|
||||
<div class="search-result-snippet">${escapeHtml(r.snippet)}</div>
|
||||
<div class="search-result-url">${escapeHtml(r.url)}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
html += '</div></div>';
|
||||
return html;
|
||||
}
|
||||
|
||||
function toggleSearchResults(id) {
|
||||
const content = document.getElementById(id);
|
||||
const toggle = document.getElementById(id + '-toggle');
|
||||
if (content.classList.contains('expanded')) {
|
||||
content.classList.remove('expanded');
|
||||
toggle.innerHTML = '展开 <i class="ri-arrow-down-s-line"></i>';
|
||||
} else {
|
||||
content.classList.add('expanded');
|
||||
toggle.innerHTML = '收起 <i class="ri-arrow-up-s-line"></i>';
|
||||
}
|
||||
}
|
||||
|
||||
// 会话管理
|
||||
async function loadConversations() {
|
||||
const res = await fetch('/api/conversations');
|
||||
@@ -684,6 +758,10 @@
|
||||
input.value = '';
|
||||
input.style.height = 'auto';
|
||||
|
||||
// 立即显示用户消息(不等后端广播)
|
||||
lastSentMessage = msg; // 记录最后发送的消息,避免重复显示
|
||||
appendMessage('user', msg);
|
||||
|
||||
// 获取工具禁用状态
|
||||
const enableSearch = document.getElementById('enableSearch').checked;
|
||||
const disabledTools = [];
|
||||
@@ -700,6 +778,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
let lastSentMessage = null; // 记录最后发送的消息
|
||||
|
||||
function setupTextarea() {
|
||||
const textarea = document.getElementById('messageInput');
|
||||
textarea.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } });
|
||||
|
||||
Reference in New Issue
Block a user