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

@@ -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");