NodeJS ExpressJS和OpenAI API - createCompletion方法不起作用(类型错误:将循环结构转换为JSON)

hgc7kmma  于 2023-02-18  发布在  Node.js
关注(0)|答案(2)|浏览(196)

我只是在试用OpenAI的API,并运行了一个非常基本的express应用程序,我想做的只是让它用基本的输入返回一个适当的响应,但它目前一直失败。
我正在使用Postman迭代localhost上的代码。所有的包都已经安装,API密钥是正确的,并且在.env文件中指定。
我目前的工作文件如下。我肯定会踢自己,但有人能看出我可能做了什么蠢事吗?

const express = require('express');
const app = express();
require('dotenv').config();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const axios = require('axios'); // Come back to this

const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

app.get('/api/v1', async (req, res) => {
    
  let body = {
      model: "text-davinci-003",        
      prompt: "How are you?",
      temperature: 1,
      max_tokens: 2086,
      top_p: 1,
      frequency_penalty: 0,
      presence_penalty: 0,
  };

  
  const response = await openai.createCompletion(body);

  res.send({ response });
});

// Listen for requests
app.listen(3000, function() {
    console.log('Server is listening on port 3000');
});

终端中生成错误

/home/mint-pc/Desktop/projects/ebooks/api/node_modules/express/lib/response.js:1150
    : JSON.stringify(value);
           ^

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'ClientRequest'
    |     property 'socket' -> object with constructor 'TLSSocket'
    --- property '_httpMessage' closes the circle
    at JSON.stringify (<anonymous>)
    at stringify (/home/mint-pc/Desktop/projects/ebooks/api/node_modules/express/lib/response.js:1150:12)
    at ServerResponse.json (/home/mint-pc/Desktop/projects/ebooks/api/node_modules/express/lib/response.js:271:14)
    at ServerResponse.send (/home/mint-pc/Desktop/projects/ebooks/api/node_modules/express/lib/response.js:162:21)
    at /home/mint-pc/Desktop/projects/ebooks/api/ghost_writer.js:48:7
ttygqcqt

ttygqcqt1#

步骤1:运行Express服务器

在终端中运行nodemon test.js

    • 测试. js**
const express = require('express');
const app = express();

const bodyParser = require('body-parser');

app.use(bodyParser.json());

const { OpenAIApi } = require("openai");

const openai = new OpenAIApi();

app.post('https://api.openai.com/v1/completions', async (req, res) => {
    try {
        const request_options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer xxxxx`
            },
            body: {
                model: req.body.model,
                prompt: req.body.prompt,
                max_tokens: 7,
                temperature: 0
            }
        }

        openai.createCompletion(request_options)
            .then((response) => {
                res.send({ response });
            })
            .catch(err => {
                console.log(err.message);
            })
    } catch (error) {
        console.log(error);
    }
});

app.listen(3000, function() {
    console.log('Server is listening on port 3000');
});

步骤2:在请求正文中提供modelprompt参数

{
  "model": "text-davinci-003",
  "prompt": "Say this is a test"
}

截图:

    • 另外,不要忘记提供API密钥!**

截图:

步骤3:单击"发送"发出HTTP POST请求

您应该得到200 OK和以下响应:

{
  "id": "cmpl-6ZNYkREx9KEThpq2keFD9E1Xic3q6",
  "object": "text_completion",
  "created": 1673890062,
  "model": "text-davinci-003",
  "choices": [
    {
      "text": "\n\nThis is indeed a test.",
      "index": 0,
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 5,
    "completion_tokens": 8,
    "total_tokens": 13
  }
}
h5qlskok

h5qlskok2#

@Boaz在这篇评论中提供的答案:“检查响应对象。它可能是完整的HTTP响应对象,而不仅仅是响应数据...”
就是那个。

相关问题