1.创建一个node项目
2.安装axios

npm install axios express

3.引入并写接口

const express = require('express');
const axios = require('axios');

const app = express();
const PORT = 3000; // 你可以根据需要修改端口号

// 允许解析JSON请求体
app.use(express.json());

// OpenAI API密钥,需要替换为你自己的密钥
const openaiApiKey = 'YOUR_OPENAI_API_KEY';

// OpenAI API端点
const openaiApiEndpoint = 'https://api.openai.com/v1/chat/completions';

// 创建一个接口路径为/openai-chat的POST接口
app.post('/openai-chat', async (req, res) => {
    try {
        const response = await axios.post(`${openaiApiEndpoint }`, {
            "model": "gpt-3.5-turbo",//模型版本
            "messages": [{"role": "user", "content": `${req.query.value}`}],//会话内容
            "temperature": 0.7,
            "stream": true //开启流式传输
        }, {
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${openaiApiKey }`,

            }, responseType: 'stream'
        });
        res.setHeader('Content-Type', 'text/event-stream');
        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Connection', 'keep-alive');
        response.data.on('data', (chunk) => {
            
            res.write(chunk);
        });
        response.data.on('end', () => {
            res.end();
        });
    } catch (error) {
        console.log(error)
        res.status(500).send('An error occurred');
    }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

在上面的代码中,我们创建了一个简单的Express应用,添加了一个接口路径为/openai-chat的POST接口。客户端可以通过POST请求将文本数据作为JSON发送到该接口。然后,我们使用axios库将文本发送到OpenAI API进行处理,并将OpenAI返回的响应以流的方式返回给客户端。

请注意,上述示例假设你已经获取了OpenAI的API密钥(需要账号加扣:787251775),并且已经订阅了Davinci Codex引擎的访问权限。在实际部署中,你需要根据你的应用场景和需求来设置合适的错误处理、身份验证、跨域处理等功能,这些在上述示例中未涉及。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐