优化生成标题

This commit is contained in:
2025-11-24 21:40:06 +08:00
parent 7296b7881e
commit a3cb65306a
2 changed files with 76 additions and 42 deletions

View File

@@ -1558,6 +1558,14 @@
}); });
}); });
} }
function isMobile() {
// 获取UA字符串
const userAgent = navigator.userAgent;
// 匹配主流手机相关关键词,忽略大小写
const mobileRegex = /iPhone|Android|BlackBerry|IEMobile|Opera Mini|RedMi|Huawei|Vivo/i;
// 返回匹配结果
return mobileRegex.test(userAgent);
}
function bindToLogin() { function bindToLogin() {
document.querySelector('.popbox .loading-box').classList.remove('none'); document.querySelector('.popbox .loading-box').classList.remove('none');
const data = { const data = {
@@ -1937,7 +1945,7 @@
panel.classList.remove('show'); panel.classList.remove('show');
} }
const chatbox = document.querySelector(".chat-input"); const chatbox = document.querySelector(".chat-input");
if (!sidebar.contains(e.target) && !chatbox.contains(e.target)) { if (!sidebar.contains(e.target) && !chatbox.contains(e.target)&& isMobile()) {
if (!sidebar.classList.contains("collapsed")) { if (!sidebar.classList.contains("collapsed")) {
sidebar.classList.add("collapsed"); sidebar.classList.add("collapsed");
toggleBtn.style.left = "10px"; // 收起后 toggleBtn.style.left = "10px"; // 收起后
@@ -2191,7 +2199,7 @@ function smartRender(msgDiv, text) {
}).catch(err => { }).catch(err => {
console.log("✅ 流被中断:", err.name); console.log("✅ 流被中断:", err.name);
clearInterval(interval); clearInterval(interval);
// controller.abort(); controller.abort();
controller = null; controller = null;
@@ -2282,7 +2290,7 @@ function smartRender(msgDiv, text) {
// } // }
if (obj.content && obj.type !== "title") { if (obj.content && obj.type !== "title") {
for (const char of obj.content) { for (const char of obj.content) {
await new Promise(r => setTimeout(r, 2)); // 控制字速 await new Promise(r => setTimeout(r, 5)); // 控制字速
if (isStopped) return; if (isStopped) return;
aiMsg.content += char; aiMsg.content += char;
smartRender(msgDiv, aiMsg.content); smartRender(msgDiv, aiMsg.content);
@@ -2459,7 +2467,7 @@ function smartRender(msgDiv, text) {
const deleteSession = (sessionId, userId) => { const deleteSession = (sessionId, userId) => {
if (activeChatId == sessionId) { if (activeChatId == sessionId) {
if (controller) { if (controller) {
// controller.abort(); controller.abort();
controller = null; controller = null;
if (sendBtnImg.classList.contains('none')) { if (sendBtnImg.classList.contains('none')) {
sendBtnImg.classList.remove('none'); sendBtnImg.classList.remove('none');
@@ -2736,7 +2744,7 @@ function smartRender(msgDiv, text) {
} }
if (controller) { if (controller) {
// controller.abort(); controller.abort();
controller = null; controller = null;
if (sendBtnImg.classList.contains('none')) { if (sendBtnImg.classList.contains('none')) {
sendBtnImg.classList.remove('none'); sendBtnImg.classList.remove('none');

View File

@@ -862,8 +862,10 @@ const stopFlags = new Map();
app.post("/analyze", upload.single("file"), async (req, res) => { app.post("/analyze", upload.single("file"), async (req, res) => {
try try
{ {
const { requestId } = req.body; const { requestId } = req.body;
res.setHeader("Content-Type", "text/plain; charset=utf-8"); res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.setHeader("Transfer-Encoding", "chunked"); res.setHeader("Transfer-Encoding", "chunked");
res.setHeader("Cache-Control", "no-cache"); res.setHeader("Cache-Control", "no-cache");
@@ -890,6 +892,22 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
return res.status(400).json({ error: "缺少必要参数" }); return res.status(400).json({ error: "缺少必要参数" });
} }
const { userPrompt, imageBase64, userId, sessionId } = req.body; const { userPrompt, imageBase64, userId, sessionId } = req.body;
const [rows] = await pool.query(
`
SELECT EXISTS(
SELECT 1
FROM ai_chat_messages
WHERE session_id = ?
AND user_id = ?
AND title IS NOT NULL
AND title != ''
) AS hasTitle
`,
[sessionId, userId]
);
const existingTitle = rows[0].hasTitle === 1; // true / false
console.log(existingTitle, rows?.[0], 9999, rows)
// 如果前端没有传 sessionId,生成一个 // 如果前端没有传 sessionId,生成一个
const sessId = sessionId || Date.now().toString(); const sessId = sessionId || Date.now().toString();
@@ -1082,42 +1100,50 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
// 保存 LLM 输出到数据库 // 保存 LLM 输出到数据库
/* 加标题需要异步,且在会话开始时就进行 */ /* 加标题需要异步,且在会话开始时就进行 */
// try if (existingTitle) {
// { console.log("uidh")
// const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
// 用户问题: ${userPrompt}
// AI回答: ${llmText}`;
// const titleResp = await client1.chat.completions.create({
// model: "gpt-5-mini",
// messages: [
// { role: "system", content: "你是标题生成助手,只返回标题,不要解释。" },
// { role: "user", content: titlePrompt }
// ]
// });
// const title = titleResp.choices[0]?.message?.content?.trim() || "未命名会话";
// res.write(
// `data: ${JSON.stringify({ type: "title", content: title })}\n\n`
// );
// console.log("生成的标题:", title);
// // 保存到数据库(建议你给 ai_chat_messages 表新增一列 title,或者单独建一张会话表)
// // await pool.query(
// // "INSERT INTO ai_chat_messages (session_id, user_id, role, content,title) VALUES (?, ?, 'assistant', ?,?)",
// // [sessId, userId || null, llmText,title]
// // );
// }
// catch (err)
// {
// console.error("生成标题失败:", err.message);
// }
await pool.query( await pool.query(
"INSERT INTO ai_chat_messages (session_id, user_id, role, content) VALUES (?, ?, 'assistant', ?)", "INSERT INTO ai_chat_messages (session_id, user_id, role, content) VALUES (?, ?, 'assistant', ?)",
[sessId, userId || null, llmText] [sessId, userId || null, llmText]
); );
} else {
console.log("uidh1111")
try
{
const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
用户问题: ${userPrompt}
AI回答: ${llmText}`;
const titleResp = await client1.chat.completions.create({
model: "gpt-5-mini",
messages: [
{ role: "system", content: "你是标题生成助手,只返回标题,不要解释。" },
{ role: "user", content: titlePrompt }
]
});
const title = titleResp.choices[0]?.message?.content?.trim() || "未命名会话";
res.write(
`data: ${JSON.stringify({ type: "title", content: title })}\n\n`
);
console.log("生成的标题:", title);
// 保存到数据库(建议你给 ai_chat_messages 表新增一列 title,或者单独建一张会话表)
await pool.query(
"INSERT INTO ai_chat_messages (session_id, user_id, role, content,title) VALUES (?, ?, 'assistant', ?,?)",
[sessId, userId || null, llmText,title]
);
}
catch (err)
{
console.error("生成标题失败:", err.message);
}
}
res.write("data: [DONE]\n\n"); res.write("data: [DONE]\n\n");
res.end(); res.end();