66 lines
1.8 KiB
JavaScript
66 lines
1.8 KiB
JavaScript
const express = require('express');
|
||
const axios = require('axios');
|
||
const cors = require('cors');
|
||
const path = require('path');
|
||
|
||
const app = express();
|
||
const PORT = 3000;
|
||
|
||
// 中间件
|
||
app.use(cors());
|
||
app.use(express.json());
|
||
app.use(express.static(path.join(__dirname, 'public')));
|
||
|
||
// API路由
|
||
app.post('/api/chat', async (req, res) => {
|
||
try {
|
||
const { message, history } = req.body;
|
||
|
||
// 构建消息数组,包含系统提示、历史对话和当前消息
|
||
const messages = [
|
||
{ role: "system", content: "You are a helpful assistant." },
|
||
...(history || []), // 添加历史对话
|
||
{ role: "user", content: message } // 添加当前消息
|
||
];
|
||
|
||
// 限制对话历史长度,防止超出token限制
|
||
const maxHistoryLength = 10; // 可根据实际情况调整
|
||
if (messages.length > maxHistoryLength) {
|
||
messages.splice(1, messages.length - maxHistoryLength);
|
||
}
|
||
|
||
const response = await axios.post('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
|
||
model: "farui-plus",
|
||
input: {
|
||
messages: messages
|
||
}
|
||
}, {
|
||
headers: {
|
||
'Authorization': `sk-24a6af9eea55494b8f465a01cb92d461`,
|
||
'Content-Type': 'application/json'
|
||
}
|
||
});
|
||
|
||
res.json({
|
||
status: 'success',
|
||
response: response.data
|
||
});
|
||
} catch (error) {
|
||
console.error(error);
|
||
res.status(500).json({
|
||
status: 'error',
|
||
message: 'Internal server error'
|
||
});
|
||
}
|
||
});
|
||
|
||
// 前端路由
|
||
app.get('*', (req, res) => {
|
||
res.sendFile(path.join(__dirname, 'public', 'index.html'));
|
||
});
|
||
|
||
app.listen(PORT, () => {
|
||
console.log(`Server is running on http://localhost:${PORT}`);
|
||
});
|
||
|