Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 527885f3d6 | |||
| c21270195a | |||
| db7d0fd586 | |||
| f9e3708ce0 | |||
| 64f0aa0c0b | |||
| 8ddc50a0a9 | |||
| 20ef1abe7d | |||
| 54290019c3 | |||
| d3e80c0afb | |||
| a3def9702b | |||
| cd1f95bb2c | |||
| 0c4cc96106 | |||
| 2dca775911 |
87
main_v2.py
87
main_v2.py
@@ -3,7 +3,7 @@ AI对话系统 v2.0.0 - 主应用
|
||||
支持:大模型池、Agent管理、渠道独立绑定、思考功能开关
|
||||
"""
|
||||
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -13,6 +13,9 @@ import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
import os
|
||||
import base64
|
||||
import uuid
|
||||
import time
|
||||
|
||||
# 使用新的数据模型
|
||||
from models_v2 import (
|
||||
@@ -34,7 +37,14 @@ app = FastAPI(title="AI对话系统 v2.0", version="2.0.0")
|
||||
|
||||
# 静态文件和模板
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
UPLOADS_DIR = os.path.join(BASE_DIR, "uploads", "images")
|
||||
|
||||
# 确保上传目录存在
|
||||
os.makedirs(UPLOADS_DIR, exist_ok=True)
|
||||
|
||||
# 静态文件服务
|
||||
app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "static")), name="static")
|
||||
app.mount("/uploads", StaticFiles(directory=os.path.join(BASE_DIR, "uploads")), name="uploads")
|
||||
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))
|
||||
|
||||
# WebSocket连接管理
|
||||
@@ -110,6 +120,8 @@ async def get_providers(db: Session = Depends(get_db)):
|
||||
"default_model": p.default_model,
|
||||
"supports_thinking": p.supports_thinking,
|
||||
"thinking_model": p.thinking_model,
|
||||
"supports_vision": p.supports_vision,
|
||||
"vision_model": p.vision_model,
|
||||
"max_tokens": p.max_tokens,
|
||||
"temperature": p.temperature,
|
||||
"is_active": p.is_active,
|
||||
@@ -575,6 +587,56 @@ async def perform_search(data: dict, db: Session = Depends(get_db)):
|
||||
return {"success": False, "message": "不支持的搜索提供商"}
|
||||
|
||||
|
||||
# ==================== 图片上传 API ====================
|
||||
|
||||
@app.post("/api/v2/upload-image")
|
||||
async def upload_image(data: dict):
|
||||
"""上传图片到服务器,返回文件路径"""
|
||||
try:
|
||||
image_data = data.get('image')
|
||||
file_name = data.get('name', 'image.png')
|
||||
|
||||
if not image_data:
|
||||
return {"success": False, "message": "缺少图片数据"}
|
||||
|
||||
# 解析 base64 数据
|
||||
if image_data.startswith('data:image/'):
|
||||
# 提取格式和base64内容
|
||||
header, base64_content = image_data.split(',', 1)
|
||||
# 从header中提取图片格式
|
||||
format_match = header.split(':')[1].split(';')[0] # 如 'image/png'
|
||||
ext = format_match.split('/')[1] if '/' in format_match else 'png'
|
||||
else:
|
||||
base64_content = image_data
|
||||
ext = 'png'
|
||||
|
||||
# 生成唯一文件名
|
||||
timestamp = int(time.time())
|
||||
unique_id = uuid.uuid4().hex[:8]
|
||||
safe_name = f"{timestamp}_{unique_id}.{ext}"
|
||||
|
||||
# 保存文件
|
||||
file_path = os.path.join(UPLOADS_DIR, safe_name)
|
||||
image_bytes = base64.b64decode(base64_content)
|
||||
|
||||
# 检查文件大小(限制10MB)
|
||||
if len(image_bytes) > 10 * 1024 * 1024:
|
||||
return {"success": False, "message": "图片大小超过10MB限制"}
|
||||
|
||||
with open(file_path, 'wb') as f:
|
||||
f.write(image_bytes)
|
||||
|
||||
# 返回可访问的URL路径
|
||||
url_path = f"/uploads/images/{safe_name}"
|
||||
logger.info(f"图片已保存: {file_path}, URL: {url_path}")
|
||||
|
||||
return {"success": True, "path": url_path, "name": safe_name}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"图片上传失败: {e}")
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
# ==================== 对话 API(保留原有) ====================
|
||||
|
||||
@app.get("/api/conversations")
|
||||
@@ -787,6 +849,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
# 处理文件内容,添加到消息
|
||||
image_contents = [] # 图片内容(用于视觉模型)
|
||||
text_contents = [] # 文本文件内容
|
||||
image_paths = [] # 图片服务器路径(用于历史记录显示)
|
||||
if files:
|
||||
for f in files:
|
||||
if f.get('type') and f['type'].startswith('image/'):
|
||||
@@ -796,6 +859,13 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
'type': f['type'],
|
||||
'data': f.get('content', '') # base64 数据
|
||||
})
|
||||
# 记录服务器路径(用于历史记录)
|
||||
if f.get('serverPath'):
|
||||
image_paths.append({
|
||||
'name': f['name'],
|
||||
'type': f['type'],
|
||||
'url': f['serverPath'] # 服务器文件路径
|
||||
})
|
||||
# 不添加文件名文本,图片信息保存在 extra_data 中
|
||||
elif f.get('content'):
|
||||
# 文本文件:直接添加内容,不带文件名前缀
|
||||
@@ -808,10 +878,16 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
for content in text_contents:
|
||||
message += f"\n\n{content}"
|
||||
|
||||
# 保存图片信息到 extra_data(用于历史记录)
|
||||
# 保存图片和文件信息到 extra_data(用于历史记录)
|
||||
extra_data_for_msg = None
|
||||
if image_contents:
|
||||
# 只保存图片 URL(不保存完整 base64)
|
||||
if image_paths:
|
||||
# 图片保存服务器路径URL,历史记录可以显示
|
||||
extra_data_for_msg = {
|
||||
'images': image_paths,
|
||||
'files': [{'name': f['name'], 'type': f['type']} for f in files if not f['type'].startswith('image/')]
|
||||
}
|
||||
elif image_contents:
|
||||
# 没有服务器路径但有问题(可能上传失败)
|
||||
extra_data_for_msg = {
|
||||
'images': [{'name': i['name'], 'type': i['type']} for i in image_contents],
|
||||
'files': [{'name': f['name'], 'type': f['type']} for f in files if not f['type'].startswith('image/')]
|
||||
@@ -969,7 +1045,8 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
messages=history,
|
||||
provider_config=agent_config['provider'],
|
||||
agent_config=agent_config['agent'],
|
||||
enable_thinking=enable_thinking
|
||||
enable_thinking=enable_thinking,
|
||||
images=image_contents # 传递图片数据给多模态模型
|
||||
)
|
||||
|
||||
logger.info(f"LLM响应: response长度={len(response)}, thinking长度={len(thinking_content) if thinking_content else 0}")
|
||||
|
||||
@@ -32,6 +32,10 @@ class LLMProvider(Base):
|
||||
supports_thinking = Column(Boolean, default=False) # 是否原生支持思考
|
||||
thinking_model = Column(String(100), nullable=True) # 思考模式模型名(如有单独模型)
|
||||
|
||||
# 视觉能力支持
|
||||
supports_vision = Column(Boolean, default=False) # 是否支持图片理解(多模态)
|
||||
vision_model = Column(String(100), nullable=True) # 视觉模型名(如与默认模型不同)
|
||||
|
||||
# 配额和限制
|
||||
max_tokens = Column(Integer, default=4096)
|
||||
temperature = Column(Float, default=0.7)
|
||||
|
||||
@@ -98,11 +98,19 @@ class LLMService:
|
||||
messages: List[Dict],
|
||||
provider_config: dict,
|
||||
agent_config: dict,
|
||||
enable_thinking: bool = True
|
||||
enable_thinking: bool = True,
|
||||
images: List[Dict] = None # 图片数据列表 [{'name', 'type', 'data': base64}]
|
||||
) -> Tuple[str, Optional[str]]:
|
||||
"""
|
||||
调用AI模型进行对话
|
||||
|
||||
Args:
|
||||
messages: 对话历史
|
||||
provider_config: LLM Provider配置
|
||||
agent_config: Agent配置
|
||||
enable_thinking: 是否启用思考
|
||||
images: 图片数据列表(用于多模态模型)
|
||||
|
||||
Returns:
|
||||
Tuple[str, Optional[str]]: (回复内容, 思考过程)
|
||||
"""
|
||||
@@ -123,6 +131,22 @@ class LLMService:
|
||||
if final_messages and final_messages[0]['role'] != 'system':
|
||||
final_messages.insert(0, {"role": "system", "content": system_prompt})
|
||||
|
||||
# 如果有图片,构建多模态消息(只修改最后一条用户消息)
|
||||
if images and len(images) > 0:
|
||||
# 找到最后一条用户消息
|
||||
for i in range(len(final_messages) - 1, -1, -1):
|
||||
if final_messages[i]['role'] == 'user':
|
||||
original_text = final_messages[i]['content']
|
||||
# 构建多模态内容
|
||||
multimodal_content = [{"type": "text", "text": original_text if original_text else "请描述这张图片"}]
|
||||
for img in images:
|
||||
multimodal_content.append({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": img['data']} # base64 data URL
|
||||
})
|
||||
final_messages[i]['content'] = multimodal_content
|
||||
break
|
||||
|
||||
thinking_content = None
|
||||
|
||||
# 处理思考功能
|
||||
@@ -208,7 +232,7 @@ class LLMService:
|
||||
temperature: float = 0.7
|
||||
) -> str:
|
||||
"""调用API"""
|
||||
url = f"{api_base}/chat/completions"
|
||||
url = f"{api_base.rstrip('/')}/chat/completions"
|
||||
headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json"
|
||||
@@ -220,13 +244,33 @@ class LLMService:
|
||||
"max_tokens": max_tokens
|
||||
}
|
||||
|
||||
# 打印请求详情(调试)
|
||||
logger.info(f"调用LLM: url={url}, model={model}")
|
||||
logger.info(f"消息数量: {len(messages)}, 第一条消息类型: {type(messages[0].get('content'))}")
|
||||
|
||||
async with httpx.AsyncClient(timeout=60.0) as client:
|
||||
response = await client.post(url, headers=headers, json=payload)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return data['choices'][0]['message']['content']
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=60.0) as client:
|
||||
response = await client.post(url, headers=headers, json=payload)
|
||||
|
||||
# 检查HTTP状态
|
||||
if response.status_code != 200:
|
||||
logger.error(f"API返回错误: status={response.status_code}, body={response.text[:500]}")
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
|
||||
# 检查响应格式
|
||||
if 'choices' not in data or len(data['choices']) == 0:
|
||||
logger.error(f"API响应格式错误: {data}")
|
||||
raise ValueError("API响应格式错误:缺少choices")
|
||||
|
||||
return data['choices'][0]['message']['content']
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"HTTP错误: {e.response.status_code}, {e.response.text}")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"API调用异常: {type(e).__name__}: {e}")
|
||||
raise
|
||||
|
||||
async def chat_stream(
|
||||
self,
|
||||
|
||||
@@ -58,8 +58,8 @@
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<table class="table">
|
||||
<thead><tr><th>名称</th><th>API地址</th><th>默认模型</th><th>思考支持</th><th>状态</th><th>操作</th></tr></thead>
|
||||
<tbody id="providers-list"><tr><td colspan="6" class="text-center">加载中...</td></tr></tbody>
|
||||
<thead><tr><th>名称</th><th>API地址</th><th>默认模型</th><th>思考</th><th>视觉</th><th>状态</th><th>操作</th></tr></thead>
|
||||
<tbody id="providers-list"><tr><td colspan="7" class="text-center">加载中...</td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
@@ -162,6 +162,8 @@
|
||||
<div class="mt-3 form-check"><input type="checkbox" class="form-check-input" id="provider-active" checked><label class="form-check-label">启用</label></div>
|
||||
<hr><h6>思考功能</h6>
|
||||
<div class="thinking-config"><div class="row"><div class="col-md-6 form-check"><input type="checkbox" class="form-check-input" id="provider-supports-thinking"><label class="form-check-label">支持原生思考</label></div><div class="col-md-6"><label class="form-label">思考模型名</label><input type="text" class="form-control" id="provider-thinking-model"></div></div></div>
|
||||
<hr><h6>视觉能力</h6>
|
||||
<div class="thinking-config"><div class="row"><div class="col-md-6 form-check"><input type="checkbox" class="form-check-input" id="provider-supports-vision"><label class="form-check-label">支持图片理解</label></div><div class="col-md-6"><label class="form-label">视觉模型名</label><input type="text" class="form-control" id="provider-vision-model" placeholder="留空则使用默认模型"></div></div><small class="text-muted mt-2 d-block">启用后可上传图片让AI识别分析内容</small></div>
|
||||
<div class="mt-3"><button type="button" class="btn btn-outline-primary" onclick="fetchProviderModels()"><i class="ri-refresh-line"></i> 获取模型</button><button type="button" class="btn btn-outline-secondary" onclick="testProviderConnection()"><i class="ri-link"></i> 测试连接</button></div>
|
||||
<div class="mt-2" id="provider-models-preview"></div><div class="mt-2" id="provider-test-result"></div>
|
||||
</form></div>
|
||||
@@ -181,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>
|
||||
@@ -250,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) {
|
||||
@@ -260,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() {
|
||||
@@ -274,6 +330,7 @@
|
||||
tbody.innerHTML = providersData.map(p => `<tr>
|
||||
<td><strong>${p.name}</strong></td><td><small>${p.api_base||'-'}</small></td><td>${p.default_model||'auto'}</td>
|
||||
<td>${p.supports_thinking?'<span class="badge bg-success">支持</span>':'<span class="badge bg-secondary">不支持</span>'}</td>
|
||||
<td>${p.supports_vision?'<span class="badge bg-info">支持</span>':'<span class="badge bg-secondary">不支持</span>'}</td>
|
||||
<td>${p.is_active?'<span class="badge bg-success">启用</span>':'<span class="badge bg-secondary">禁用</span>'}</td>
|
||||
<td><button class="btn btn-sm btn-outline-primary" onclick="editProvider(${p.id})"><i class="ri-edit-line"></i></button>
|
||||
<button class="btn btn-sm btn-outline-danger" onclick="deleteProvider(${p.id},'${p.name}')"><i class="ri-delete-bin-line"></i></button></td>
|
||||
@@ -290,6 +347,8 @@
|
||||
document.getElementById('provider-form').reset();
|
||||
document.getElementById('provider-id').value = '';
|
||||
document.getElementById('provider-active').checked = true;
|
||||
document.getElementById('provider-supports-thinking').checked = false;
|
||||
document.getElementById('provider-supports-vision').checked = false;
|
||||
document.getElementById('provider-models-preview').innerHTML = '';
|
||||
document.getElementById('provider-test-result').innerHTML = '';
|
||||
new bootstrap.Modal(document.getElementById('providerModal')).show();
|
||||
@@ -310,6 +369,8 @@
|
||||
document.getElementById('provider-active').checked = p.is_active;
|
||||
document.getElementById('provider-supports-thinking').checked = p.supports_thinking;
|
||||
document.getElementById('provider-thinking-model').value = p.thinking_model || '';
|
||||
document.getElementById('provider-supports-vision').checked = p.supports_vision;
|
||||
document.getElementById('provider-vision-model').value = p.vision_model || '';
|
||||
new bootstrap.Modal(document.getElementById('providerModal')).show();
|
||||
}
|
||||
|
||||
@@ -326,7 +387,9 @@
|
||||
description: document.getElementById('provider-description').value,
|
||||
is_active: document.getElementById('provider-active').checked,
|
||||
supports_thinking: document.getElementById('provider-supports-thinking').checked,
|
||||
thinking_model: document.getElementById('provider-thinking-model').value
|
||||
thinking_model: document.getElementById('provider-thinking-model').value,
|
||||
supports_vision: document.getElementById('provider-supports-vision').checked,
|
||||
vision_model: document.getElementById('provider-vision-model').value
|
||||
};
|
||||
const res = await fetch(id ? `/api/v2/providers/${id}` : '/api/v2/providers', { method: id ? 'PUT' : 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(data) });
|
||||
const result = await res.json();
|
||||
@@ -394,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();
|
||||
}
|
||||
|
||||
@@ -416,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,
|
||||
@@ -443,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();
|
||||
|
||||
@@ -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%; left: 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; }
|
||||
@@ -146,6 +184,17 @@
|
||||
.modal-buttons { display: flex; gap: 12px; justify-content: flex-end; }
|
||||
.modal-buttons button { padding: 8px 16px; border-radius: 8px; cursor: pointer; }
|
||||
|
||||
/* 图片放大弹窗 */
|
||||
.image-lightbox { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.9); display: none; align-items: center; justify-content: center; z-index: 2000; cursor: zoom-out; }
|
||||
.image-lightbox.show { display: flex; }
|
||||
.image-lightbox img { max-width: 90%; max-height: 90%; border-radius: 8px; box-shadow: 0 0 30px rgba(255,255,255,0.2); }
|
||||
.image-lightbox-close { position: absolute; top: 20px; right: 20px; width: 40px; height: 40px; background: rgba(255,255,255,0.2); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 20px; cursor: pointer; transition: background 0.2s; }
|
||||
.image-lightbox-close:hover { background: rgba(255,255,255,0.3); }
|
||||
|
||||
/* 对话中的图片可点击 */
|
||||
.uploaded-image img { cursor: zoom-in; transition: transform 0.2s; }
|
||||
.uploaded-image img:hover { transform: scale(1.02); }
|
||||
|
||||
.welcome { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: #666; }
|
||||
.welcome h2 { font-size: 28px; margin-bottom: 16px; color: #333; }
|
||||
|
||||
@@ -181,15 +230,27 @@
|
||||
<div class="input-row">
|
||||
<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>
|
||||
<!-- 工具按钮放附件右边 -->
|
||||
<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>
|
||||
<textarea id="messageInput" placeholder="输入消息..." rows="1"></textarea>
|
||||
<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>
|
||||
@@ -211,6 +272,34 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 图片放大弹窗 -->
|
||||
<div class="image-lightbox" id="imageLightbox" onclick="closeImageLightbox()">
|
||||
<div class="image-lightbox-close"><i class="ri-close-line"></i></div>
|
||||
<img id="lightboxImage" src="" alt="放大图片">
|
||||
</div>
|
||||
|
||||
<!-- 隐藏的图片上传API处理 -->
|
||||
<script>
|
||||
// 图片上传到服务器(保存文件)
|
||||
async function uploadImageToServer(base64Data, fileName) {
|
||||
try {
|
||||
const response = await fetch('/api/v2/upload-image', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ image: base64Data, name: fileName })
|
||||
});
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
return result.path; // 返回服务器文件路径
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
console.error('图片上传失败:', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Markdown渲染库 -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<script>
|
||||
@@ -221,6 +310,7 @@
|
||||
let currentConversationId = null;
|
||||
let currentAgentId = null;
|
||||
let agents = [];
|
||||
let providers = []; // 大模型池数据
|
||||
let quickPhrases = [];
|
||||
let lastSentMessage = null; // 记录最后发送的消息
|
||||
let lastSentFiles = null; // 记录发送的文件
|
||||
@@ -233,6 +323,8 @@
|
||||
let messageVersions = {}; // 存储每个assistant消息的多个版本 { messageId: [{content, thinking}] }
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
loadProviders(); // 加载大模型池
|
||||
loadToolsData(); // 加载工具列表
|
||||
loadAgents();
|
||||
loadQuickPhrases();
|
||||
connectWebSocket();
|
||||
@@ -240,6 +332,144 @@
|
||||
setupTextarea();
|
||||
});
|
||||
|
||||
// 加载大模型池
|
||||
async function loadProviders() {
|
||||
try {
|
||||
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); }
|
||||
}
|
||||
|
||||
// 检查当前Agent是否支持视觉
|
||||
function checkAgentVisionSupport() {
|
||||
const agent = agents.find(a => a.id === currentAgentId);
|
||||
if (!agent) return false;
|
||||
const provider = providers.find(p => p.id === agent.llm_provider_id);
|
||||
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 {
|
||||
@@ -249,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); }
|
||||
}
|
||||
|
||||
@@ -271,6 +505,8 @@
|
||||
if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ action: 'switch_agent', agent_id: currentAgentId }));
|
||||
await createNewConversation();
|
||||
showAgentSwitchNotice();
|
||||
// 切换Agent后检查工具支持
|
||||
showToolWarning();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,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>`;
|
||||
|
||||
@@ -393,19 +632,50 @@
|
||||
html += '</div>';
|
||||
div.innerHTML = html;
|
||||
|
||||
// 如果是用户消息且有搜索结果,在设置innerHTML后追加
|
||||
// 如果是用户消息且有额外数据(搜索结果、图片、文件),在设置innerHTML后追加
|
||||
if (role === 'user' && extraData) {
|
||||
console.log('Processing extraData for user message:', extraData);
|
||||
console.log('search_results exists:', extraData.search_results);
|
||||
const bodyDiv = div.querySelector('.message-body');
|
||||
|
||||
// 处理图片(如果有服务器URL,显示图片)
|
||||
if (extraData.images && extraData.images.length > 0) {
|
||||
let imagesHtml = '<div class="history-images" style="margin-top:8px;display:flex;gap:8px;flex-wrap:wrap;">';
|
||||
for (const img of extraData.images) {
|
||||
if (img.url) {
|
||||
// 有服务器URL,显示真实图片
|
||||
imagesHtml += `<div class="history-image" style="display:inline-block;">
|
||||
<img src="${img.url}" style="max-width:300px;max-height:200px;border-radius:8px;cursor:zoom-in;" onclick="openImageLightbox('${img.url}')">
|
||||
</div>`;
|
||||
} else {
|
||||
// 没有URL,显示占位符
|
||||
imagesHtml += `<div class="history-image-placeholder" style="padding:8px 12px;background:#f0f0f0;border-radius:8px;display:flex;align-items:center;gap:6px;font-size:13px;color:#666;">
|
||||
<i class="ri-image-line" style="color:#10a37f;"></i>
|
||||
<span>${escapeHtml(img.name || '图片')}</span>
|
||||
</div>`;
|
||||
}
|
||||
}
|
||||
imagesHtml += '</div>';
|
||||
if (bodyDiv) bodyDiv.insertAdjacentHTML('beforeend', imagesHtml);
|
||||
}
|
||||
|
||||
// 处理文本文件
|
||||
if (extraData.files && extraData.files.length > 0) {
|
||||
let filesHtml = '<div class="history-files" style="margin-top:8px;">';
|
||||
for (const f of extraData.files) {
|
||||
filesHtml += `<div class="history-file-placeholder" style="padding:6px 10px;background:#f5f5f5;border-radius:6px;margin-bottom:4px;display:flex;align-items:center;gap:6px;font-size:12px;color:#666;">
|
||||
<i class="ri-file-text-line" style="color:#10a37f;"></i>
|
||||
<span>${escapeHtml(f.name || '文件')}</span>
|
||||
</div>`;
|
||||
}
|
||||
filesHtml += '</div>';
|
||||
if (bodyDiv) bodyDiv.insertAdjacentHTML('beforeend', filesHtml);
|
||||
}
|
||||
|
||||
// 处理搜索结果
|
||||
if (extraData.search_results && extraData.search_results.length > 0) {
|
||||
console.log('Building search results HTML for', extraData.search_results.length, 'results');
|
||||
const searchHtml = buildSearchResultsHtml(extraData.search_results, extraData.search_query || content);
|
||||
const bodyDiv = div.querySelector('.message-body');
|
||||
console.log('bodyDiv found:', bodyDiv != null);
|
||||
if (bodyDiv) {
|
||||
bodyDiv.insertAdjacentHTML('beforeend', searchHtml);
|
||||
console.log('Search results HTML inserted');
|
||||
}
|
||||
if (bodyDiv) bodyDiv.insertAdjacentHTML('beforeend', searchHtml);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -653,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, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
@@ -798,6 +1198,26 @@
|
||||
// 如果没有消息且没有文件,不发送
|
||||
if (!msg && pendingFiles.length === 0) return;
|
||||
|
||||
// 检查是否有图片上传
|
||||
const hasImages = pendingFiles.some(f => f.type && f.type.startsWith('image/'));
|
||||
if (hasImages && !checkAgentVisionSupport()) {
|
||||
const agent = agents.find(a => a.id === currentAgentId);
|
||||
const agentName = agent?.display_name || agent?.name || '当前Agent';
|
||||
alert(`⚠️ ${agentName} 不支持图片识别功能\n\n请选择支持视觉能力的Agent(如 vlm-agent),或者移除图片后再发送。`);
|
||||
document.getElementById('sendBtn').disabled = false;
|
||||
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';
|
||||
@@ -810,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) {
|
||||
@@ -852,13 +1275,15 @@
|
||||
lastSentFiles = files.map(f => ({
|
||||
name: f.name,
|
||||
type: f.type,
|
||||
content: f.content
|
||||
content: f.content,
|
||||
serverPath: f.serverPath // 服务器路径(用于历史记录)
|
||||
}));
|
||||
|
||||
for (const f of files) {
|
||||
if (f.type.startsWith('image/')) {
|
||||
// 图片直接显示
|
||||
html += `<div class="uploaded-image" style="margin-bottom:8px"><img src="${f.content}" style="max-width:300px;border-radius:8px"></div>`;
|
||||
// 图片直接显示(用服务器路径或base64)
|
||||
const imgSrc = f.serverPath || f.content;
|
||||
html += `<div class="uploaded-image" style="margin-bottom:8px"><img src="${f.content}" style="max-width:300px;border-radius:8px" onclick="openImageLightbox('${imgSrc}')"></div>`;
|
||||
} else {
|
||||
// 文本文件显示名称和内容摘要
|
||||
html += `<div class="uploaded-file" style="padding:8px;background:#f5f5f5;border-radius:6px;margin-bottom:8px">`;
|
||||
@@ -883,7 +1308,7 @@
|
||||
}
|
||||
|
||||
// 文件上传处理
|
||||
function handleFileUpload(event) {
|
||||
async function handleFileUpload(event) {
|
||||
const files = event.target.files;
|
||||
const previewArea = document.getElementById('filePreviewArea');
|
||||
|
||||
@@ -892,13 +1317,23 @@
|
||||
|
||||
// 读取文件内容
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
reader.onload = async (e) => {
|
||||
const base64Content = e.target.result;
|
||||
|
||||
// 图片:先上传到服务器保存
|
||||
let serverPath = null;
|
||||
if (file.type.startsWith('image/')) {
|
||||
serverPath = await uploadImageToServer(base64Content, file.name);
|
||||
console.log('图片上传结果:', serverPath);
|
||||
}
|
||||
|
||||
const fileData = {
|
||||
id: fileId,
|
||||
name: file.name,
|
||||
type: file.type,
|
||||
size: file.size,
|
||||
content: e.target.result
|
||||
content: base64Content, // base64数据(用于多模态模型)
|
||||
serverPath: serverPath // 服务器路径(用于历史记录显示)
|
||||
};
|
||||
pendingFiles.push(fileData);
|
||||
|
||||
@@ -909,8 +1344,9 @@
|
||||
|
||||
if (file.type.startsWith('image/')) {
|
||||
previewItem.classList.add('image-preview');
|
||||
// 预览用本地base64,显示更快
|
||||
previewItem.innerHTML = `
|
||||
<img src="${e.target.result}" alt="${file.name}">
|
||||
<img src="${base64Content}" alt="${file.name}" style="cursor:pointer" onclick="openImageLightbox('${serverPath || base64Content}')">
|
||||
<button class="file-remove" onclick="removeFile('${fileId}')"><i class="ri-close-line"></i></button>
|
||||
`;
|
||||
} else {
|
||||
@@ -931,6 +1367,21 @@
|
||||
}
|
||||
|
||||
previewArea.appendChild(previewItem);
|
||||
|
||||
// 如果上传的是图片且当前Agent不支持视觉,显示警告提示
|
||||
if (file.type.startsWith('image/') && !checkAgentVisionSupport()) {
|
||||
const agent = agents.find(a => a.id === currentAgentId);
|
||||
const agentName = agent?.display_name || agent?.name || '当前Agent';
|
||||
const warningDiv = document.createElement('div');
|
||||
warningDiv.className = 'vision-warning';
|
||||
warningDiv.id = 'vision-warning-tip';
|
||||
warningDiv.style.cssText = 'margin-top:8px;padding:8px 12px;background:#fff3cd;border:1px solid #ffc107;border-radius:6px;font-size:13px;color:#856404;';
|
||||
warningDiv.innerHTML = `<i class="ri-alert-line"></i> <strong>${agentName}</strong> 不支持图片识别,请选择支持视觉的Agent或移除图片`;
|
||||
// 避免重复添加
|
||||
if (!document.getElementById('vision-warning-tip')) {
|
||||
previewArea.appendChild(warningDiv);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 根据文件类型选择读取方式
|
||||
@@ -952,6 +1403,13 @@
|
||||
pendingFiles = pendingFiles.filter(f => f.id !== fileId);
|
||||
const preview = document.getElementById(fileId + '-preview');
|
||||
if (preview) preview.remove();
|
||||
|
||||
// 如果没有图片了,移除视觉警告提示
|
||||
const hasImages = pendingFiles.some(f => f.type && f.type.startsWith('image/'));
|
||||
if (!hasImages) {
|
||||
const warning = document.getElementById('vision-warning-tip');
|
||||
if (warning) warning.remove();
|
||||
}
|
||||
}
|
||||
|
||||
// 发送消息
|
||||
@@ -1014,6 +1472,26 @@
|
||||
}
|
||||
|
||||
document.getElementById('newPhraseInput').addEventListener('keydown', e => { if (e.key === 'Enter') addPhrase(); if (e.key === 'Escape') hidePhraseModal(); });
|
||||
|
||||
// 图片放大弹窗
|
||||
function openImageLightbox(imageSrc) {
|
||||
const lightbox = document.getElementById('imageLightbox');
|
||||
const lightboxImg = document.getElementById('lightboxImage');
|
||||
lightboxImg.src = imageSrc;
|
||||
lightbox.classList.add('show');
|
||||
}
|
||||
|
||||
function closeImageLightbox() {
|
||||
const lightbox = document.getElementById('imageLightbox');
|
||||
lightbox.classList.remove('show');
|
||||
}
|
||||
|
||||
// ESC键关闭图片弹窗
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key === 'Escape') {
|
||||
closeImageLightbox();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
BIN
uploads/images/1776134549_0c993820.jpeg
Normal file
BIN
uploads/images/1776134549_0c993820.jpeg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 225 KiB |
BIN
uploads/images/1776134674_10f77dae.png
Normal file
BIN
uploads/images/1776134674_10f77dae.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 147 KiB |
BIN
uploads/images/1776137541_298f5318.png
Normal file
BIN
uploads/images/1776137541_298f5318.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 147 KiB |
Reference in New Issue
Block a user