fix: Add localhost host binding to Vite config and index fix script
- Add host: 'localhost' to vite.config.js to ensure consistent IP - Add scripts/fix-indexes.js for database index verification - Add routes/llmTest.js for LLM testing endpoint 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
219
routes/llmTest.js
Normal file
219
routes/llmTest.js
Normal file
@@ -0,0 +1,219 @@
|
||||
import express from 'express';
|
||||
import { asyncHandler } from '../middleware/errorHandler.js';
|
||||
import { requireAuth, requireAdmin } from '../middleware/auth.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* GET /api/llm-test/models
|
||||
* 列出可用的 LLM 模型(從 API 動態獲取)
|
||||
*/
|
||||
router.get('/models', requireAuth, asyncHandler(async (req, res) => {
|
||||
const { api_url } = req.query;
|
||||
const targetUrl = api_url || 'https://ollama_pjapi.theaken.com';
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
|
||||
const response = await axios.get(`${targetUrl}/v1/models`, {
|
||||
timeout: 10000
|
||||
});
|
||||
|
||||
if (response.data && response.data.data) {
|
||||
const models = response.data.data.map(model => ({
|
||||
id: model.id,
|
||||
name: model.info?.name || model.id,
|
||||
description: model.info?.description || '',
|
||||
best_for: model.info?.best_for || '',
|
||||
owned_by: model.owned_by || 'unknown'
|
||||
}));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: models
|
||||
});
|
||||
} else {
|
||||
throw new Error('Invalid response format');
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: '無法取得模型列表',
|
||||
message: error.message
|
||||
});
|
||||
}
|
||||
}));
|
||||
|
||||
/**
|
||||
* POST /api/llm-test/quick
|
||||
* 快速測試 LLM 連線(僅管理員)
|
||||
*/
|
||||
router.post('/quick', requireAdmin, asyncHandler(async (req, res) => {
|
||||
const { api_url, api_key, model_name } = req.body;
|
||||
|
||||
if (!api_url || !model_name) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: '請提供 API 端點和模型名稱'
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
const startTime = Date.now();
|
||||
|
||||
const response = await axios.post(
|
||||
`${api_url}/v1/chat/completions`,
|
||||
{
|
||||
model: model_name,
|
||||
messages: [
|
||||
{ role: 'user', content: 'Hello, please respond with just "OK"' }
|
||||
],
|
||||
max_tokens: 10
|
||||
},
|
||||
{
|
||||
timeout: 15000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(api_key && { 'Authorization': `Bearer ${api_key}` })
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const responseTime = Date.now() - startTime;
|
||||
|
||||
if (response.data && response.data.choices) {
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'LLM API 連線測試成功',
|
||||
responseTime: responseTime,
|
||||
response: response.data.choices[0]?.message?.content || ''
|
||||
});
|
||||
} else {
|
||||
throw new Error('Invalid API response format');
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'LLM API 連線測試失敗',
|
||||
message: error.message
|
||||
});
|
||||
}
|
||||
}));
|
||||
|
||||
/**
|
||||
* POST /api/llm-test/chat
|
||||
* 直接與 LLM 對話(測試用,僅管理員)
|
||||
*/
|
||||
router.post('/chat', requireAdmin, asyncHandler(async (req, res) => {
|
||||
const { api_url, api_key, model_name, messages, temperature, max_tokens, stream } = req.body;
|
||||
|
||||
if (!api_url || !model_name || !messages) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: '請提供必要參數'
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
const startTime = Date.now();
|
||||
|
||||
// 非串流模式
|
||||
if (!stream) {
|
||||
const response = await axios.post(
|
||||
`${api_url}/v1/chat/completions`,
|
||||
{
|
||||
model: model_name,
|
||||
messages: messages,
|
||||
temperature: temperature || 0.7,
|
||||
max_tokens: max_tokens || 2000,
|
||||
stream: false
|
||||
},
|
||||
{
|
||||
timeout: 120000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(api_key && { 'Authorization': `Bearer ${api_key}` })
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const responseTime = Date.now() - startTime;
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
content: response.data.choices[0]?.message?.content || '',
|
||||
usage: response.data.usage,
|
||||
model: response.data.model,
|
||||
responseTime: responseTime
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// 串流模式 - 使用 Server-Sent Events
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
|
||||
const response = await axios.post(
|
||||
`${api_url}/v1/chat/completions`,
|
||||
{
|
||||
model: model_name,
|
||||
messages: messages,
|
||||
temperature: temperature || 0.7,
|
||||
max_tokens: max_tokens || 2000,
|
||||
stream: true
|
||||
},
|
||||
{
|
||||
timeout: 120000,
|
||||
responseType: 'stream',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(api_key && { 'Authorization': `Bearer ${api_key}` })
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
response.data.on('data', (chunk) => {
|
||||
const lines = chunk.toString().split('\n');
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
const dataStr = line.slice(6).trim();
|
||||
if (dataStr && dataStr !== '[DONE]') {
|
||||
try {
|
||||
const data = JSON.parse(dataStr);
|
||||
const content = data.choices?.[0]?.delta?.content;
|
||||
if (content) {
|
||||
res.write(`data: ${JSON.stringify({ content })}\n\n`);
|
||||
}
|
||||
} catch (e) {
|
||||
// Skip invalid JSON
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
response.data.on('end', () => {
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
});
|
||||
|
||||
response.data.on('error', (error) => {
|
||||
res.write(`data: ${JSON.stringify({ error: error.message })}\n\n`);
|
||||
res.end();
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'LLM 對話失敗',
|
||||
message: error.message
|
||||
});
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
export default router;
|
||||
204
scripts/fix-indexes.js
Normal file
204
scripts/fix-indexes.js
Normal file
@@ -0,0 +1,204 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Fix Database Indexes
|
||||
* Ensures all indexes exist on renamed 5Why_ tables
|
||||
*
|
||||
* Run: node scripts/fix-indexes.js
|
||||
*/
|
||||
|
||||
import mysql from 'mysql2/promise';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT) || 33306,
|
||||
user: process.env.DB_USER || 'A102',
|
||||
password: process.env.DB_PASSWORD || 'Bb123456',
|
||||
database: process.env.DB_NAME || 'db_A102'
|
||||
};
|
||||
|
||||
// Index definitions for each table
|
||||
const indexDefinitions = {
|
||||
'5Why_users': [
|
||||
{ name: 'idx_employee_id', columns: 'employee_id' },
|
||||
{ name: 'idx_email', columns: 'email' },
|
||||
{ name: 'idx_role', columns: 'role' }
|
||||
],
|
||||
'5Why_analyses': [
|
||||
{ name: 'idx_user_id', columns: 'user_id' },
|
||||
{ name: 'idx_status', columns: 'status' },
|
||||
{ name: 'idx_created_at', columns: 'created_at' }
|
||||
],
|
||||
'5Why_analysis_perspectives': [
|
||||
{ name: 'idx_analysis_id', columns: 'analysis_id' }
|
||||
],
|
||||
'5Why_analysis_whys': [
|
||||
{ name: 'idx_perspective_id', columns: 'perspective_id' },
|
||||
{ name: 'idx_level', columns: 'level' }
|
||||
],
|
||||
'5Why_llm_configs': [
|
||||
{ name: 'idx_provider', columns: 'provider' },
|
||||
{ name: 'idx_is_active', columns: 'is_active' }
|
||||
],
|
||||
'5Why_system_settings': [
|
||||
{ name: 'idx_setting_key', columns: 'setting_key' },
|
||||
{ name: 'idx_is_public', columns: 'is_public' }
|
||||
],
|
||||
'5Why_audit_logs': [
|
||||
{ name: 'idx_user_id', columns: 'user_id' },
|
||||
{ name: 'idx_action', columns: 'action' },
|
||||
{ name: 'idx_created_at', columns: 'created_at' },
|
||||
{ name: 'idx_entity', columns: 'entity_type, entity_id' }
|
||||
],
|
||||
'5Why_sessions': [
|
||||
{ name: 'idx_expires', columns: 'expires' }
|
||||
]
|
||||
};
|
||||
|
||||
async function fixIndexes() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('\n╔════════════════════════════════════════════════════════╗');
|
||||
console.log('║ 5 Why Analyzer - Fix Database Indexes ║');
|
||||
console.log('╚════════════════════════════════════════════════════════╝\n');
|
||||
|
||||
console.log('🔄 Connecting to database...');
|
||||
connection = await mysql.createConnection(dbConfig);
|
||||
console.log('✅ Connected successfully\n');
|
||||
|
||||
// Process each table
|
||||
for (const [tableName, indexes] of Object.entries(indexDefinitions)) {
|
||||
console.log(`📋 Processing table: ${tableName}`);
|
||||
|
||||
// Check if table exists
|
||||
const [tableExists] = await connection.execute(
|
||||
`SELECT COUNT(*) as count FROM information_schema.tables
|
||||
WHERE table_schema = ? AND table_name = ?`,
|
||||
[dbConfig.database, tableName]
|
||||
);
|
||||
|
||||
if (tableExists[0].count === 0) {
|
||||
console.log(` ⚠ Table ${tableName} not found, skipping...`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get existing indexes
|
||||
const [existingIndexes] = await connection.execute(
|
||||
`SELECT DISTINCT INDEX_NAME FROM information_schema.statistics
|
||||
WHERE table_schema = ? AND table_name = ?`,
|
||||
[dbConfig.database, tableName]
|
||||
);
|
||||
const existingIndexNames = existingIndexes.map(idx => idx.INDEX_NAME);
|
||||
|
||||
// Create missing indexes
|
||||
for (const index of indexes) {
|
||||
if (existingIndexNames.includes(index.name)) {
|
||||
console.log(` ✓ Index ${index.name} already exists`);
|
||||
} else {
|
||||
try {
|
||||
await connection.execute(
|
||||
`CREATE INDEX ${index.name} ON \`${tableName}\` (${index.columns})`
|
||||
);
|
||||
console.log(` ✓ Created index: ${index.name} on (${index.columns})`);
|
||||
} catch (err) {
|
||||
if (err.code === 'ER_DUP_KEYNAME') {
|
||||
console.log(` ⚠ Index ${index.name} already exists (duplicate)`);
|
||||
} else {
|
||||
console.error(` ✗ Error creating index ${index.name}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Verify unique constraints on 5Why_users
|
||||
console.log('\n📋 Verifying unique constraints on 5Why_users...');
|
||||
|
||||
// Check employee_id unique constraint
|
||||
const [empUnique] = await connection.execute(
|
||||
`SELECT COUNT(*) as count FROM information_schema.statistics
|
||||
WHERE table_schema = ? AND table_name = '5Why_users'
|
||||
AND column_name = 'employee_id' AND non_unique = 0`,
|
||||
[dbConfig.database]
|
||||
);
|
||||
|
||||
if (empUnique[0].count > 0) {
|
||||
console.log(' ✓ employee_id has unique constraint');
|
||||
} else {
|
||||
console.log(' ⚠ employee_id missing unique constraint, adding...');
|
||||
try {
|
||||
await connection.execute(
|
||||
`ALTER TABLE 5Why_users ADD UNIQUE INDEX idx_employee_id_unique (employee_id)`
|
||||
);
|
||||
console.log(' ✓ Added unique constraint on employee_id');
|
||||
} catch (err) {
|
||||
if (err.code === 'ER_DUP_KEYNAME' || err.message.includes('Duplicate')) {
|
||||
console.log(' ✓ Unique constraint already exists');
|
||||
} else {
|
||||
console.error(` ✗ Error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check email unique constraint
|
||||
const [emailUnique] = await connection.execute(
|
||||
`SELECT COUNT(*) as count FROM information_schema.statistics
|
||||
WHERE table_schema = ? AND table_name = '5Why_users'
|
||||
AND column_name = 'email' AND non_unique = 0`,
|
||||
[dbConfig.database]
|
||||
);
|
||||
|
||||
if (emailUnique[0].count > 0) {
|
||||
console.log(' ✓ email has unique constraint');
|
||||
} else {
|
||||
console.log(' ⚠ email missing unique constraint, adding...');
|
||||
try {
|
||||
await connection.execute(
|
||||
`ALTER TABLE 5Why_users ADD UNIQUE INDEX idx_email_unique (email)`
|
||||
);
|
||||
console.log(' ✓ Added unique constraint on email');
|
||||
} catch (err) {
|
||||
if (err.code === 'ER_DUP_KEYNAME' || err.message.includes('Duplicate')) {
|
||||
console.log(' ✓ Unique constraint already exists');
|
||||
} else {
|
||||
console.error(` ✗ Error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n╔════════════════════════════════════════════════════════╗');
|
||||
console.log('║ Index Fix Complete! ║');
|
||||
console.log('╚════════════════════════════════════════════════════════╝\n');
|
||||
|
||||
// Show current indexes for 5Why_users
|
||||
console.log('📊 Current indexes on 5Why_users:');
|
||||
const [userIndexes] = await connection.execute(
|
||||
`SELECT INDEX_NAME, COLUMN_NAME, NON_UNIQUE
|
||||
FROM information_schema.statistics
|
||||
WHERE table_schema = ? AND table_name = '5Why_users'
|
||||
ORDER BY INDEX_NAME, SEQ_IN_INDEX`,
|
||||
[dbConfig.database]
|
||||
);
|
||||
|
||||
userIndexes.forEach(idx => {
|
||||
const unique = idx.NON_UNIQUE === 0 ? ' (UNIQUE)' : '';
|
||||
console.log(` - ${idx.INDEX_NAME}: ${idx.COLUMN_NAME}${unique}`);
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('\n❌ Fix indexes failed:');
|
||||
console.error(' Error:', error.message);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('\n🔌 Database connection closed\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Execute
|
||||
fixIndexes();
|
||||
@@ -4,6 +4,7 @@ import react from '@vitejs/plugin-react'
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
host: 'localhost',
|
||||
port: 5173,
|
||||
open: true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user