node写一个ai聊天的服务demo
node 环境 16+
// main.js import OpenAI from 'openai'; import express from 'express'; import mysql from 'mysql2/promise'; // 初始化 openai 客户端 const openai = new OpenAI({ apiKey: "sk-034c7d21eaec4ec57ab70c231b3c", // 从环境变量读取 baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1' }); // 创建 Express 应用 const app = express(); const port = 3000; // 配置 MySQL 连接池 const pool = mysql.createPool({ host: '*', user: 'cutepet', password: 'xyjYJYcfxwNh*****', database: 'cutepet', charset: 'utf8mb4' }); // 定义 HTTP 路由 app.get('/chat', async (req, res) => { try { const history = []; const id = req.query.id; const h_id = req.query.h_id; if(!id){ id = 1; } // 从 MySQL 数据库中获取问题 const [rows] = await pool.execute('SELECT name FROM sheep_ai_question WHERE id = ' + id); if (rows.length === 0) { res.status(404).send('No question found in the database.'); return; } const question = rows[0].name; if(h_id){ const h_ids = h_id.split(','); for(let i = 0; i < h_ids.length; i++){ console.log(h_ids[i]) const [rows] = await pool.execute( `SELECT \`name\`, \`reply_text\` FROM sheep_ai_question WHERE id = ` + parseInt(h_ids[i])); if (rows.length === 0) { res.status(404).send('No question found in the database.'); return; } history.push( { role: 'user', content: rows[0].name }, { role: 'assistant', content: rows[0].reply_text }, ); } history.push({ role: 'user', content: question }); }else{ history.push({ role: 'user', content: question }); } console.log(history); // 设置响应头以支持流式传输 res.setHeader('Content-Type', 'text/event-stream;charset=utf-8'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); res.flushHeaders(); let reasoningContent = ''; let answerContent = ''; let isAnswering = false; // 调用 OpenAI API 并获取流式响应 const stream = await openai.chat.completions.create({ model: 'deepseek-v3', messages: history, stream: true }); // 处理流式响应 for await (const chunk of stream) { if (!chunk.choices?.length) { res.write('\nUsage:'); res.write(JSON.stringify(chunk.usage)); continue; } const delta = chunk.choices[0].delta; // 处理思考过程 if (delta.reasoning_content) { res.write(delta.reasoning_content); reasoningContent += delta.reasoning_content; } // 处理正式回复 else if (delta.content) { if (!isAnswering) { isAnswering = true; } res.write(delta.content); answerContent += delta.content; } } res.end(); } catch (error) { console.error('Error:', error); res.status(500).send('Internal Server Error'); } }); // 启动服务器 app.listen(port, () => { console.log(`Server running on port ${port}`); });
module安装方式使用npm。
package.json
{
"name": "ai-chatbot",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.18.2",
"mysql2": "^3.6.0",
"openai": "^4.17.0"
}
}
滴水成冰,世间不存在毫无意义的付出,时间终会给你答案。

浙公网安备 33010602011771号