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"
  }
}

作者:itbaby

出处:https://www.cnblogs.com/itbaby/p/18747881

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   知风阁  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示