web端增加微信登陆
This commit is contained in:
225
server2.js
225
server2.js
@@ -144,8 +144,7 @@ const client1 = new OpenAI({
|
|||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
async function test1()
|
async function test1() {
|
||||||
{
|
|
||||||
console.time("test");
|
console.time("test");
|
||||||
await client.chat.completions.create({
|
await client.chat.completions.create({
|
||||||
model: "gpt-4.1", // 注意:这里必须是你在 Azure portal 里创建的“部署名称”
|
model: "gpt-4.1", // 注意:这里必须是你在 Azure portal 里创建的“部署名称”
|
||||||
@@ -155,10 +154,9 @@ async function test1()
|
|||||||
});
|
});
|
||||||
console.timeEnd("test");
|
console.timeEnd("test");
|
||||||
}
|
}
|
||||||
async function directCall()
|
async function directCall() {
|
||||||
{
|
|
||||||
console.time("directCall");
|
console.time("directCall");
|
||||||
await client1.chat.completions.create({ model:"gpt-5-mini", messages:[{ role: "user", content: "ping" }] });
|
await client1.chat.completions.create({ model: "gpt-5-mini", messages: [{ role: "user", content: "ping" }] });
|
||||||
console.timeEnd("directCall");
|
console.timeEnd("directCall");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,7 +169,7 @@ async function getAccessToken() {
|
|||||||
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;
|
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;
|
||||||
const res = await axios.get(url);
|
const res = await axios.get(url);
|
||||||
if (res.data.access_token) {
|
if (res.data.access_token) {
|
||||||
console.log('✅ 获取 access_token 成功',res.data);
|
console.log('✅ 获取 access_token 成功', res.data);
|
||||||
|
|
||||||
return res.data.access_token;
|
return res.data.access_token;
|
||||||
} else {
|
} else {
|
||||||
@@ -302,7 +300,7 @@ async function createMenu() {
|
|||||||
{
|
{
|
||||||
"type": "view",
|
"type": "view",
|
||||||
"name": "运维招工",
|
"name": "运维招工",
|
||||||
"url": "https://zp.satabot.com/#/pages/Wxpublic/Wxpublic?redirect=/pages/index/index"
|
"url": "https://zp.satabot.com/"
|
||||||
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -405,7 +403,7 @@ app.post('/wechat', async (req, res) => {
|
|||||||
|
|
||||||
const userRes = await axios.get('https://api.weixin.qq.com/sns/userinfo', {
|
const userRes = await axios.get('https://api.weixin.qq.com/sns/userinfo', {
|
||||||
params: {
|
params: {
|
||||||
access_token:token,
|
access_token: token,
|
||||||
fromUser,
|
fromUser,
|
||||||
lang: 'zh_CN'
|
lang: 'zh_CN'
|
||||||
}
|
}
|
||||||
@@ -484,8 +482,107 @@ app.post('/wechat', async (req, res) => {
|
|||||||
// 异常情况下回复空串
|
// 异常情况下回复空串
|
||||||
res.send('');
|
res.send('');
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/webCallback', async (req, res) => {
|
||||||
|
try {
|
||||||
|
// 获取 URL 中的 code 和 state 参数
|
||||||
|
const { code, state } = req.query;
|
||||||
|
if (!code) {
|
||||||
|
return res.status(400).send('授权失败:没有 code');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录 extraParams
|
||||||
|
console.log('Extra Params:', state);
|
||||||
|
|
||||||
|
// 1️⃣ 用 code 换 access_token
|
||||||
|
const tokenRes = await axios.get('https://api.weixin.qq.com/sns/oauth2/access_token', {
|
||||||
|
params: {
|
||||||
|
appid: 'wx0eeb7556d60121db',
|
||||||
|
secret: 'a01456fbccf15adf57ea0d3c702d4e31',
|
||||||
|
code,
|
||||||
|
grant_type: 'authorization_code',
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const { access_token, openid, unionid } = tokenRes.data;
|
||||||
|
console.log('Access Token Response:', tokenRes.data);
|
||||||
|
|
||||||
|
if (!access_token || !openid) {
|
||||||
|
return res.status(400).send('access_token 获取失败');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2️⃣ 用 access_token 和 openid 拉取用户信息
|
||||||
|
const userInfoRes = await axios.get('https://api.weixin.qq.com/sns/userinfo', {
|
||||||
|
params: {
|
||||||
|
access_token,
|
||||||
|
openid,
|
||||||
|
lang: 'zh_CN',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const userInfo = userInfoRes.data;
|
||||||
|
console.log('User Info Response:', userInfoRes.data);
|
||||||
|
const datalogin = {
|
||||||
|
sourceType: 1,
|
||||||
|
openId: openid,
|
||||||
|
phonenumber: '',
|
||||||
|
smsCode: '',
|
||||||
|
loginPlatForm: 2
|
||||||
|
|
||||||
|
}
|
||||||
|
console.log(datalogin, "data")
|
||||||
|
// 3️⃣ 发送用户信息到登录接口
|
||||||
|
try {
|
||||||
|
const loginRes = await axios.post('https://serviceri.satabot.com/login', datalogin, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
}
|
||||||
|
});
|
||||||
|
console.log('Login Response:', loginRes.data);
|
||||||
|
if (loginRes.data.code === 200) {
|
||||||
|
// 登录成功,设置 token 并跳转
|
||||||
|
const { token, userId, username } = loginRes.data;
|
||||||
|
res.cookie('Admin-Token', token, {
|
||||||
|
maxAge: 900000, httpOnly: true, sameSite: 'None', // 或 'Strict' / 'Lax',具体根据需要选择
|
||||||
|
});
|
||||||
|
res.cookie('userId', userId, {
|
||||||
|
maxAge: 900000, httpOnly: true, sameSite: 'None', // 或 'Strict' / 'Lax',具体根据需要选择
|
||||||
|
});
|
||||||
|
|
||||||
|
const encodedUserId = btoa(unescape(encodeURIComponent(userId)));
|
||||||
|
// 跳转到指定的页面
|
||||||
|
const t = Date.now();
|
||||||
|
// document.body.classList.add('fadeout');
|
||||||
|
if (state == "ai") {
|
||||||
|
res.redirect(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${token}&t=${t}`);
|
||||||
|
// window.location.replace(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${token}&t=${t}`);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
const encodedToken = btoa(unescape(encodeURIComponent(token)));
|
||||||
|
const encodedUsername = btoa(unescape(encodeURIComponent(username)));
|
||||||
|
res.redirect(`http://ri.satabot.com/#/index?djjdbsjdwjhedbh=${encodedToken}&username=${encodedUsername}`);
|
||||||
|
}
|
||||||
|
// res.redirect(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${token}&t=${t}`);
|
||||||
|
|
||||||
|
// res.redirect(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${token}&t=${t}`);
|
||||||
|
// window.location.replace(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${token}&t=${t}`);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
return res.status(400).send('登录失败');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Login Error:', err);
|
||||||
|
return res.status(500).send('登录接口请求失败');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error:', err.response?.data || err);
|
||||||
|
res.status(500).send('服务器错误');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// app.post('/wechat', async (req, res) => {
|
// app.post('/wechat', async (req, res) => {
|
||||||
// try {
|
// try {
|
||||||
@@ -557,7 +654,7 @@ app.post('/wechat', async (req, res) => {
|
|||||||
app.get('/wechat/oauth/callback', async (req, res) => {
|
app.get('/wechat/oauth/callback', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { code, state } = req.query;
|
const { code, state } = req.query;
|
||||||
console.log(code,"code")
|
console.log(code, "code")
|
||||||
|
|
||||||
|
|
||||||
// 用 code 换取 access_token 和 openid
|
// 用 code 换取 access_token 和 openid
|
||||||
@@ -627,11 +724,11 @@ app.post("/user", async (req, res) => {
|
|||||||
const { userId } = req.body; // 从请求体里拿到 user_id
|
const { userId } = req.body; // 从请求体里拿到 user_id
|
||||||
|
|
||||||
|
|
||||||
if (!userId&&userId!="NaN") {
|
if (!userId && userId != "NaN") {
|
||||||
res.json({
|
res.json({
|
||||||
code: 300,
|
code: 300,
|
||||||
error: "http://ri.satabot.com/#/login?goRemote=1",
|
error: "http://ri.satabot.com/#/login?goRemote=1",
|
||||||
msg:"未找到该用户"
|
msg: "未找到该用户"
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -646,12 +743,12 @@ app.post("/user", async (req, res) => {
|
|||||||
res.json({
|
res.json({
|
||||||
code: 300,
|
code: 300,
|
||||||
error: "http://ri.satabot.com/#/login?goRemote=1",
|
error: "http://ri.satabot.com/#/login?goRemote=1",
|
||||||
msg:"未找到该用户"
|
msg: "未找到该用户"
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ code:0,userId, userName: rows[0].user_name });
|
res.json({ code: 0, userId, userName: rows[0].user_name });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
res.status(500).send("服务器错误");
|
res.status(500).send("服务器错误");
|
||||||
@@ -673,17 +770,17 @@ app.post("/getuserByopenid", async (req, res) => {
|
|||||||
);
|
);
|
||||||
if (rows.length > 0) {
|
if (rows.length > 0) {
|
||||||
// 用户存在,直接返回
|
// 用户存在,直接返回
|
||||||
res.json({ code: 0, msg: "找到该用户",userId:rows[0].user_id });
|
res.json({ code: 0, msg: "找到该用户", userId: rows[0].user_id });
|
||||||
return
|
return
|
||||||
} else {
|
} else {
|
||||||
// 用户不存在,插入新用户
|
// 用户不存在,插入新用户
|
||||||
const [result] = await pool.query(
|
const [result] = await pool.query(
|
||||||
"INSERT INTO sys_user (open_id,user_name,nick_name) VALUES (?,?,?)",
|
"INSERT INTO sys_user (open_id,user_name,nick_name) VALUES (?,?,?)",
|
||||||
[userId,userId,userId]
|
[userId, userId, userId]
|
||||||
);
|
);
|
||||||
console.log(result,"udgwehvdh")
|
console.log(result, "udgwehvdh")
|
||||||
res.json({code:0,msg:"新增该用户",userId:result.insertId});
|
res.json({ code: 0, msg: "新增该用户", userId: result.insertId });
|
||||||
return ;
|
return;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
@@ -710,8 +807,7 @@ app.get("/sessions", async (req, res) => {
|
|||||||
console.log("收到的 userId:", req.query.userId);
|
console.log("收到的 userId:", req.query.userId);
|
||||||
try {
|
try {
|
||||||
const userId = req.query.userId;
|
const userId = req.query.userId;
|
||||||
if (!userId || userId == "NaN" || isNaN(Number(userId)))
|
if (!userId || userId == "NaN" || isNaN(Number(userId))) {
|
||||||
{
|
|
||||||
console.log("userId:", req.query.userId);
|
console.log("userId:", req.query.userId);
|
||||||
res.json({
|
res.json({
|
||||||
code: 300,
|
code: 300,
|
||||||
@@ -758,16 +854,15 @@ app.get("/sessions", async (req, res) => {
|
|||||||
ORDER BY MIN(created_at) ASC
|
ORDER BY MIN(created_at) ASC
|
||||||
`, [userId]);
|
`, [userId]);
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
code: 0,
|
code: 0,
|
||||||
sessions: rows.map(r => ({
|
sessions: rows.map(r => ({
|
||||||
sessId: r.session_id,
|
sessId: r.session_id,
|
||||||
title: r.title
|
title: r.title
|
||||||
}))
|
}))
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
catch (err)
|
catch (err) {
|
||||||
{
|
|
||||||
console.error("查询会话列表失败:", err);
|
console.error("查询会话列表失败:", err);
|
||||||
res.status(500).json({ code: 1, error: err.message });
|
res.status(500).json({ code: 1, error: err.message });
|
||||||
}
|
}
|
||||||
@@ -775,10 +870,8 @@ res.json({
|
|||||||
|
|
||||||
// 查询会话历史
|
// 查询会话历史
|
||||||
app.get("/history", async (req, res) => {
|
app.get("/history", async (req, res) => {
|
||||||
try
|
try {
|
||||||
{
|
if (!req.query?.sessionId || req.query?.sessionId == "NaN") {
|
||||||
if(!req.query?.sessionId || req.query?.sessionId == "NaN")
|
|
||||||
{
|
|
||||||
return res.status(400).json({ code: 1, error: "sessionId 必填" });
|
return res.status(400).json({ code: 1, error: "sessionId 必填" });
|
||||||
}
|
}
|
||||||
const { sessionId } = req.query;
|
const { sessionId } = req.query;
|
||||||
@@ -802,13 +895,11 @@ app.get("/history", async (req, res) => {
|
|||||||
|
|
||||||
// 删除指定会话及其消息
|
// 删除指定会话及其消息
|
||||||
app.delete("/session", async (req, res) => {
|
app.delete("/session", async (req, res) => {
|
||||||
try
|
try {
|
||||||
{
|
|
||||||
console.log("会话删除:", req.query);
|
console.log("会话删除:", req.query);
|
||||||
|
|
||||||
// if (!sessionId || !userId)
|
// if (!sessionId || !userId)
|
||||||
if (req.query?.userId == "NaN" || !req.query?.userId || !req.query?.sessionId || req.query?.sessionId == "NaN")
|
if (req.query?.userId == "NaN" || !req.query?.userId || !req.query?.sessionId || req.query?.sessionId == "NaN") {
|
||||||
{
|
|
||||||
return res.status(400).json({ code: 1, error: "sessionId 和 userId 必填" });
|
return res.status(400).json({ code: 1, error: "sessionId 和 userId 必填" });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -835,8 +926,7 @@ app.delete("/session", async (req, res) => {
|
|||||||
message: `会话 ${sessionId} 已删除`,
|
message: `会话 ${sessionId} 已删除`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
catch (err)
|
catch (err) {
|
||||||
{
|
|
||||||
console.error("删除会话失败:", err);
|
console.error("删除会话失败:", err);
|
||||||
res.status(500).json({ code: 1, error: err.message });
|
res.status(500).json({ code: 1, error: err.message });
|
||||||
}
|
}
|
||||||
@@ -844,13 +934,11 @@ app.delete("/session", async (req, res) => {
|
|||||||
|
|
||||||
// 新建会话(实际上就是往消息表里插入一条记录)
|
// 新建会话(实际上就是往消息表里插入一条记录)
|
||||||
app.post("/session", async (req, res) => {
|
app.post("/session", async (req, res) => {
|
||||||
try
|
try {
|
||||||
{
|
console.log("新建会话: ", req.body)
|
||||||
console.log("新建会话: ",req.body)
|
|
||||||
|
|
||||||
if (req.body?.userId == "NaN" || !req.body?.userId || !req.body?.sessionId || req.body?.sessionId == "NaN")
|
if (req.body?.userId == "NaN" || !req.body?.userId || !req.body?.sessionId || req.body?.sessionId == "NaN") {
|
||||||
{
|
console.log("=== userId: ", req.body?.userId)
|
||||||
console.log("=== userId: ",req.body?.userId)
|
|
||||||
return res.status(400).json({ code: 1, error: "userId 和 sessionId 必填" });
|
return res.status(400).json({ code: 1, error: "userId 和 sessionId 必填" });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -867,8 +955,7 @@ app.post("/session", async (req, res) => {
|
|||||||
message: `会话 ${sessionId} 已创建`,
|
message: `会话 ${sessionId} 已创建`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
catch (err)
|
catch (err) {
|
||||||
{
|
|
||||||
console.error("创建会话失败:", err);
|
console.error("创建会话失败:", err);
|
||||||
res.status(500).json({ code: 1, error: err.message });
|
res.status(500).json({ code: 1, error: err.message });
|
||||||
}
|
}
|
||||||
@@ -887,7 +974,7 @@ function getMutex(userId) {
|
|||||||
return mutexes.get(userId);
|
return mutexes.get(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setQuota(userId,num) {
|
async function setQuota(userId, num) {
|
||||||
const m = getMutex(userId);
|
const m = getMutex(userId);
|
||||||
return await m.runExclusive(async () => {
|
return await m.runExclusive(async () => {
|
||||||
console.log("更新用户对话次数:", userId, num);
|
console.log("更新用户对话次数:", userId, num);
|
||||||
@@ -928,8 +1015,8 @@ app.post("/refreshAiChatNum", async (req, res) => {
|
|||||||
);
|
);
|
||||||
if (userRemainChatNum.length > 0) {
|
if (userRemainChatNum.length > 0) {
|
||||||
const quota = userRemainChatNum[0].ai_chat_num;
|
const quota = userRemainChatNum[0].ai_chat_num;
|
||||||
console.log(userId,"刷新对话次数",quota);
|
console.log(userId, "刷新对话次数", quota);
|
||||||
await setQuota(userId,quota);
|
await setQuota(userId, quota);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("更新失败:", error);
|
console.error("更新失败:", error);
|
||||||
@@ -938,8 +1025,7 @@ app.post("/refreshAiChatNum", async (req, res) => {
|
|||||||
|
|
||||||
app.post("/analyze", upload.single("file"), async (req, res) => {
|
app.post("/analyze", upload.single("file"), async (req, res) => {
|
||||||
const { userId } = req.body;
|
const { userId } = req.body;
|
||||||
try
|
try {
|
||||||
{
|
|
||||||
const exists = await hasQuota(userId);
|
const exists = await hasQuota(userId);
|
||||||
if (!exists) {
|
if (!exists) {
|
||||||
const [userRemainChatNum] = await pool.query(
|
const [userRemainChatNum] = await pool.query(
|
||||||
@@ -951,7 +1037,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
if (quota <= 0 && quota !== -1) {
|
if (quota <= 0 && quota !== -1) {
|
||||||
return res.status(400).json({ error: "对话次数已用完,请完成账号注册" });
|
return res.status(400).json({ error: "对话次数已用完,请完成账号注册" });
|
||||||
}
|
}
|
||||||
await setQuota(userId,quota);
|
await setQuota(userId, quota);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const quota = await getQuota(userId);
|
const quota = await getQuota(userId);
|
||||||
@@ -975,15 +1061,13 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
|
|
||||||
console.time("analyze");
|
console.time("analyze");
|
||||||
const logBody = { ...req.body };
|
const logBody = { ...req.body };
|
||||||
if(req.body?.imageBase64)
|
if (req.body?.imageBase64) {
|
||||||
{
|
|
||||||
delete logBody.imageBase64;
|
delete logBody.imageBase64;
|
||||||
}
|
}
|
||||||
console.log("analyze: ", logBody);
|
console.log("analyze: ", logBody);
|
||||||
|
|
||||||
// console.log("analyze: ",req.body)
|
// console.log("analyze: ",req.body)
|
||||||
if (!req.body?.userId || !req.body?.sessionId)
|
if (!req.body?.userId || !req.body?.sessionId) {
|
||||||
{
|
|
||||||
console.log("缺少必要参数");
|
console.log("缺少必要参数");
|
||||||
return res.status(400).json({ error: "缺少必要参数" });
|
return res.status(400).json({ error: "缺少必要参数" });
|
||||||
}
|
}
|
||||||
@@ -1021,14 +1105,12 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 添加文本内容
|
// 添加文本内容
|
||||||
if (row.content)
|
if (row.content) {
|
||||||
{
|
|
||||||
message.content.push({ type: "text", text: row.content });
|
message.content.push({ type: "text", text: row.content });
|
||||||
}
|
}
|
||||||
|
|
||||||
// 添加图片内容
|
// 添加图片内容
|
||||||
if (row.image_base64)
|
if (row.image_base64) {
|
||||||
{
|
|
||||||
message.content.push({
|
message.content.push({
|
||||||
type: "image_url",
|
type: "image_url",
|
||||||
image_url: {
|
image_url: {
|
||||||
@@ -1097,8 +1179,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
});
|
});
|
||||||
res.socket.setNoDelay(true);
|
res.socket.setNoDelay(true);
|
||||||
|
|
||||||
for await (const chunk of completion)
|
for await (const chunk of completion) {
|
||||||
{
|
|
||||||
if (stopFlags.get(requestId)) {
|
if (stopFlags.get(requestId)) {
|
||||||
console.log("⛔ 图像分析被前端中断");
|
console.log("⛔ 图像分析被前端中断");
|
||||||
res.end();
|
res.end();
|
||||||
@@ -1108,8 +1189,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
const delta = chunk.choices[0]?.delta?.content || "";
|
const delta = chunk.choices[0]?.delta?.content || "";
|
||||||
sceneText += delta;
|
sceneText += delta;
|
||||||
|
|
||||||
if (delta)
|
if (delta) {
|
||||||
{
|
|
||||||
res.write(
|
res.write(
|
||||||
`data: ${JSON.stringify({ type: "scene", content: delta })}\n\n`
|
`data: ${JSON.stringify({ type: "scene", content: delta })}\n\n`
|
||||||
);
|
);
|
||||||
@@ -1164,8 +1244,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
|
|
||||||
console.log("====== 开始深度思考... ======")
|
console.log("====== 开始深度思考... ======")
|
||||||
let llmText = "";
|
let llmText = "";
|
||||||
for await (const chunk of llmStream)
|
for await (const chunk of llmStream) {
|
||||||
{
|
|
||||||
if (stopFlags.get(requestId)) {
|
if (stopFlags.get(requestId)) {
|
||||||
console.log("⛔ 深度分析被前端中断");
|
console.log("⛔ 深度分析被前端中断");
|
||||||
res.end();
|
res.end();
|
||||||
@@ -1177,7 +1256,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
|
|
||||||
if (delta)
|
if (delta)
|
||||||
res.write(
|
res.write(
|
||||||
`data: ${JSON.stringify({ type: "llm", content: delta})}\n\n`
|
`data: ${JSON.stringify({ type: "llm", content: delta })}\n\n`
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
@@ -1204,8 +1283,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
} else {
|
} else {
|
||||||
console.log("uidh1111")
|
console.log("uidh1111")
|
||||||
|
|
||||||
try
|
try {
|
||||||
{
|
|
||||||
const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
|
const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
|
||||||
用户问题: ${userPrompt}
|
用户问题: ${userPrompt}
|
||||||
AI回答: ${llmText}`;
|
AI回答: ${llmText}`;
|
||||||
@@ -1228,11 +1306,10 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
// 保存到数据库(建议你给 ai_chat_messages 表新增一列 title,或者单独建一张会话表)
|
// 保存到数据库(建议你给 ai_chat_messages 表新增一列 title,或者单独建一张会话表)
|
||||||
await pool.query(
|
await pool.query(
|
||||||
"INSERT INTO ai_chat_messages (session_id, user_id, role, content,title) VALUES (?, ?, 'assistant', ?,?)",
|
"INSERT INTO ai_chat_messages (session_id, user_id, role, content,title) VALUES (?, ?, 'assistant', ?,?)",
|
||||||
[sessId, userId || null, llmText,title]
|
[sessId, userId || null, llmText, title]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
catch (err)
|
catch (err) {
|
||||||
{
|
|
||||||
console.error("生成标题失败:", err.message);
|
console.error("生成标题失败:", err.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1244,8 +1321,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
res.end();
|
res.end();
|
||||||
|
|
||||||
// 删除上传文件
|
// 删除上传文件
|
||||||
if (req.file && req.file.path)
|
if (req.file && req.file.path) {
|
||||||
{
|
|
||||||
fs.unlinkSync(req.file.path);
|
fs.unlinkSync(req.file.path);
|
||||||
}
|
}
|
||||||
console.log("====== 分析完成 ======");
|
console.log("====== 分析完成 ======");
|
||||||
@@ -1259,8 +1335,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
// console.log(`用户剩余AI 对话次数: ${userChatNum}`);
|
// console.log(`用户剩余AI 对话次数: ${userChatNum}`);
|
||||||
// }
|
// }
|
||||||
}
|
}
|
||||||
catch (err)
|
catch (err) {
|
||||||
{
|
|
||||||
console.error("❌ 调用失败:", err.response?.data || err.message);
|
console.error("❌ 调用失败:", err.response?.data || err.message);
|
||||||
res.status(500).json({ code: 1, error: err.response?.data || err.message });
|
res.status(500).json({ code: 1, error: err.response?.data || err.message });
|
||||||
}
|
}
|
||||||
@@ -1284,10 +1359,10 @@ app.post("/stop", express.json(), (req, res) => {
|
|||||||
const { requestId } = req.body;
|
const { requestId } = req.body;
|
||||||
console.log("🔴 收到停止信号:", requestId);
|
console.log("🔴 收到停止信号:", requestId);
|
||||||
stopFlags.set(requestId, true);
|
stopFlags.set(requestId, true);
|
||||||
console.log(stopFlags,"消息id");
|
console.log(stopFlags, "消息id");
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
});
|
});
|
||||||
app.post('/submit',async (req, res) => {
|
app.post('/submit', async (req, res) => {
|
||||||
const { company, scenes, needs, userId } = req.body;
|
const { company, scenes, needs, userId } = req.body;
|
||||||
|
|
||||||
console.log("收到数据:", company, scenes, needs, userId);
|
console.log("收到数据:", company, scenes, needs, userId);
|
||||||
@@ -1302,7 +1377,7 @@ app.post('/submit',async (req, res) => {
|
|||||||
|
|
||||||
await pool.query(sql, [company, scenes, needs, userId || null]);
|
await pool.query(sql, [company, scenes, needs, userId || null]);
|
||||||
|
|
||||||
res.json({ code:200,message: "提交成功!" });
|
res.json({ code: 200, message: "提交成功!" });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("数据库插入失败:", err);
|
console.error("数据库插入失败:", err);
|
||||||
res.status(500).json({ message: "数据库写入失败" });
|
res.status(500).json({ message: "数据库写入失败" });
|
||||||
|
|||||||
Reference in New Issue
Block a user