2 Commits

Author SHA1 Message Date
db114269f9 feat: 添加对话功能
新增功能:
- 对话页面 (/chat)
- 选择不同模型进行对话
- 历史对话保存和加载
- 支持继续历史对话

API:
- GET /api/chat/models - 获取可用模型
- GET /api/chat/list - 获取对话列表
- GET /api/chat/<id> - 获取对话详情
- POST /api/chat/send - 发送消息
- DELETE /api/chat/<id> - 删除对话
- POST /api/chat/<id>/clear - 清空对话
2026-04-09 18:29:54 +08:00
a3b4376871 style: Auto配置页面改用Tailwind CSS风格,与其他页面保持一致 2026-04-09 18:08:41 +08:00
7 changed files with 823 additions and 186 deletions

View File

@@ -94,6 +94,10 @@ def logs_page():
def config_page():
return render_template('config.html')
@app.route('/chat')
def chat_page():
return render_template('chat.html')
@app.route('/auto-profiles')
def auto_profiles_page():
return render_template('auto-profiles.html')
@@ -431,6 +435,206 @@ def api_reload_config():
# 这里只返回成功,实际重载由主服务自己处理
return jsonify({'success': True, 'message': 'Config saved, restart main service to apply'})
# ============ 对话功能 ============
CHATS_FILE = DATA_DIR / 'chats.json'
def load_chats():
"""加载对话数据"""
if CHATS_FILE.exists():
return json.loads(CHATS_FILE.read_text(encoding='utf-8'))
return {'chats': []}
def save_chats(data):
"""保存对话数据"""
CHATS_FILE.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
@app.route('/api/chat/models')
def api_chat_models():
"""获取可用模型列表"""
providers = get_providers()
profiles = get_auto_profiles()
models = []
added = set()
# 添加所有auto配置
for name, profile in profiles.items():
if name not in added:
models.append({
'id': name,
'description': profile.get('description', 'Auto-select')
})
added.add(name)
# 添加提供商的模型
for provider in providers:
if not provider['enabled']:
continue
for model in provider['models']:
if model not in added:
models.append({
'id': model,
'description': provider['name']
})
added.add(model)
return jsonify(models)
@app.route('/api/chat/list')
def api_chat_list():
"""获取对话列表"""
data = load_chats()
chats = []
for chat in data.get('chats', []):
chats.append({
'id': chat['id'],
'title': chat.get('title', '新对话'),
'model': chat.get('model', 'auto'),
'message_count': len(chat.get('messages', [])),
'created_at': chat.get('created_at'),
'updated_at': chat.get('updated_at')
})
# 按更新时间倒序
chats.sort(key=lambda x: x.get('updated_at', ''), reverse=True)
return jsonify(chats)
@app.route('/api/chat/<chat_id>')
def api_chat_detail(chat_id):
"""获取对话详情"""
data = load_chats()
for chat in data.get('chats', []):
if chat['id'] == chat_id:
return jsonify(chat)
return jsonify({'error': 'Chat not found'}), 404
@app.route('/api/chat/send', methods=['POST'])
def api_chat_send():
"""发送消息"""
req = request.get_json()
user_message = req.get('message', '')
model = req.get('model', 'auto')
chat_id = req.get('chat_id')
if not user_message:
return jsonify({'error': 'Message is required'}), 400
data = load_chats()
# 查找或创建对话
chat = None
if chat_id:
for c in data['chats']:
if c['id'] == chat_id:
chat = c
break
if not chat:
chat_id = str(uuid.uuid4())[:8]
chat = {
'id': chat_id,
'title': '新对话',
'model': model,
'messages': [],
'created_at': datetime.now().isoformat(),
'updated_at': datetime.now().isoformat()
}
data['chats'].append(chat)
# 添加用户消息
chat['messages'].append({
'role': 'user',
'content': user_message,
'time': datetime.now().isoformat()
})
# 调用LLM API
try:
proxy_url = f"http://localhost:{SERVER_CONFIG['port']}/v1/chat/completions"
# 构建消息历史
messages = []
for msg in chat['messages'][-20:]: # 最多保留20条历史
messages.append({
'role': msg['role'],
'content': msg['content']
})
response = requests.post(proxy_url, json={
'model': model,
'messages': messages,
'stream': False
}, timeout=120)
if response.status_code == 200:
result = response.json()
assistant_message = result['choices'][0]['message']['content']
used_model = result.get('model', model)
# 添加助手消息
chat['messages'].append({
'role': 'assistant',
'content': assistant_message,
'model': used_model,
'time': datetime.now().isoformat()
})
# 更新标题(如果是第一条消息)
if len(chat['messages']) == 2:
chat['title'] = user_message[:30] + ('...' if len(user_message) > 30 else '')
chat['updated_at'] = datetime.now().isoformat()
save_chats(data)
return jsonify({
'success': True,
'chat_id': chat_id,
'response': assistant_message,
'model': used_model,
'title': chat['title']
})
else:
error_msg = response.json().get('error', {}).get('message', 'Unknown error')
return jsonify({'error': error_msg}), response.status_code
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/chat/<chat_id>', methods=['DELETE'])
def api_delete_chat(chat_id):
"""删除对话"""
data = load_chats()
data['chats'] = [c for c in data['chats'] if c['id'] != chat_id]
save_chats(data)
return jsonify({'success': True})
@app.route('/api/chat/<chat_id>/clear', methods=['POST'])
def api_clear_chat(chat_id):
"""清空对话消息"""
data = load_chats()
for chat in data['chats']:
if chat['id'] == chat_id:
chat['messages'] = []
chat['updated_at'] = datetime.now().isoformat()
save_chats(data)
return jsonify({'success': True})
return jsonify({'error': 'Chat not found'}), 404
@app.route('/api/requests/recent')
def api_recent_requests():
"""获取最近请求记录"""

View File

@@ -4,123 +4,141 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Auto配置管理 - LLM Proxy</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
<style>
body { background-color: #f8f9fa; }
.provider-item { cursor: move; transition: all 0.2s; }
.provider-item:hover { background-color: #f0f0f0; }
.provider-item.selected { border-color: #198754; background-color: #f0fff0; }
.provider-item.disabled { opacity: 0.5; }
.drag-handle { cursor: grab; }
.profile-card { transition: all 0.2s; }
.profile-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.gradient-bg { background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); }
.dragging { opacity: 0.5; transform: scale(1.02); }
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="/">
<i class="bi bi-cpu"></i> LLM Proxy Admin
</a>
<div class="navbar-nav ms-auto">
<a class="nav-link" href="/">仪表盘</a>
<a class="nav-link" href="/providers">提供商</a>
<a class="nav-link" href="/models">模型</a>
<a class="nav-link active" href="/auto-profiles">Auto配置</a>
<a class="nav-link" href="/logs">日志</a>
<a class="nav-link" href="/config">配置</a>
<body class="bg-gray-50 min-h-screen">
<div class="flex">
<aside class="w-64 bg-slate-800 min-h-screen fixed left-0 top-0">
<div class="p-6">
<h1 class="text-white text-xl font-bold flex items-center gap-2">
<i class="ri-route-line text-2xl text-purple-400"></i>
LLM Proxy
</h1>
<p class="text-slate-400 text-sm mt-1">后台管理</p>
</div>
</div>
</nav>
<nav class="mt-6">
<a href="/" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-dashboard-line"></i><span>仪表盘</span>
</a>
<a href="/providers" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-server-line"></i><span>提供商管理</span>
</a>
<a href="/models" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-cpu-line"></i><span>模型管理</span>
</a>
<a href="/auto-profiles" class="flex items-center gap-3 px-6 py-3 bg-slate-700 text-white">
<i class="ri-shuffle-line"></i><span>Auto配置</span>
</a>
<a href="/chat" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-chat-3-line"></i><span>对话</span>
</a>
<a href="/logs" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-file-list-line"></i><span>日志查看</span>
</a>
<a href="/config" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-settings-3-line"></i><span>系统配置</span>
</a>
</nav>
</aside>
<div class="container py-4">
<div class="d-flex justify-content-between align-items-center mb-4">
<h4><i class="bi bi-shuffle"></i> Auto配置管理</h4>
<button class="btn btn-primary" onclick="showCreateModal()">
<i class="bi bi-plus-lg"></i> 创建Auto配置
</button>
</div>
<main class="ml-64 flex-1 p-8">
<!-- 顶部操作栏 -->
<div class="flex justify-between items-center mb-6">
<div>
<h1 class="text-2xl font-bold text-gray-800">Auto配置管理</h1>
<p class="text-gray-500 text-sm mt-1">创建自定义的自动选择模式,指定候选提供商和优先级</p>
</div>
<button onclick="showCreateModal()" class="px-4 py-2 gradient-bg text-white rounded-lg hover:opacity-90 transition">
<i class="ri-add-line mr-1"></i> 创建Auto配置
</button>
</div>
<div class="alert alert-info">
<i class="bi bi-info-circle"></i>
<strong>Auto配置</strong>允许您创建自定义的自动选择模式,指定哪些提供商参与选择以及优先级顺序。
例如<code>auto-fast</code> 只选择响应快的模型<code>auto-cheap</code> 只选择便宜的模型
</div>
<!-- 说明卡片 -->
<div class="mb-6 p-4 bg-indigo-50 rounded-lg text-sm text-indigo-600">
<i class="ri-information-line mr-1"></i>
<strong>Auto配置</strong>创建自定义的模型自动选择模式。例如 <code>model="auto-fast"</code> 只选择响应快的提供商<code>model="auto-cheap"</code> 只选择便宜的提供商
</div>
<div id="profilesList" class="row">
<div class="col-12 text-center py-4">
<div class="spinner-border text-primary"></div>
<p class="mt-2">加载中...</p>
<!-- 配置列表 -->
<div id="profilesList" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<p class="text-gray-500 col-span-full text-center py-8">加载中...</p>
</div>
</main>
</div>
<!-- 创建/编辑弹窗 -->
<div id="editModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50 p-4">
<div class="bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
<div class="p-6 border-b flex justify-between items-center">
<h2 class="text-xl font-bold text-gray-800" id="modalTitle">创建Auto配置</h2>
<button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
<i class="ri-close-line text-2xl"></i>
</button>
</div>
<div class="p-6 overflow-y-auto flex-1">
<form id="profileForm">
<input type="hidden" id="profileId">
<div class="grid grid-cols-2 gap-4 mb-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">配置名称</label>
<input type="text" id="profileName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
placeholder="例如: auto-fast, auto-cheap">
<p class="text-xs text-gray-500 mt-1">调用时使用 model="此名称"</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">显示名称</label>
<input type="text" id="displayName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
placeholder="例如: 快速模式">
</div>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">描述</label>
<textarea id="profileDesc" rows="2" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
placeholder="描述这个配置的用途"></textarea>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">选择策略</label>
<select id="profileStrategy" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
<option value="priority">按优先级选择(推荐)</option>
<option value="random">随机选择</option>
</select>
<p class="text-xs text-gray-500 mt-1">按优先级会选择列表中第一个可用的提供商</p>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-2">候选提供商(可拖拽调整优先级)</label>
<div id="providerList" class="border border-gray-200 rounded-lg p-3 space-y-2 min-h-[100px] bg-gray-50">
<!-- 提供商列表 -->
</div>
<p class="text-xs text-gray-500 mt-1">勾选参与自动选择的提供商,拖拽调整优先级</p>
</div>
</form>
</div>
<div class="p-6 border-t bg-gray-50 flex justify-end gap-3">
<button onclick="closeModal()" class="px-4 py-2 text-gray-600 hover:text-gray-800 transition">取消</button>
<button onclick="saveProfile()" class="px-4 py-2 gradient-bg text-white rounded-lg hover:opacity-90 transition">
<i class="ri-save-line mr-1"></i> 保存
</button>
</div>
</div>
</div>
<!-- 创建/编辑模态框 -->
<div class="modal fade" id="profileModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalTitle">创建Auto配置</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<form id="profileForm">
<input type="hidden" id="profileId">
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label">配置名称</label>
<input type="text" class="form-control" id="profileName"
placeholder="例如: auto-fast, auto-cheap" required>
<small class="text-muted">模型调用时使用此名称,如 model="auto-fast"</small>
</div>
<div class="col-md-6 mb-3">
<label class="form-label">显示名称</label>
<input type="text" class="form-control" id="displayName"
placeholder="例如: 快速模式, 经济模式">
</div>
</div>
<div class="mb-3">
<label class="form-label">描述</label>
<textarea class="form-control" id="profileDesc" rows="2"
placeholder="描述这个Auto配置的用途"></textarea>
</div>
<div class="mb-3">
<label class="form-label">选择策略</label>
<select class="form-select" id="profileStrategy">
<option value="priority">按优先级(推荐)</option>
<option value="random">随机选择</option>
</select>
<small class="text-muted">按优先级会选择列表中第一个可用的提供商</small>
</div>
<div class="mb-3">
<label class="form-label">候选提供商(拖拽调整优先级)</label>
<div id="providerList" class="border rounded p-2" style="min-height: 100px;">
<!-- 提供商列表将通过JS加载 -->
</div>
<small class="text-muted">勾选参与自动选择的提供商,拖拽调整优先级</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="saveProfile()">保存</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
let providers = [];
let profiles = [];
// 加载提供商和配置
// 加载数据
async function loadData() {
const [providersRes, profilesRes] = await Promise.all([
fetch('/api/providers'),
@@ -139,67 +157,73 @@
if (profiles.length === 0) {
container.innerHTML = `
<div class="col-12 text-center py-4 text-muted">
<i class="bi bi-inbox display-4"></i>
<p class="mt-2">暂无Auto配置</p>
<div class="col-span-full text-center py-12">
<i class="ri-inbox-line text-4xl text-gray-300"></i>
<p class="text-gray-500 mt-2">暂无Auto配置</p>
<button onclick="showCreateModal()" class="mt-4 px-4 py-2 gradient-bg text-white rounded-lg">
<i class="ri-add-line mr-1"></i> 创建第一个配置
</button>
</div>
`;
return;
}
container.innerHTML = profiles.map(profile => `
<div class="col-md-6 col-lg-4 mb-3">
<div class="card profile-card h-100">
<div class="card-header d-flex justify-content-between align-items-center">
<h6 class="mb-0">
<code>${profile.name}</code>
${profile.name === 'auto' ? '<span class="badge bg-secondary ms-2">默认</span>' : ''}
</h6>
<div class="dropdown">
<button class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
<i class="bi bi-three-dots"></i>
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#" onclick="editProfile('${profile.name}')">
<i class="bi bi-pencil"></i> 编辑
</a></li>
${profile.name !== 'auto' ? `
<li><a class="dropdown-item text-danger" href="#" onclick="deleteProfile('${profile.name}')">
<i class="bi bi-trash"></i> 删除
</a></li>
` : ''}
</ul>
</div>
<div class="bg-white rounded-xl border border-gray-200 hover:shadow-md transition">
<div class="p-4 border-b flex justify-between items-center">
<div>
<code class="text-indigo-600 font-semibold">${profile.name}</code>
${profile.name === 'auto' ? '<span class="ml-2 px-2 py-0.5 bg-gray-100 text-gray-600 text-xs rounded">默认</span>' : ''}
</div>
<div class="card-body">
<h6 class="card-title">${profile.display_name || profile.name}</h6>
<p class="card-text small text-muted">${profile.description || '暂无描述'}</p>
<div class="mt-2">
<span class="badge bg-info">${profile.strategy === 'priority' ? '按优先级' : '随机'}</span>
<span class="badge bg-secondary">${profile.provider_details?.length || 0} 个提供商</span>
</div>
<div class="mt-2">
${profile.provider_details?.slice(0, 3).map(p =>
`<span class="badge bg-light text-dark me-1">${p.name}</span>`
).join('') || ''}
${(profile.provider_details?.length || 0) > 3 ?
`<span class="text-muted small">+${profile.provider_details.length - 3} 更多</span>` : ''}
</div>
<div class="flex gap-1">
${profile.name !== 'auto' ? `
<button onclick="editProfile('${profile.name}')" class="p-2 text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition">
<i class="ri-pencil-line"></i>
</button>
<button onclick="deleteProfile('${profile.name}')" class="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition">
<i class="ri-delete-bin-line"></i>
</button>
` : `
<button onclick="editProfile('${profile.name}')" class="p-2 text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition">
<i class="ri-pencil-line"></i>
</button>
`}
</div>
</div>
<div class="p-4">
<h3 class="font-medium text-gray-800">${profile.display_name || profile.name}</h3>
<p class="text-sm text-gray-500 mt-1">${profile.description || '暂无描述'}</p>
<div class="flex gap-2 mt-3">
<span class="px-2 py-1 bg-indigo-50 text-indigo-600 text-xs rounded">
${profile.strategy === 'priority' ? '按优先级' : '随机'}
</span>
<span class="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded">
${profile.provider_details?.length || 0} 个提供商
</span>
</div>
<div class="mt-3 flex flex-wrap gap-1">
${profile.provider_details?.slice(0, 4).map(p =>
`<span class="px-2 py-0.5 bg-slate-100 text-slate-600 text-xs rounded">${p.name}</span>`
).join('') || ''}
${(profile.provider_details?.length || 0) > 4 ?
`<span class="text-xs text-gray-400">+${profile.provider_details.length - 4}</span>` : ''}
</div>
</div>
</div>
`).join('');
}
// 显示创建模态框
// 显示创建弹窗
function showCreateModal() {
document.getElementById('modalTitle').textContent = '创建Auto配置';
document.getElementById('profileId').value = '';
document.getElementById('profileForm').reset();
document.getElementById('profileName').disabled = false;
renderProviderList([]);
new bootstrap.Modal(document.getElementById('profileModal')).show();
document.getElementById('editModal').classList.remove('hidden');
document.getElementById('editModal').classList.add('flex');
}
// 编辑配置
@@ -217,7 +241,14 @@
renderProviderList(profile.provider_details || []);
new bootstrap.Modal(document.getElementById('profileModal')).show();
document.getElementById('editModal').classList.remove('hidden');
document.getElementById('editModal').classList.add('flex');
}
// 关闭弹窗
function closeModal() {
document.getElementById('editModal').classList.add('hidden');
document.getElementById('editModal').classList.remove('flex');
}
// 渲染提供商列表
@@ -225,7 +256,6 @@
const container = document.getElementById('providerList');
const selectedIds = selectedProviders.map(p => p.id);
// 按 priority 排序
const sortedProviders = [...providers].sort((a, b) => a.priority - b.priority);
container.innerHTML = sortedProviders.map(p => {
@@ -233,26 +263,21 @@
const isAll = p.id === '*';
return `
<div class="provider-item border rounded p-2 mb-2 ${isSelected ? 'selected' : ''} ${isAll ? 'bg-light' : ''}"
<div class="flex items-center gap-3 p-3 bg-white rounded-lg border ${isSelected ? 'border-indigo-500 bg-indigo-50' : 'border-gray-200'} hover:border-indigo-300 transition cursor-move"
data-id="${p.id}" data-priority="${p.priority}">
<div class="d-flex align-items-center">
<i class="bi bi-grip-vertical drag-handle me-2 text-muted"></i>
<div class="form-check me-3">
<input type="checkbox" class="form-check-input provider-check"
id="provider-${p.id}" ${isSelected ? 'checked' : ''}
${isAll ? 'onchange="toggleAllProviders(this)"' : ''}>
<i class="ri-drag-move-2 text-gray-400 cursor-grab"></i>
<input type="checkbox" class="provider-check w-4 h-4 text-indigo-600 rounded"
id="provider-${p.id}" ${isSelected ? 'checked' : ''}
onchange="this.closest('[data-id]').classList.toggle('border-indigo-500', this.checked);this.closest('[data-id]').classList.toggle('bg-indigo-50', this.checked)">
<div class="flex-1 min-w-0">
<div class="font-medium text-gray-800 truncate">${p.name}</div>
<div class="text-xs text-gray-500">
优先级 ${p.priority} · ${p.models?.slice(0, 2).join(', ')}${p.models?.length > 2 ? '...' : ''}
</div>
<div class="flex-grow-1">
<div class="fw-bold">${p.name}</div>
<small class="text-muted">
优先级: ${p.priority} |
模型: ${p.models?.slice(0, 2).join(', ')}${p.models?.length > 2 ? '...' : ''}
</small>
</div>
${p.available ?
'<span class="badge bg-success">可用</span>' :
'<span class="badge bg-danger">不可用</span>'}
</div>
${p.available ?
'<span class="px-2 py-0.5 bg-green-100 text-green-700 text-xs rounded">可用</span>' :
'<span class="px-2 py-0.5 bg-red-100 text-red-700 text-xs rounded">不可用</span>'}
</div>
`;
}).join('');
@@ -260,19 +285,8 @@
// 初始化拖拽排序
new Sortable(container, {
animation: 150,
handle: '.drag-handle',
ghostClass: 'bg-info bg-opacity-10',
});
}
// 切换所有提供商
function toggleAllProviders(checkbox) {
const checks = document.querySelectorAll('.provider-check');
checks.forEach(c => {
if (c.id !== 'provider-*') {
c.checked = checkbox.checked;
c.closest('.provider-item').classList.toggle('selected', checkbox.checked);
}
handle: '.ri-drag-move-2',
ghostClass: 'dragging',
});
}
@@ -290,17 +304,9 @@
// 收集选中的提供商
const selectedProviders = [];
const allCheckbox = document.getElementById('provider-*');
if (allCheckbox?.checked) {
selectedProviders.push('*');
} else {
document.querySelectorAll('.provider-check:checked').forEach(c => {
if (c.id !== 'provider-*') {
selectedProviders.push(c.dataset?.id || c.id.replace('provider-', ''));
}
});
}
document.querySelectorAll('.provider-check:checked').forEach(c => {
selectedProviders.push(c.id.replace('provider-', ''));
});
const data = {
name: profileName,
@@ -324,7 +330,7 @@
const result = await res.json();
if (result.success) {
bootstrap.Modal.getInstance(document.getElementById('profileModal')).hide();
closeModal();
loadData();
} else {
alert('保存失败: ' + (result.error || '未知错误'));

415
admin/templates/chat.html Normal file
View File

@@ -0,0 +1,415 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>对话 - LLM Proxy</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
<style>
.gradient-bg { background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); }
.chat-container { height: calc(100vh - 200px); }
.message-user { background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); }
.message-assistant { background: #f3f4f6; }
.typing-indicator span { animation: blink 1.4s infinite both; }
.typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
.typing-indicator span:nth-child(3) { animation-delay: 0.4s; }
@keyframes blink { 0%, 60%, 100% { opacity: 0.3; } 30% { opacity: 1; } }
</style>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
primary: '#6366f1',
}
}
}
}
</script>
</head>
<body class="bg-gray-50 min-h-screen">
<div class="flex">
<!-- 侧边栏 -->
<aside class="w-64 bg-slate-800 min-h-screen fixed left-0 top-0">
<div class="p-6">
<h1 class="text-white text-xl font-bold flex items-center gap-2">
<i class="ri-route-line text-2xl text-purple-400"></i>
LLM Proxy
</h1>
<p class="text-slate-400 text-sm mt-1">后台管理</p>
</div>
<nav class="mt-6">
<a href="/" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-dashboard-line"></i><span>仪表盘</span>
</a>
<a href="/providers" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-server-line"></i><span>提供商管理</span>
</a>
<a href="/models" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-cpu-line"></i><span>模型管理</span>
</a>
<a href="/auto-profiles" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-shuffle-line"></i><span>Auto配置</span>
</a>
<a href="/chat" class="flex items-center gap-3 px-6 py-3 bg-slate-700 text-white">
<i class="ri-chat-3-line"></i><span>对话</span>
</a>
<a href="/logs" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-file-list-line"></i><span>日志查看</span>
</a>
<a href="/config" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-settings-3-line"></i><span>系统配置</span>
</a>
</nav>
</aside>
<!-- 主内容区 -->
<main class="ml-64 flex-1 flex">
<!-- 历史对话列表 -->
<div class="w-72 bg-white border-r flex flex-col">
<div class="p-4 border-b flex justify-between items-center">
<h2 class="font-semibold text-gray-800">历史对话</h2>
<button onclick="newChat()" class="p-2 text-primary hover:bg-indigo-50 rounded-lg transition" title="新建对话">
<i class="ri-add-line text-xl"></i>
</button>
</div>
<div id="chatList" class="flex-1 overflow-y-auto p-2 space-y-1">
<p class="text-gray-400 text-sm text-center py-4">加载中...</p>
</div>
</div>
<!-- 对话区域 -->
<div class="flex-1 flex flex-col">
<!-- 顶部工具栏 -->
<div class="bg-white border-b px-6 py-3 flex items-center justify-between">
<div class="flex items-center gap-4">
<select id="modelSelect" class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary">
<option value="auto">auto (自动选择)</option>
</select>
<span id="chatTitle" class="text-gray-600">新对话</span>
</div>
<div class="flex items-center gap-2">
<button onclick="clearCurrentChat()" class="px-3 py-2 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-lg transition" title="清空对话">
<i class="ri-delete-bin-line"></i>
</button>
</div>
</div>
<!-- 消息区域 -->
<div id="messagesContainer" class="flex-1 overflow-y-auto p-6 space-y-4 bg-gray-50">
<div class="text-center text-gray-400 py-12">
<i class="ri-chat-3-line text-4xl"></i>
<p class="mt-2">开始新对话</p>
</div>
</div>
<!-- 输入区域 -->
<div class="bg-white border-t px-6 py-4">
<div class="flex gap-3">
<textarea id="messageInput"
class="flex-1 px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary resize-none"
placeholder="输入消息... (Shift+Enter换行Enter发送)"
rows="1"
onkeydown="handleKeyDown(event)"></textarea>
<button onclick="sendMessage()" id="sendBtn" class="px-6 py-3 gradient-bg text-white rounded-xl hover:opacity-90 transition flex items-center gap-2">
<i class="ri-send-plane-fill"></i>
<span>发送</span>
</button>
</div>
</div>
</div>
</main>
</div>
<script>
let chats = [];
let currentChatId = null;
let models = [];
let isLoading = false;
// 初始化
async function init() {
await Promise.all([loadModels(), loadChats()]);
updateModelSelect();
// 如果有对话,加载第一个
if (chats.length > 0) {
loadChat(chats[0].id);
}
}
// 加载模型列表
async function loadModels() {
const res = await fetch('/api/chat/models');
models = await res.json();
}
// 更新模型选择器
function updateModelSelect() {
const select = document.getElementById('modelSelect');
select.innerHTML = models.map(m =>
`<option value="${m.id}">${m.id}${m.description ? ' - ' + m.description : ''}</option>`
).join('');
}
// 加载对话列表
async function loadChats() {
const res = await fetch('/api/chat/list');
chats = await res.json();
renderChatList();
}
// 渲染对话列表
function renderChatList() {
const container = document.getElementById('chatList');
if (chats.length === 0) {
container.innerHTML = `
<div class="text-center text-gray-400 py-8">
<i class="ri-chat-off-line text-2xl"></i>
<p class="text-sm mt-2">暂无对话</p>
</div>
`;
return;
}
container.innerHTML = chats.map(chat => `
<div onclick="loadChat('${chat.id}')"
class="p-3 rounded-lg cursor-pointer transition ${currentChatId === chat.id ? 'bg-indigo-100 border border-indigo-300' : 'hover:bg-gray-100'}">
<div class="flex justify-between items-start">
<div class="flex-1 min-w-0">
<div class="font-medium text-gray-800 truncate">${chat.title || '新对话'}</div>
<div class="text-xs text-gray-500 mt-1">${chat.message_count || 0} 条消息</div>
</div>
<button onclick="event.stopPropagation(); deleteChat('${chat.id}')"
class="p-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded transition">
<i class="ri-delete-bin-line"></i>
</button>
</div>
<div class="text-xs text-gray-400 mt-1">${formatDate(chat.updated_at)}</div>
</div>
`).join('');
}
// 新建对话
function newChat() {
currentChatId = null;
document.getElementById('messagesContainer').innerHTML = `
<div class="text-center text-gray-400 py-12">
<i class="ri-chat-3-line text-4xl"></i>
<p class="mt-2">开始新对话</p>
</div>
`;
document.getElementById('chatTitle').textContent = '新对话';
renderChatList();
document.getElementById('messageInput').focus();
}
// 加载对话
async function loadChat(chatId) {
currentChatId = chatId;
renderChatList();
const res = await fetch(`/api/chat/${chatId}`);
const chat = await res.json();
document.getElementById('chatTitle').textContent = chat.title || '新对话';
document.getElementById('modelSelect').value = chat.model || 'auto';
// 渲染消息
const container = document.getElementById('messagesContainer');
if (!chat.messages || chat.messages.length === 0) {
container.innerHTML = `
<div class="text-center text-gray-400 py-12">
<i class="ri-chat-3-line text-4xl"></i>
<p class="mt-2">开始对话</p>
</div>
`;
return;
}
container.innerHTML = chat.messages.map(msg => renderMessage(msg)).join('');
scrollToBottom();
}
// 渲染单条消息
function renderMessage(msg) {
if (msg.role === 'user') {
return `
<div class="flex justify-end">
<div class="message-user text-white px-4 py-3 rounded-2xl rounded-br-md max-w-[80%]">
<div class="whitespace-pre-wrap">${escapeHtml(msg.content)}</div>
</div>
</div>
`;
} else {
return `
<div class="flex justify-start">
<div class="message-assistant px-4 py-3 rounded-2xl rounded-bl-md max-w-[80%]">
<div class="whitespace-pre-wrap text-gray-800">${escapeHtml(msg.content)}</div>
${msg.model ? `<div class="text-xs text-gray-400 mt-2">模型: ${msg.model}</div>` : ''}
</div>
</div>
`;
}
}
// 发送消息
async function sendMessage() {
const input = document.getElementById('messageInput');
const content = input.value.trim();
if (!content || isLoading) return;
const model = document.getElementById('modelSelect').value;
// 添加用户消息到界面
const container = document.getElementById('messagesContainer');
const userMsg = { role: 'user', content: content };
container.innerHTML += renderMessage(userMsg);
// 清空输入
input.value = '';
scrollToBottom();
// 显示加载状态
isLoading = true;
document.getElementById('sendBtn').disabled = true;
container.innerHTML += `
<div id="typingIndicator" class="flex justify-start">
<div class="message-assistant px-4 py-3 rounded-2xl rounded-bl-md">
<div class="typing-indicator flex gap-1">
<span class="w-2 h-2 bg-gray-400 rounded-full"></span>
<span class="w-2 h-2 bg-gray-400 rounded-full"></span>
<span class="w-2 h-2 bg-gray-400 rounded-full"></span>
</div>
</div>
</div>
`;
scrollToBottom();
try {
const res = await fetch('/api/chat/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: currentChatId,
model: model,
message: content
})
});
const data = await res.json();
// 移除加载指示器
document.getElementById('typingIndicator')?.remove();
if (data.success) {
// 更新当前对话ID
currentChatId = data.chat_id;
// 添加助手回复
const assistantMsg = { role: 'assistant', content: data.response, model: data.model };
container.innerHTML += renderMessage(assistantMsg);
// 更新标题
document.getElementById('chatTitle').textContent = data.title || '新对话';
// 刷新对话列表
loadChats();
} else {
container.innerHTML += `
<div class="flex justify-start">
<div class="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-2xl rounded-bl-md">
<i class="ri-error-warning-line mr-1"></i>
${data.error || '请求失败'}
</div>
</div>
`;
}
} catch (e) {
document.getElementById('typingIndicator')?.remove();
container.innerHTML += `
<div class="flex justify-start">
<div class="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-2xl rounded-bl-md">
<i class="ri-error-warning-line mr-1"></i>
网络错误: ${e.message}
</div>
</div>
`;
} finally {
isLoading = false;
document.getElementById('sendBtn').disabled = false;
scrollToBottom();
}
}
// 清空当前对话
async function clearCurrentChat() {
if (!currentChatId) {
newChat();
return;
}
if (!confirm('确定清空当前对话吗?')) return;
await fetch(`/api/chat/${currentChatId}/clear`, { method: 'POST' });
loadChat(currentChatId);
}
// 删除对话
async function deleteChat(chatId) {
if (!confirm('确定删除此对话吗?')) return;
await fetch(`/api/chat/${chatId}`, { method: 'DELETE' });
if (currentChatId === chatId) {
newChat();
}
loadChats();
}
// 处理键盘事件
function handleKeyDown(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
}
// 滚动到底部
function scrollToBottom() {
const container = document.getElementById('messagesContainer');
container.scrollTop = container.scrollHeight;
}
// 格式化日期
function formatDate(dateStr) {
if (!dateStr) return '';
const date = new Date(dateStr);
const now = new Date();
const diff = now - date;
if (diff < 60000) return '刚刚';
if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前';
if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前';
if (diff < 604800000) return Math.floor(diff / 86400000) + '天前';
return date.toLocaleDateString();
}
// HTML转义
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// 启动
init();
</script>
</body>
</html>

View File

@@ -33,6 +33,9 @@
<a href="/auto-profiles" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-shuffle-line"></i><span>Auto配置</span>
</a>
<a href="/chat" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-chat-3-line"></i><span>对话</span>
</a>
<a href="/logs" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-file-list-line"></i><span>日志查看</span>
</a>

View File

@@ -34,6 +34,9 @@
<a href="/auto-profiles" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-shuffle-line"></i><span>Auto配置</span>
</a>
<a href="/chat" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-chat-3-line"></i><span>对话</span>
</a>
<a href="/logs" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-file-list-line"></i><span>日志查看</span>
</a>

View File

@@ -33,6 +33,9 @@
<a href="/auto-profiles" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-shuffle-line"></i><span>Auto配置</span>
</a>
<a href="/chat" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-chat-3-line"></i><span>对话</span>
</a>
<a href="/logs" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-file-list-line"></i><span>日志查看</span>
</a>

View File

@@ -35,6 +35,9 @@
<a href="/auto-profiles" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-shuffle-line"></i><span>Auto配置</span>
</a>
<a href="/chat" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-chat-3-line"></i><span>对话</span>
</a>
<a href="/logs" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-file-list-line"></i><span>日志查看</span>
</a>