This commit is contained in:
2025-11-24 13:15:17 +08:00
parent c1e38d8e0a
commit fc5ef75510
3 changed files with 101 additions and 63 deletions

View File

@@ -2073,6 +2073,12 @@
chatMessages.appendChild(msg);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
function uuid() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
function sendMessage(isPre) {
@@ -2130,6 +2136,22 @@
}
getAiResponse(imgUrl);
}
let renderPending = false;
let lastRendered = "";
// 实时渲染 + 不闪烁 + 性能好
function smartRender(msgDiv, text) {
if (renderPending) return; // 避免频繁渲染
renderPending = true;
requestAnimationFrame(() => {
if (lastRendered !== text) {
msgDiv.innerHTML = marked.parse(text); // 实时解析 Markdown
lastRendered = text;
}
renderPending = false;
});
}
let reader;
const getAiResponse = async (img) => {
@@ -2158,7 +2180,8 @@
// ✅ 创建 AbortController
controller = new AbortController();
sendParam.requestId = crypto.randomUUID();
// sendParam.requestId = crypto.randomUUID();
sendParam.requestId=uuid();
const res = await fetch("https://serviceai.satabot.com/analyze", {
method: "POST",
@@ -2168,7 +2191,7 @@
}).catch(err => {
console.log("✅ 流被中断:", err.name);
clearInterval(interval);
controller.abort();
// controller.abort();
controller = null;
@@ -2240,6 +2263,9 @@
const stopBtn = document.querySelector('#stopBtn');
sendBtnImg.classList.remove('none');
stopBtn.classList.add('none');
msgDiv.innerHTML = marked.parse(aiMsg.content);
setTimeout(scrollToBottom, 0); // chatMessages.scrollTop = chatMessages.scrollHeight;
return;
@@ -2256,10 +2282,14 @@
// }
if (obj.content && obj.type !== "title") {
for (const char of obj.content) {
await new Promise(r => setTimeout(r, 1)); // 控制字速
await new Promise(r => setTimeout(r, 2)); // 控制字速
if (isStopped) return;
aiMsg.content += char;
msgDiv.innerHTML = marked.parse(aiMsg.content);
smartRender(msgDiv, aiMsg.content);
// msgDiv.insertAdjacentText("beforeend", char);
// msgDiv.innerHTML = marked.parse(aiMsg.content);
// chatMessages.scrollTop = chatMessages.scrollHeight;
setTimeout(scrollToBottom, 0);
@@ -2429,7 +2459,7 @@
const deleteSession = (sessionId, userId) => {
if (activeChatId == sessionId) {
if (controller) {
controller.abort();
// controller.abort();
controller = null;
if (sendBtnImg.classList.contains('none')) {
sendBtnImg.classList.remove('none');
@@ -2706,7 +2736,7 @@
}
if (controller) {
controller.abort();
// controller.abort();
controller = null;
if (sendBtnImg.classList.contains('none')) {
sendBtnImg.classList.remove('none');

View File

@@ -1,6 +1,7 @@
{
"name": "node-server",
"version": "1.0.0",
"type": "commonjs",
"description": "",
"main": "server2.js",
"scripts": {

View File

@@ -8,6 +8,21 @@ const OpenAI = require("openai");
const xml2js = require('xml2js');
const xmlparser = require('express-xml-bodyparser'); // 引入XML解析中间件
const https = require("https");
// 强制 IPv4 的 https agent
const ipv4Agent = new https.Agent({
family: 4, // 👈 最关键:强制 IPv4
keepAlive: true
});
// 包一个强制 IPv4 的 fetch
const fetchIPv4 = (url, options = {}) => {
return fetch(url, {
...options,
agent: ipv4Agent, // 👈 加上 IPv4 专用 agent
});
};
const bodyParser = require("body-parser");
const axios = require('axios');
@@ -105,16 +120,32 @@ const client = new OpenAI({
apiKey: "DxvRiQWROzLTapiSHcK0FXKAAXDBlhci1XaqTTpr50sgUsAkmxfUJQQJ99BIACYeBjFXJ3w3AAABACOGZdHp",
baseURL: "https://satabot.openai.azure.com/openai/deployments/gpt-4.1",
defaultQuery: { "api-version": "2024-04-01-preview" },
timeout: 120000
timeout: 120000,
fetch: fetchIPv4 // 👈 关键点:把自定义 fetch 注入 SDK
});
const client1 = new OpenAI({
apiKey: "DxvRiQWROzLTapiSHcK0FXKAAXDBlhci1XaqTTpr50sgUsAkmxfUJQQJ99BIACYeBjFXJ3w3AAABACOGZdHp",
baseURL: "https://satabot.openai.azure.com/openai/deployments/gpt-5-mini/",
defaultQuery: { "api-version": "2024-04-01-preview" },
timeout: 120000
timeout: 120000,
fetch: fetchIPv4 // 👈 关键点:把自定义 fetch 注入 SDK
});
async function test()
{
console.time("test");
await client.chat.completions.create({
model: "gpt-4.1", // 注意:这里必须是你在 Azure portal 里创建的“部署名称”
messages: [
{ role: "user", content: "ping" }
]
});
console.timeEnd("test");
}
test();
// 获取 access_token
// getAccessToken();
async function getAccessToken() {
@@ -434,31 +465,7 @@ app.post('/wechat', async (req, res) => {
}
});
// 新增:发送客服消息的函数
async function sendCustomerServiceMessage(openid, content) {
try {
const token = await getAccessToken();
const url = `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${token}`;
const data = {
touser: openid,
msgtype: 'text',
text: {
content: content
}
};
await axios.post(url, data, {
headers: {
'Content-Type': 'application/json'
}
});
console.log("客服消息发送成功");
} catch (err) {
console.error("发送客服消息失败:", err);
}
}
// app.post('/wechat', async (req, res) => {
// try {
// console.log(req,"收到恢复")
@@ -841,12 +848,12 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.setHeader("Transfer-Encoding", "chunked");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
let aborted = false;
req.on("close", () => {
res.setHeader("Connection", "keep-alive");
let aborted = false;
req.on("close", () => {
console.log("🔴 前端断开连接,停止整个分析流程");
aborted = true;
});
});
const logBody = { ...req.body };
@@ -950,7 +957,6 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
let sceneText = "";
for await (const chunk of completion)
{
console.log(stopFlags.get(requestId),"停止了嘛")
if (stopFlags.get(requestId)) {
console.log("⛔ 图像分析被前端中断");
res.end();
@@ -1030,42 +1036,43 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
res.write(`data: ${JSON.stringify({ type: "llm", content: ch })}\n\n`);
await new Promise(r => setTimeout(r, 0)); // 控制渲染节奏
}
}
}
}
// 保存 LLM 输出到数据库
try {
const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
用户问题: ${userPrompt}
AI回答: ${llmText}`;
// 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 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`
);
// const title = titleResp.choices[0]?.message?.content?.trim() || "未命名会话";
// res.write(
// `data: ${JSON.stringify({ type: "title", content: title })}\n\n`
// );
console.log("生成的标题:", title);
// 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]
);
// // 保存到数据库(建议你给 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);
}
// }
// catch (err) {
// console.error("生成标题失败:", err.message);
// }
res.write("data: [DONE]\n\n");