Compare commits

...

5 Commits

3 changed files with 394 additions and 16 deletions

View File

@@ -183,7 +183,10 @@
<hr><h6>思考功能</h6>
<div class="thinking-config"><div class="form-check"><input type="checkbox" class="form-check-input" id="agent-enable-thinking" checked><label class="form-check-label">启用思考</label></div><div class="mt-2"><label class="form-label">思考提示词</label><textarea class="form-control" id="agent-thinking-prompt" rows="2"></textarea></div><div class="row mt-2"><div class="col-md-6"><label class="form-label">前缀</label><input type="text" class="form-control" id="agent-thinking-prefix"></div><div class="col-md-6"><label class="form-label">后缀</label><input type="text" class="form-control" id="agent-thinking-suffix"></div></div></div>
<hr><h6>工具配置</h6>
<div class="thinking-config"><div class="form-check"><input type="checkbox" class="form-check-input" id="agent-tool-search"><label class="form-check-label">启用搜索工具</label></div><small class="text-muted">启用后 Agent 可以使用搜索功能获取实时信息</small></div>
<div class="thinking-config">
<div id="agent-tools-list">加载中...</div>
<small class="text-muted">从系统工具列表中选择Agent可使用的工具</small>
</div>
</form></div>
<div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button><button type="button" class="btn btn-primary" onclick="saveAgent()">保存</button></div>
</div></div></div>
@@ -252,7 +255,7 @@
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// 全局数据
let providersData = [], agentsData = [], channelsData = [];
let providersData = [], agentsData = [], channelsData = [], toolsData = [];
// 页面切换函数
function loadPageData(page) {
@@ -262,6 +265,57 @@
if (page === 'tools') loadTools();
if (page === 'stats') loadStats();
}
// 加载工具列表用于Agent配置
async function loadToolsList() {
try {
const res = await fetch('/api/v2/tools');
const data = await res.json();
toolsData = data.tools || [];
renderAgentToolsList();
} catch (e) { console.error('加载工具列表失败:', e); }
}
// 渲染Agent工具选择列表
function renderAgentToolsList(selectedTools = []) {
const container = document.getElementById('agent-tools-list');
if (!container) return;
if (toolsData.length === 0) {
container.innerHTML = '<div class="text-muted">暂无可用工具,请先在「工具管理」中添加</div>';
return;
}
container.innerHTML = toolsData.filter(t => t.is_active).map(t => {
const toolType = t.tool_type || 'unknown';
const isSelected = selectedTools.includes(toolType);
const icon = getToolIcon(toolType);
return `<div class="form-check">
<input type="checkbox" class="form-check-input agent-tool-checkbox" id="agent-tool-${t.id}" value="${toolType}" ${isSelected ? 'checked' : ''}>
<label class="form-check-label" for="agent-tool-${t.id}">
<i class="${icon}"></i> ${t.name} <small class="text-muted">(${toolType})</small>
</label>
</div>`;
}).join('');
}
// 工具图标
function getToolIcon(toolType) {
const icons = {
'search': 'ri-search-line',
'calculator': 'ri-calculator-line',
'code': 'ri-code-line',
'image': 'ri-image-line',
'web': 'ri-global-line'
};
return icons[toolType] || 'ri-tools-line';
}
// 获取Agent选中的工具列表
function getSelectedAgentTools() {
const checkboxes = document.querySelectorAll('.agent-tool-checkbox:checked');
return Array.from(checkboxes).map(cb => cb.value);
}
// ===== 大模型池 =====
async function loadProviders() {
@@ -403,6 +457,7 @@
document.getElementById('agent-enable-thinking').checked = true;
document.getElementById('agent-system-prompt').value = '你是一个有用的AI助手。';
updateProviderSelect();
loadToolsList(); // 加载工具列表
new bootstrap.Modal(document.getElementById('agentModal')).show();
}
@@ -425,17 +480,16 @@
document.getElementById('agent-thinking-prompt').value = a.thinking_prompt || '';
document.getElementById('agent-thinking-prefix').value = a.thinking_prefix || '';
document.getElementById('agent-thinking-suffix').value = a.thinking_suffix || '';
// 工具配置
const tools = a.tools || [];
document.getElementById('agent-tool-search').checked = tools.includes('search');
// 工具配置 - 从工具列表渲染并勾选Agent已有的工具
loadToolsList();
setTimeout(() => renderAgentToolsList(a.tools || []), 100); // 等工具列表加载完成
new bootstrap.Modal(document.getElementById('agentModal')).show();
}
async function saveAgent() {
const id = document.getElementById('agent-id').value;
// 处理工具列表
const tools = [];
if (document.getElementById('agent-tool-search').checked) tools.push('search');
// 获取选中的工具列表
const tools = getSelectedAgentTools();
const data = {
name: document.getElementById('agent-name').value,
@@ -452,7 +506,7 @@
thinking_prompt: document.getElementById('agent-thinking-prompt').value,
thinking_prefix: document.getElementById('agent-thinking-prefix').value,
thinking_suffix: document.getElementById('agent-thinking-suffix').value,
tools: tools // 工具列表
tools: tools // 工具列表(从系统工具中选择)
};
const res = await fetch(id ? `/api/v2/agents/${id}` : '/api/v2/agents', { method: id ? 'PUT' : 'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(data) });
const result = await res.json();

View File

@@ -60,6 +60,10 @@
.action-btn:hover { background: #e8e8e8; border-color: #ccc; }
.action-btn.copied { color: #10a37f; border-color: #10a37f; background: #e8f5e9; }
.action-btn.regenerate:hover { color: #667eea; border-color: #667eea; }
.action-btn.edit:hover { color: #10a37f; border-color: #10a37f; }
/* 用户消息编辑样式 */
.edit-textarea:focus { outline: none; border-color: #10a37f; box-shadow: 0 0 0 2px rgba(16,163,127,0.1); }
/* 版本切换控件 - 简洁版 */
.version-switcher { display: none; align-items: center; gap: 4px; margin-left: 4px; }
@@ -126,6 +130,40 @@
/* 快捷语句 - 横向扁平 */
.quick-phrases-bar { display: flex; align-items: center; gap: 8px; margin-top: 12px; position: relative; }
/* 工具折叠面板 - 放在输入行内 */
.tools-collapsible { position: relative; }
.tools-toggle-btn {
width: 40px; height: 40px; background: #f5f5f5; border: 1px solid #e0e0e0; border-radius: 8px;
cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 16px; color: #666;
transition: all 0.2s; position: relative;
}
.tools-toggle-btn:hover { background: #e8e8e8; border-color: #10a37f; color: #10a37f; }
.tools-toggle-btn.active { background: #e8f5e9; border-color: #10a37f; color: #10a37f; }
.tools-badge {
position: absolute; top: -4px; right: -4px;
background: #10a37f; color: white; font-size: 10px; padding: 1px 4px; border-radius: 10px;
min-width: 14px; text-align: center;
}
.tools-panel {
display: none; position: absolute; bottom: 100%; right: 0; margin-bottom: 8px;
background: white; border: 1px solid #e0e0e0; border-radius: 12px;
box-shadow: 0 4px 20px rgba(0,0,0,0.15); min-width: 180px; z-index: 100;
}
.tools-panel.show { display: block; }
.tools-panel-header {
display: flex; justify-content: space-between; align-items: center;
padding: 10px 14px; border-bottom: 1px solid #eee; font-weight: 500; color: #333; font-size: 13px;
}
.tools-panel-header button { background: none; border: none; color: #999; cursor: pointer; padding: 2px; }
.tools-panel-header button:hover { color: #666; }
.tools-panel-content { padding: 10px 14px; max-height: 280px; overflow-y: auto; }
.tool-item { display: flex; align-items: center; gap: 6px; padding: 6px 0; }
.tool-item input { width: 14px; height: 14px; }
.tool-item label { cursor: pointer; font-size: 13px; color: #333; display: flex; align-items: center; gap: 4px; }
.tool-item label i { color: #10a37f; font-size: 14px; }
.tool-item.disabled { opacity: 0.5; }
.tool-item.disabled label { color: #999; cursor: not-allowed; }
.add-phrase-btn { padding: 6px 10px; background: #f0f0f0; border: 1px solid #ddd; border-radius: 6px; cursor: pointer; font-size: 12px; color: #666; white-space: nowrap; flex-shrink: 0; }
.add-phrase-btn:hover { background: #e8e8e8; }
.phrase-list-wrapper { flex: 1; overflow-x: auto; overflow-y: hidden; scrollbar-width: thin; }
@@ -193,14 +231,26 @@
<input type="file" id="fileInput" multiple accept="image/*,.pdf,.txt,.md,.json,.csv,.doc,.docx" style="display:none" onchange="handleFileUpload(event)">
<button class="upload-btn" onclick="document.getElementById('fileInput').click()" title="上传文件"><i class="ri-attachment-2"></i></button>
<textarea id="messageInput" placeholder="输入消息..." rows="1"></textarea>
<!-- 工具按钮放在右边 -->
<div class="tools-collapsible">
<button class="tools-toggle-btn" onclick="toggleToolsPanel()" title="工具设置">
<i class="ri-tools-line"></i>
<span class="tools-badge" id="toolsBadge" style="display:none;">0</span>
</button>
<div class="tools-panel" id="toolsPanel">
<div class="tools-panel-header">
<span>工具设置</span>
<button onclick="toggleToolsPanel()"><i class="ri-close-line"></i></button>
</div>
<div class="tools-panel-content" id="toolsPanelContent"></div>
</div>
</div>
<button class="send-btn" id="sendBtn" onclick="sendMessage()"><i class="ri-send-plane-fill"></i></button>
</div>
<!-- 工具警告提示 -->
<div id="tool-warning-tip" style="display:none;margin-top:4px;padding:6px 10px;background:#fff3cd;border:1px solid #ffc107;border-radius:6px;font-size:12px;color:#856404;"></div>
<div class="file-preview-area" id="filePreviewArea"></div>
<div class="quick-phrases-bar">
<div class="tool-toggle">
<input type="checkbox" id="enableSearch" checked>
<label for="enableSearch"><i class="ri-search-line"></i> 搜索</label>
</div>
<button class="add-phrase-btn" onclick="showAddPhraseModal()"><i class="ri-add-line"></i> 添加</button>
<div class="phrase-list-wrapper" id="phraseListWrapper" onwheel="scrollPhrases(event)">
<div class="phrase-list" id="quickPhrasesList"></div>
@@ -274,6 +324,7 @@
document.addEventListener('DOMContentLoaded', () => {
loadProviders(); // 加载大模型池
loadToolsData(); // 加载工具列表
loadAgents();
loadQuickPhrases();
connectWebSocket();
@@ -287,6 +338,8 @@
const res = await fetch('/api/v2/providers');
const data = await res.json();
providers = data.providers || [];
// 加载后检查工具支持如果agents已加载
if (agents.length > 0) showToolWarning();
} catch (e) { console.error('加载Provider失败:', e); }
}
@@ -298,6 +351,125 @@
return provider?.supports_vision || false;
}
// 检查当前Agent是否支持某个工具
function checkAgentToolSupport(toolType) {
const agent = agents.find(a => a.id === currentAgentId);
if (!agent) return false;
const agentTools = agent.tools || [];
return agentTools.includes(toolType);
}
// 获取当前Agent不支持的工具列表用户已启用但Agent不支持
function getUnsupportedTools() {
const unsupported = [];
// 检查所有工具checkbox排除disabled的
const toolCheckboxes = document.querySelectorAll('.tool-checkbox:not([disabled])');
toolCheckboxes.forEach(cb => {
if (cb.checked) {
// 检查Agent是否支持
if (!checkAgentToolSupport(cb.dataset.toolType)) {
// 获取工具显示名称
const label = cb.closest('.tool-item')?.querySelector('label')?.textContent?.trim() || cb.dataset.toolType;
unsupported.push(label);
}
}
});
return unsupported;
}
// 渲染工具选择区域(根据系统工具列表)
function renderToolToggles() {
const container = document.getElementById('toolsPanelContent');
if (!container || toolsData.length === 0) return;
// 获取当前Agent支持的工具
const agent = agents.find(a => a.id === currentAgentId);
const agentTools = agent?.tools || [];
// 渲染工具checkbox列表
let html = '';
toolsData.filter(t => t.is_active).forEach(t => {
const toolType = t.tool_type || 'unknown';
const isSupported = agentTools.includes(toolType);
const icon = getToolIconFrontend(toolType);
const disabledClass = isSupported ? '' : 'disabled';
html += `<div class="tool-item ${disabledClass}">
<input type="checkbox" class="tool-checkbox" id="tool-${toolType}" data-tool-type="${toolType}" ${isSupported ? 'checked' : ''} ${!isSupported ? 'disabled' : ''} onchange="showToolWarning()">
<label for="tool-${toolType}"><i class="${icon}"></i> ${t.name}</label>
</div>`;
});
container.innerHTML = html || '<div class="text-muted" style="padding:8px;">暂无可用工具</div>';
// 更新工具数量badge
updateToolsBadge();
}
// 更新工具数量badge
function updateToolsBadge() {
const badge = document.getElementById('toolsBadge');
const selectedCount = document.querySelectorAll('.tool-checkbox:checked').length;
if (selectedCount > 0) {
badge.textContent = selectedCount;
badge.style.display = 'inline';
} else {
badge.style.display = 'none';
}
}
// 切换工具面板显示
function toggleToolsPanel() {
const panel = document.getElementById('toolsPanel');
const btn = document.querySelector('.tools-toggle-btn');
panel.classList.toggle('show');
btn.classList.toggle('active');
}
// 前端工具图标
function getToolIconFrontend(toolType) {
const icons = {
'search': 'ri-search-line',
'calculator': 'ri-calculator-line',
'code': 'ri-code-line',
'image': 'ri-image-line',
'web': 'ri-global-line'
};
return icons[toolType] || 'ri-tools-line';
}
// 加载工具列表
let toolsData = [];
async function loadToolsData() {
try {
const res = await fetch('/api/v2/tools');
const data = await res.json();
toolsData = data.tools || [];
renderToolToggles();
} catch (e) { console.error('加载工具列表失败:', e); }
}
// 显示工具不支持提示
function showToolWarning() {
updateToolsBadge(); // 更新badge数量
const unsupported = getUnsupportedTools();
const warningDiv = document.getElementById('tool-warning-tip');
if (unsupported.length > 0) {
const agent = agents.find(a => a.id === currentAgentId);
const agentName = agent?.display_name || agent?.name || '当前Agent';
const msg = `<i class="ri-alert-line"></i> <strong>${agentName}</strong> 不支持 <strong>${unsupported.join('、')}</strong> 工具请关闭或切换Agent`;
warningDiv.innerHTML = msg;
warningDiv.style.display = 'block';
// 禁用发送按钮
document.getElementById('sendBtn').disabled = true;
} else {
warningDiv.style.display = 'none';
document.getElementById('sendBtn').disabled = false;
}
}
// 加载Agent
async function loadAgents() {
try {
@@ -307,6 +479,10 @@
const defaultAgent = agents.find(a => a.is_default) || agents[0];
if (defaultAgent) currentAgentId = defaultAgent.id;
renderAgentSelect();
// 加载后检查工具支持
showToolWarning();
// 渲染工具选择区域
renderToolToggles();
} catch (e) { console.error('加载Agent失败:', e); }
}
@@ -329,6 +505,8 @@
if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ action: 'switch_agent', agent_id: currentAgentId }));
await createNewConversation();
showAgentSwitchNotice();
// 切换Agent后检查工具支持
showToolWarning();
}
}
@@ -440,6 +618,9 @@
html += `<span class="version-label" id="${messageId}_version_label">1/1</span>`;
html += `<button class="version-arrow" onclick="switchVersion('${messageId}', 1)" data-dir="next"><i class="ri-arrow-right-s-line"></i></button>`;
html += `</span>`;
} else {
// 用户消息添加编辑按钮
html += `<button class="action-btn edit" onclick="editUserMessage(this)" title="编辑并重新发送"><i class="ri-edit-line"></i> 编辑</button>`;
}
html += `</div>`;
@@ -742,6 +923,136 @@
}
}
// 编辑用户消息并重新发送
let editingUserMessage = null; // 正在编辑的用户消息元素
function editUserMessage(btn) {
const messageDiv = btn.closest('.message.user');
if (!messageDiv) return;
// 获取消息内容
const contentDiv = messageDiv.querySelector('.user-message-text');
const originalContent = contentDiv.textContent;
const actionsDiv = messageDiv.querySelector('.message-actions');
// 保存原始状态用于取消
editingUserMessage = {
element: messageDiv,
originalContent: originalContent,
contentDiv: contentDiv,
actionsDiv: actionsDiv
};
// 将消息文本变成可编辑的textarea
contentDiv.innerHTML = `<textarea class="edit-textarea" style="width:100%;min-height:60px;padding:8px;border:1px solid #ddd;border-radius:8px;font-size:15px;resize:vertical;">${escapeHtml(originalContent)}</textarea>`;
// 隐藏原有操作按钮,显示编辑操作按钮
actionsDiv.innerHTML = `
<button class="action-btn" onclick="confirmEditMessage()" style="background:#10a37f;color:white;border-color:#10a37f;"><i class="ri-check-line"></i> 确认</button>
<button class="action-btn" onclick="cancelEditMessage()"><i class="ri-close-line"></i> 取消</button>
`;
// 聚焦到textarea
const textarea = contentDiv.querySelector('.edit-textarea');
textarea.focus();
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
// 添加Ctrl+Enter快捷键确认
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && e.ctrlKey) {
e.preventDefault();
confirmEditMessage();
}
if (e.key === 'Escape') {
e.preventDefault();
cancelEditMessage();
}
});
}
function cancelEditMessage() {
if (!editingUserMessage) return;
// 恢复原始内容
editingUserMessage.contentDiv.innerHTML = escapeHtml(editingUserMessage.originalContent);
// 恢复原始操作按钮
editingUserMessage.actionsDiv.innerHTML = `
<button class="action-btn" onclick="copyMessage(this)"><i class="ri-file-copy-line"></i> 复制</button>
<button class="action-btn edit" onclick="editUserMessage(this)" title="编辑并重新发送"><i class="ri-edit-line"></i> 编辑</button>
`;
editingUserMessage = null;
}
function confirmEditMessage() {
if (!editingUserMessage) return;
const textarea = editingUserMessage.contentDiv.querySelector('.edit-textarea');
const newContent = textarea.value.trim();
if (!newContent) {
alert('消息内容不能为空');
return;
}
// 如果内容没有变化,直接取消编辑
if (newContent === editingUserMessage.originalContent) {
cancelEditMessage();
return;
}
// 更新消息内容
editingUserMessage.contentDiv.innerHTML = escapeHtml(newContent);
// 恢复操作按钮
editingUserMessage.actionsDiv.innerHTML = `
<button class="action-btn" onclick="copyMessage(this)"><i class="ri-file-copy-line"></i> 复制</button>
<button class="action-btn edit" onclick="editUserMessage(this)" title="编辑并重新发送"><i class="ri-edit-line"></i> 编辑</button>
`;
// 更新最后用户消息记录
lastUserMessage = newContent;
// 找到下一条assistant消息设置重新生成标志
const container = document.getElementById('messagesContainer');
const allMessages = container.querySelectorAll('.message');
let nextAssistantId = null;
for (let i = 0; i < allMessages.length; i++) {
if (allMessages[i] === editingUserMessage.element && i + 1 < allMessages.length) {
const nextMsg = allMessages[i + 1];
if (nextMsg.classList.contains('assistant')) {
nextAssistantId = nextMsg.id || nextMsg.dataset.messageId;
}
break;
}
}
if (nextAssistantId) {
isRegenerating = true;
regeneratingMessageId = nextAssistantId;
showLoadingIndicator(nextAssistantId);
} else {
// 没有assistant消息需要创建新的
isRegenerating = false;
regeneratingMessageId = null;
}
editingUserMessage = null;
// 重新发送编辑后的消息
document.getElementById('sendBtn').disabled = true;
if (ws?.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
action: 'chat',
message: newContent,
conversation_id: currentConversationId,
agent_id: currentAgentId
}));
}
}
function escapeHtml(text) {
return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
@@ -897,6 +1208,16 @@
return;
}
// 检查工具支持
const unsupported = getUnsupportedTools();
if (unsupported.length > 0) {
const agent = agents.find(a => a.id === currentAgentId);
const agentName = agent?.display_name || agent?.name || '当前Agent';
alert(`⚠️ ${agentName} 不支持 ${unsupported.join('、')} 工具\n\n请关闭不支持的工具或切换到支持该工具的Agent。`);
document.getElementById('sendBtn').disabled = false;
return;
}
document.getElementById('sendBtn').disabled = true;
input.value = '';
input.style.height = 'auto';
@@ -909,10 +1230,13 @@
pendingFiles = [];
document.getElementById('filePreviewArea').innerHTML = '';
// 获取工具禁用状态
const enableSearch = document.getElementById('enableSearch').checked;
// 获取禁用的工具列表(所有系统工具 - 用户选中的工具)
const disabledTools = [];
if (!enableSearch) disabledTools.push('search');
const allToolTypes = toolsData.filter(t => t.is_active).map(t => t.tool_type);
const selectedTools = Array.from(document.querySelectorAll('.tool-checkbox:checked')).map(cb => cb.dataset.toolType);
allToolTypes.forEach(t => {
if (!selectedTools.includes(t)) disabledTools.push(t);
});
// 发送消息(包含文件)
if (ws?.readyState === WebSocket.OPEN) {

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB