优化输出内容
This commit is contained in:
175
server2.js
175
server2.js
@@ -1394,17 +1394,19 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
|
|
||||||
const { requestId } = req.body;
|
const { requestId } = req.body;
|
||||||
|
|
||||||
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
res.writeHead(200, {
|
||||||
res.setHeader("Transfer-Encoding", "chunked");
|
"Content-Type": "text/event-stream; charset=utf-8",
|
||||||
res.setHeader("Cache-Control", "no-cache");
|
"Cache-Control": "no-cache, no-transform",
|
||||||
res.setHeader("Connection", "keep-alive");
|
"Connection": "keep-alive",
|
||||||
|
"X-Accel-Buffering": "no",
|
||||||
|
});
|
||||||
|
res.flushHeaders?.();
|
||||||
let aborted = false;
|
let aborted = false;
|
||||||
req.on("close", () => {
|
req.on("close", () => {
|
||||||
console.log("🔴 前端断开连接,停止整个分析流程");
|
console.log("🔴 前端断开连接,停止整个分析流程");
|
||||||
aborted = true;
|
aborted = true;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
console.time("analyze");
|
console.time("analyze");
|
||||||
const logBody = { ...req.body };
|
const logBody = { ...req.body };
|
||||||
if (req.body?.imageBase64) {
|
if (req.body?.imageBase64) {
|
||||||
@@ -1412,7 +1414,6 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
}
|
}
|
||||||
console.log("analyze: ", logBody);
|
console.log("analyze: ", logBody);
|
||||||
|
|
||||||
// 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: "缺少必要参数" });
|
||||||
@@ -1432,9 +1433,8 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
[sessionId, userId]
|
[sessionId, userId]
|
||||||
);
|
);
|
||||||
const existingTitle = rows[0].hasTitle === 1; // true / false
|
const existingTitle = rows[0].hasTitle === 1; // true / false
|
||||||
console.log(existingTitle, rows?.[0], 9999, rows)
|
console.log(existingTitle, rows?.[0], 9999, rows);
|
||||||
|
|
||||||
// 如果前端没有传 sessionId,生成一个
|
|
||||||
const sessId = sessionId || Date.now().toString();
|
const sessId = sessionId || Date.now().toString();
|
||||||
|
|
||||||
// ------------------ 获取历史对话(上下文) ------------------
|
// ------------------ 获取历史对话(上下文) ------------------
|
||||||
@@ -1470,20 +1470,17 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
return message;
|
return message;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
// ------------------ 保存用户提问 ------------------
|
// ------------------ 保存用户提问 ------------------
|
||||||
await pool.query(
|
await pool.query(
|
||||||
"INSERT INTO ai_chat_messages (session_id, user_id, role, content, image_base64) VALUES (?, ?, 'user', ?, ?)",
|
"INSERT INTO ai_chat_messages (session_id, user_id, role, content, image_base64) VALUES (?, ?, 'user', ?, ?)",
|
||||||
[sessId, userId || null, userPrompt || "", imageBase64 || null]
|
[sessId, userId || null, userPrompt || "", imageBase64 || null]
|
||||||
);
|
);
|
||||||
|
|
||||||
// console.log("userPrompt: ",userPrompt);
|
|
||||||
// console.log("imageBase64: ",imageBase64);
|
|
||||||
// console.log("userId: ",userId);
|
|
||||||
// console.log("sessionId: ",sessionId);
|
|
||||||
|
|
||||||
// ------------------ 图像分析 ------------------
|
// ------------------ 图像分析 ------------------
|
||||||
// 构建包含上下文的消息数组
|
let sceneText = "";
|
||||||
|
|
||||||
|
// If an image is uploaded, start with image analysis
|
||||||
|
if (imageBase64) {
|
||||||
const imageAnalysisMessages = [
|
const imageAnalysisMessages = [
|
||||||
{
|
{
|
||||||
role: "system",
|
role: "system",
|
||||||
@@ -1493,7 +1490,12 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
{
|
{
|
||||||
role: "user",
|
role: "user",
|
||||||
content: [
|
content: [
|
||||||
{ type: "text", text: userPrompt || "请描述图片内容,并给出分析思考过程" },
|
{ type: "text", text: userPrompt || `请描述图片内容, 请输出【思路概览】,模拟人类分析问题的过程,但不要暴露内部推理细节。
|
||||||
|
|
||||||
|
要求:
|
||||||
|
- 使用项目符号
|
||||||
|
- 只输出思路,不给结论
|
||||||
|
` },
|
||||||
imageBase64
|
imageBase64
|
||||||
? {
|
? {
|
||||||
type: "image_url",
|
type: "image_url",
|
||||||
@@ -1514,22 +1516,15 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
messages: imageAnalysisMessages
|
messages: imageAnalysisMessages
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log("====== 开始图像分析... ======")
|
console.log("====== 开始图像分析... ======");
|
||||||
let sceneText = "";
|
/* TLS 加密缓冲 */
|
||||||
|
|
||||||
/* TLS 加密缓冲,小块数据可能先缓存在服务器端,不立即发送,会导致图像分析模型的结果不能立即返回 */
|
|
||||||
res.writeHead(200, {
|
|
||||||
"Content-Type": "text/event-stream",
|
|
||||||
"Cache-Control": "no-cache",
|
|
||||||
"Connection": "keep-alive",
|
|
||||||
});
|
|
||||||
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();
|
||||||
stopFlags.delete(requestId); // 用完清理
|
stopFlags.delete(requestId); // 清理
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const delta = chunk.choices[0]?.delta?.content || "";
|
const delta = chunk.choices[0]?.delta?.content || "";
|
||||||
@@ -1540,18 +1535,11 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
`data: ${JSON.stringify({ type: "scene", content: delta })}\n\n`
|
`data: ${JSON.stringify({ type: "scene", content: delta })}\n\n`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// if (delta)
|
|
||||||
// {
|
|
||||||
// for (const ch of delta)
|
|
||||||
// {
|
|
||||||
// res.write(`data: ${JSON.stringify({ type: "scene", content: ch })}\n\n`);
|
|
||||||
// await new Promise(r => setTimeout(r, 0)); // 控制渲染节奏
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
console.log(sceneText);
|
console.log(sceneText);
|
||||||
console.log("====== 图像分析结束 ======")
|
console.log("====== 图像分析结束 ======");
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------ ① 思路阶段(模拟 ChatGPT 思考) ------------------
|
// ------------------ ① 思路阶段(模拟 ChatGPT 思考) ------------------
|
||||||
const thinkingMessages = [
|
const thinkingMessages = [
|
||||||
{
|
{
|
||||||
@@ -1609,43 +1597,6 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
console.log(thinkingText);
|
console.log(thinkingText);
|
||||||
console.log("====== 思路输出结束 ======");
|
console.log("====== 思路输出结束 ======");
|
||||||
|
|
||||||
|
|
||||||
// 保存图像分析结果到数据库
|
|
||||||
// await pool.query(
|
|
||||||
// "INSERT INTO ai_chat_messages (session_id, user_id, role, content) VALUES (?, ?, 'assistant', ?)",
|
|
||||||
// [sessId, userId || null, sceneText]
|
|
||||||
// );
|
|
||||||
|
|
||||||
// ------------------ 3️⃣ LLM 分析 ------------------
|
|
||||||
// console.log("LLM 分析 sceneText: ", sceneText)
|
|
||||||
// const preText = "详细分析这个光伏场站,根据图片给出详细的运维方案"
|
|
||||||
// + "如果这个光伏场站需要割草怎么做,给出一份详细的计划"
|
|
||||||
// + "如果这个光伏场站需要用无人机清洗怎么做,给出一份详细的计划"
|
|
||||||
// + "如果这个光伏场站需要巡检怎么做,给出一份详细的计划"
|
|
||||||
|
|
||||||
// 构建包含完整上下文的LLM消息数组
|
|
||||||
const llmMessages = [
|
|
||||||
{
|
|
||||||
role: "system",
|
|
||||||
content: "你是一名新能源项目的图像分析AI分析师,需要结合历史对话提供专业建议。"
|
|
||||||
},
|
|
||||||
...historyMessages, // 添加历史对话作为上下文
|
|
||||||
{
|
|
||||||
role: "user",
|
|
||||||
content: userPrompt || "请基于图片分析提供建议。"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
role: "assistant",
|
|
||||||
content: sceneText // 添加当前图像分析结果
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
// const llmStream = await client1.chat.completions.create({
|
|
||||||
// model: "gpt-5-mini",
|
|
||||||
// stream: true,
|
|
||||||
// messages: llmMessages
|
|
||||||
// });
|
|
||||||
|
|
||||||
// ------------------ ② 结论阶段(最终分析) ------------------
|
// ------------------ ② 结论阶段(最终分析) ------------------
|
||||||
const answerMessages = [
|
const answerMessages = [
|
||||||
{
|
{
|
||||||
@@ -1704,53 +1655,15 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
console.log(llmText);
|
console.log(llmText);
|
||||||
console.log("====== 最终分析结束 ======");
|
console.log("====== 最终分析结束 ======");
|
||||||
|
|
||||||
|
// ------------------ Save Results to Database ------------------
|
||||||
// console.log("====== 开始深度思考... ======")
|
|
||||||
// let llmText = "";
|
|
||||||
// for await (const chunk of llmStream) {
|
|
||||||
// if (stopFlags.get(requestId)) {
|
|
||||||
// console.log("⛔ 深度分析被前端中断");
|
|
||||||
// res.end();
|
|
||||||
// stopFlags.delete(requestId);
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
// const delta = chunk.choices[0]?.delta?.content || "";
|
|
||||||
// llmText += delta;
|
|
||||||
|
|
||||||
// if (delta)
|
|
||||||
// res.write(
|
|
||||||
// `data: ${JSON.stringify({ type: "llm", content: delta })}\n\n`
|
|
||||||
// );
|
|
||||||
|
|
||||||
|
|
||||||
// /* delta 很长,这会 人为拉长处理时间。 */
|
|
||||||
// // if (delta)
|
|
||||||
// // {
|
|
||||||
// // for (const ch of delta)
|
|
||||||
// // {
|
|
||||||
// // res.write(`data: ${JSON.stringify({ type: "llm", content: ch })}\n\n`);
|
|
||||||
// // await new Promise(r => setTimeout(r, 0)); // 控制渲染节奏
|
|
||||||
// // }
|
|
||||||
// // }
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
|
||||||
// 保存 LLM 输出到数据库
|
|
||||||
/* 加标题需要异步,且在会话开始时就进行 */
|
|
||||||
if (existingTitle) {
|
if (existingTitle) {
|
||||||
console.log("uidh")
|
|
||||||
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 {
|
} else {
|
||||||
console.log("uidh1111")
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
|
const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):\n用户问题: ${userPrompt}\nAI回答: ${llmText}`;
|
||||||
用户问题: ${userPrompt}
|
|
||||||
AI回答: ${llmText}`;
|
|
||||||
|
|
||||||
const titleResp = await client1.chat.completions.create({
|
const titleResp = await client1.chat.completions.create({
|
||||||
model: "gpt-5-mini",
|
model: "gpt-5-mini",
|
||||||
messages: [
|
messages: [
|
||||||
@@ -1763,23 +1676,17 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
res.write(
|
res.write(
|
||||||
`data: ${JSON.stringify({ type: "title", content: title })}\n\n`
|
`data: ${JSON.stringify({ type: "title", content: title })}\n\n`
|
||||||
);
|
);
|
||||||
|
|
||||||
console.log("生成的标题:", title);
|
console.log("生成的标题:", 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
res.write("data: [DONE]\n\n");
|
res.write("data: [DONE]\n\n");
|
||||||
res.end();
|
res.end();
|
||||||
|
|
||||||
@@ -1790,19 +1697,19 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
console.log("====== 分析完成 ======");
|
console.log("====== 分析完成 ======");
|
||||||
console.timeEnd("analyze");
|
console.timeEnd("analyze");
|
||||||
|
|
||||||
// // 更新用户剩余对话次数
|
} catch (err) {
|
||||||
// let userChatNum = await getQuota(userId);
|
console.error("❌ 调用失败:", err.message);
|
||||||
// if(userChatNum!==-1){
|
|
||||||
// userChatNum = Math.max(0, userChatNum - 1); // 防止变成负数
|
if (!res.headersSent) {
|
||||||
// await setQuota(userId,userChatNum);
|
res.status(500).json({ error: err.message });
|
||||||
// console.log(`用户剩余AI 对话次数: ${userChatNum}`);
|
} else {
|
||||||
// }
|
res.write(`data: ${JSON.stringify({
|
||||||
|
type: "error",
|
||||||
|
message: err.message
|
||||||
|
})}\n\n`);
|
||||||
|
res.end();
|
||||||
}
|
}
|
||||||
catch (err) {
|
} finally {
|
||||||
console.error("❌ 调用失败:", err.response?.data || err.message);
|
|
||||||
res.status(500).json({ code: 1, error: err.response?.data || err.message });
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
let userChatNum = await getQuota(userId);
|
let userChatNum = await getQuota(userId);
|
||||||
if (userChatNum !== -1 && userChatNum !== undefined) {
|
if (userChatNum !== -1 && userChatNum !== undefined) {
|
||||||
userChatNum = Math.max(0, userChatNum - 1); // 防止变成负数
|
userChatNum = Math.max(0, userChatNum - 1); // 防止变成负数
|
||||||
@@ -1814,10 +1721,10 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
);
|
);
|
||||||
console.log("更新用户对话次数:", userId, userChatNum);
|
console.log("更新用户对话次数:", userId, userChatNum);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
app.post("/stop", express.json(), (req, res) => {
|
app.post("/stop", express.json(), (req, res) => {
|
||||||
const { requestId } = req.body;
|
const { requestId } = req.body;
|
||||||
console.log("🔴 收到停止信号:", requestId);
|
console.log("🔴 收到停止信号:", requestId);
|
||||||
|
|||||||
Reference in New Issue
Block a user