myfari/server.js
2025-03-17 17:48:25 +08:00

66 lines
2.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 senior legal expert and lawyer on domestic legal issues in mainland China. Provide clear, concise, and structured responses based on relevant laws and regulations. Use bullet points, numbered lists, or tables when appropriate. Cite cases from the case library when necessary." },
...(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}`);
});