node写一个ai聊天的服务demo
1 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 | { "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" } } |
滴水成冰,世间不存在毫无意义的付出,时间终会给你答案。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现