Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3cbdddf773 | |||
| c0ed6cd505 | |||
| 25e92b1fb1 |
34
main_v2.py
34
main_v2.py
@@ -783,11 +783,19 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
|
||||
# 检查是否需要执行搜索
|
||||
search_context = None
|
||||
search_results_for_client = None # 用于发送给前端
|
||||
logger.info(f"检查搜索条件: agent_tools={agent_tools}, disabled_tools={disabled_tools}")
|
||||
|
||||
if 'search' in agent_tools and 'search' not in disabled_tools:
|
||||
# 只要启用了搜索工具且未禁用,就执行搜索(不再依赖关键词检测)
|
||||
should_search = True
|
||||
# 只要启用了搜索工具且未禁用,就执行搜索
|
||||
logger.info("搜索条件满足,开始执行搜索")
|
||||
|
||||
if should_search:
|
||||
# 执行搜索
|
||||
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'):
|
||||
# 执行搜索
|
||||
tool_service = ToolService(db)
|
||||
search_tool = tool_service.get_default_tool('search')
|
||||
@@ -815,12 +823,30 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
if search_result.get("results"):
|
||||
# 构建搜索上下文
|
||||
# 构建搜索上下文(给LLM)
|
||||
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'])} 条结果")
|
||||
|
||||
# 构建搜索结果给前端展示
|
||||
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"][:5]
|
||||
]
|
||||
|
||||
# 发送搜索结果给前端
|
||||
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({
|
||||
|
||||
@@ -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; }
|
||||
@@ -286,6 +297,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 +635,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');
|
||||
|
||||
Reference in New Issue
Block a user