temp
This commit is contained in:
42
index.html
42
index.html
@@ -2073,6 +2073,12 @@
|
|||||||
chatMessages.appendChild(msg);
|
chatMessages.appendChild(msg);
|
||||||
chatMessages.scrollTop = chatMessages.scrollHeight;
|
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) {
|
function sendMessage(isPre) {
|
||||||
@@ -2130,6 +2136,22 @@
|
|||||||
}
|
}
|
||||||
getAiResponse(imgUrl);
|
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;
|
let reader;
|
||||||
const getAiResponse = async (img) => {
|
const getAiResponse = async (img) => {
|
||||||
|
|
||||||
@@ -2158,7 +2180,8 @@
|
|||||||
|
|
||||||
// ✅ 创建 AbortController
|
// ✅ 创建 AbortController
|
||||||
controller = new AbortController();
|
controller = new AbortController();
|
||||||
sendParam.requestId = crypto.randomUUID();
|
// sendParam.requestId = crypto.randomUUID();
|
||||||
|
sendParam.requestId=uuid();
|
||||||
|
|
||||||
const res = await fetch("https://serviceai.satabot.com/analyze", {
|
const res = await fetch("https://serviceai.satabot.com/analyze", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -2168,7 +2191,7 @@
|
|||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
console.log("✅ 流被中断:", err.name);
|
console.log("✅ 流被中断:", err.name);
|
||||||
clearInterval(interval);
|
clearInterval(interval);
|
||||||
controller.abort();
|
// controller.abort();
|
||||||
|
|
||||||
controller = null;
|
controller = null;
|
||||||
|
|
||||||
@@ -2240,6 +2263,9 @@
|
|||||||
const stopBtn = document.querySelector('#stopBtn');
|
const stopBtn = document.querySelector('#stopBtn');
|
||||||
sendBtnImg.classList.remove('none');
|
sendBtnImg.classList.remove('none');
|
||||||
stopBtn.classList.add('none');
|
stopBtn.classList.add('none');
|
||||||
|
msgDiv.innerHTML = marked.parse(aiMsg.content);
|
||||||
|
|
||||||
|
|
||||||
setTimeout(scrollToBottom, 0); // chatMessages.scrollTop = chatMessages.scrollHeight;
|
setTimeout(scrollToBottom, 0); // chatMessages.scrollTop = chatMessages.scrollHeight;
|
||||||
|
|
||||||
return;
|
return;
|
||||||
@@ -2256,10 +2282,14 @@
|
|||||||
// }
|
// }
|
||||||
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, 1)); // 控制字速
|
await new Promise(r => setTimeout(r, 2)); // 控制字速
|
||||||
if (isStopped) return;
|
if (isStopped) return;
|
||||||
aiMsg.content += char;
|
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;
|
// chatMessages.scrollTop = chatMessages.scrollHeight;
|
||||||
setTimeout(scrollToBottom, 0);
|
setTimeout(scrollToBottom, 0);
|
||||||
@@ -2429,7 +2459,7 @@
|
|||||||
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');
|
||||||
@@ -2706,7 +2736,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
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');
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "node-server",
|
"name": "node-server",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
|
"type": "commonjs",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "server2.js",
|
"main": "server2.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
119
server2.js
119
server2.js
@@ -8,6 +8,21 @@ const OpenAI = require("openai");
|
|||||||
const xml2js = require('xml2js');
|
const xml2js = require('xml2js');
|
||||||
const xmlparser = require('express-xml-bodyparser'); // 引入XML解析中间件
|
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 bodyParser = require("body-parser");
|
||||||
const axios = require('axios');
|
const axios = require('axios');
|
||||||
@@ -105,16 +120,32 @@ const client = new OpenAI({
|
|||||||
apiKey: "DxvRiQWROzLTapiSHcK0FXKAAXDBlhci1XaqTTpr50sgUsAkmxfUJQQJ99BIACYeBjFXJ3w3AAABACOGZdHp",
|
apiKey: "DxvRiQWROzLTapiSHcK0FXKAAXDBlhci1XaqTTpr50sgUsAkmxfUJQQJ99BIACYeBjFXJ3w3AAABACOGZdHp",
|
||||||
baseURL: "https://satabot.openai.azure.com/openai/deployments/gpt-4.1",
|
baseURL: "https://satabot.openai.azure.com/openai/deployments/gpt-4.1",
|
||||||
defaultQuery: { "api-version": "2024-04-01-preview" },
|
defaultQuery: { "api-version": "2024-04-01-preview" },
|
||||||
timeout: 120000
|
timeout: 120000,
|
||||||
|
fetch: fetchIPv4 // 👈 关键点:把自定义 fetch 注入 SDK
|
||||||
});
|
});
|
||||||
const client1 = new OpenAI({
|
const client1 = new OpenAI({
|
||||||
apiKey: "DxvRiQWROzLTapiSHcK0FXKAAXDBlhci1XaqTTpr50sgUsAkmxfUJQQJ99BIACYeBjFXJ3w3AAABACOGZdHp",
|
apiKey: "DxvRiQWROzLTapiSHcK0FXKAAXDBlhci1XaqTTpr50sgUsAkmxfUJQQJ99BIACYeBjFXJ3w3AAABACOGZdHp",
|
||||||
baseURL: "https://satabot.openai.azure.com/openai/deployments/gpt-5-mini/",
|
baseURL: "https://satabot.openai.azure.com/openai/deployments/gpt-5-mini/",
|
||||||
defaultQuery: { "api-version": "2024-04-01-preview" },
|
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
|
// 获取 access_token
|
||||||
// getAccessToken();
|
// getAccessToken();
|
||||||
async function 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) => {
|
// app.post('/wechat', async (req, res) => {
|
||||||
// try {
|
// try {
|
||||||
// console.log(req,"收到恢复")
|
// 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("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");
|
||||||
res.setHeader("Connection", "keep-alive");
|
res.setHeader("Connection", "keep-alive");
|
||||||
let aborted = false;
|
let aborted = false;
|
||||||
req.on("close", () => {
|
req.on("close", () => {
|
||||||
console.log("🔴 前端断开连接,停止整个分析流程");
|
console.log("🔴 前端断开连接,停止整个分析流程");
|
||||||
aborted = true;
|
aborted = true;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
const logBody = { ...req.body };
|
const logBody = { ...req.body };
|
||||||
@@ -950,7 +957,6 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
|
|||||||
let sceneText = "";
|
let sceneText = "";
|
||||||
for await (const chunk of completion)
|
for await (const chunk of completion)
|
||||||
{
|
{
|
||||||
console.log(stopFlags.get(requestId),"停止了嘛")
|
|
||||||
if (stopFlags.get(requestId)) {
|
if (stopFlags.get(requestId)) {
|
||||||
console.log("⛔ 图像分析被前端中断");
|
console.log("⛔ 图像分析被前端中断");
|
||||||
res.end();
|
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`);
|
res.write(`data: ${JSON.stringify({ type: "llm", content: ch })}\n\n`);
|
||||||
await new Promise(r => setTimeout(r, 0)); // 控制渲染节奏
|
await new Promise(r => setTimeout(r, 0)); // 控制渲染节奏
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// 保存 LLM 输出到数据库
|
// 保存 LLM 输出到数据库
|
||||||
|
|
||||||
try {
|
// try {
|
||||||
const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
|
// const titlePrompt = `请根据以下对话内容生成一个简短的标题(不超过15字):
|
||||||
用户问题: ${userPrompt}
|
// 用户问题: ${userPrompt}
|
||||||
AI回答: ${llmText}`;
|
// 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: [
|
||||||
{ role: "system", content: "你是标题生成助手,只返回标题,不要解释。" },
|
// { role: "system", content: "你是标题生成助手,只返回标题,不要解释。" },
|
||||||
{ role: "user", content: titlePrompt }
|
// { role: "user", content: titlePrompt }
|
||||||
]
|
// ]
|
||||||
});
|
// });
|
||||||
|
|
||||||
const title = titleResp.choices[0]?.message?.content?.trim() || "未命名会话";
|
// const title = titleResp.choices[0]?.message?.content?.trim() || "未命名会话";
|
||||||
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,或者单独建一张会话表)
|
// // 保存到数据库(建议你给 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) {
|
// }
|
||||||
console.error("生成标题失败:", err.message);
|
// catch (err) {
|
||||||
}
|
// console.error("生成标题失败:", err.message);
|
||||||
|
// }
|
||||||
|
|
||||||
|
|
||||||
res.write("data: [DONE]\n\n");
|
res.write("data: [DONE]\n\n");
|
||||||
|
|||||||
Reference in New Issue
Block a user