Home > Net >  Express app and OpenAI API - createCompletion method not working
Express app and OpenAI API - createCompletion method not working

Time:01-17

Just experimenting with OpenAI's api and have a very basic express app up and running. What I'm trying to do is just get it to send me back an appropriate response with a basic input but it currently keeps failing.

I'm using Postman to iterate on the code on localhost. All packages are definitely installed and the API key is correct and specfied in the .env file.

My current working file is below. I'm sure I'll kick myself but can anyone spot what dumb thing I've probably done?

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');
});

Error generated in terminal

/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

CodePudding user response:

This is the correct URL (see the documentation):

POST https://api.openai.com/v1/completions

So, change this...

app.get('/api/v1', async (req, res) => { ... }

...to this.

app.post('/api/v1/completions', async (req, res) => { ... }

CodePudding user response:

Answer provided by @Boaz: "Inspect the response object. It's likely a complete HTTP response object and not just the response data..."

It was that.

  • Related