• 「AI人工智能」NodeJs使用openai流式请求与非流式请求



    前言

    NodeJs使用openai流式请求与非流式请求


    一、非流式请求

    一次性返回所有数据,请求时间较久,兼容性好。

    1.1 无上下文模式

    router.post("/openai", async (req, res) => {
        let url = 'https://api.openai.com/v1/engines/text-davinci-003/completions' // 3.5可用
        const response = await axios.post(url, {
            max_tokens: 1000,
            prompt: req.body.content,
        }, {
            headers: {
                'Authorization': 'Bearer ' + chat_key,
                'Content-Type': 'application/json'
            }
        });
        responseJSON(res, response)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    1.2 上下文模式

    // gpt3.5 - 完成 
    router.post("/chart", async (req, res) => {
        let param = req.body
        var data = JSON.stringify({
            messages: [
                {
                    "role": "user",
                    "content": param.content
                }],
            model: chatConfig.model || 'gpt-3.5-turbo',
            frequency_penalty: chatConfig.frequency_penalty || 0,
            max_tokens: chatConfig.max_tokens || 1000,
            presence_penalty: chatConfig.presence_penalty || 0,
            temperature: chatConfig.temperature || 1,
            top_p: chatConfig.top_p || 1
        });
        var config = {
            method: 'POST',
            url: 'https://api.openai.com/v1/chat/completions', // 反向代理可用 无反向代理请求超时
            headers: {
                'Authorization': 'Bearer ' + chat_key,
                'Content-Type': 'application/json',
            },
            timeout: 60 * 1000,
            data: data, // POST 反向代理可用
        };
        axios(config)
            .then((response) => {
                console.log(JSON.stringify(response.data));
                responseJSON(res, response.data.choices[0].message)
            })
            .catch((error) => {
                console.log(error);
                responseJSON(res, error)
            });
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    二、流式请求

    即时数据响应,请求时间短,交互效果好,不一定适配所有系统。

    let sendyhChatSteam = async (req, res, param) => {
        let _res = res;
        let data = {
            data: JSON.stringify({
            messages: [
                {
                    "role": "user",
                    "content": param.content
                }],
            frequency_penalty: chatConfig.frequency_penalty || 0,
            max_tokens: chatConfig.max_tokens || 1000,
            presence_penalty: chatConfig.presence_penalty || 0,
            temperature: chatConfig.temperature || 1,
            top_p: chatConfig.top_p || 1
            })
        };
    
        let options = {
            hostname: 'api.openai-proxy.com',
            path: 'gpt-3.5-turbo',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        };
        let question = ''
        let request = http.request(options, (response) => {
            response.setEncoding('utf8');
    
            // 监听 'data' 事件,获取返回的数据
            response.on('data', (chunk) => {
                question += chunk
                // 在这里处理每个数据块
                console.log(question);
            });
    
            // 监听 'end' 事件,表示数据传输完成
            response.on('end', () => {
                console.log('------------------监听 end 事件,表示数据传输完成-----------------------------');
                console.log(question);
            });
        });
        // 可以通过流式方式将数据写入请求
        request.write(JSON.stringify(data));
        // 结束请求
        request.end();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
  • 相关阅读:
    java变量的作用域
    js 数组与对象相互转换
    2023-10-19 指针与指针的指针,我就不信你脑壳不疼
    手机APP测试流程规范和方法你知道多少?
    linux sed命令使用说明
    数据结构-----平衡二叉树
    五粮液包装车间MES系统建设----工业软件讲坛第五次讲座
    屏幕录制视频编辑软件 Camtasia 2023 mac中文版软件功能
    CSS3 grid 网格/栅格布局
    284_C++_创建循环检测定时器到时线程
  • 原文地址:https://blog.csdn.net/qq_38209578/article/details/133989560