Hi, I’m getting empty responses from OpenAIs chat completions API.
Heres my code:
import { MongoClient } from "mongodb";
import fetch from "node-fetch";
import { nanoid } from "nanoid";
// Replace the uri string with your MongoDB deployment's connection string.
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);
export default async function run(req, res) {
try {
// Get the database and collection on which to run the operation
const database = client.db("users");
const gptKeys = database.collection("gptKeys");
// Query for a movie that has the title 'The Room'
const query = { userid: req.body.userid };
// Execute query
const key = await gptKeys.findOne(query);
const body = {
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: "create a blog article about" + req.body.topic
}
]
};
fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + key.key
},
body: JSON.stringify(body)
})
.then(response => response.json())
.then(async data => {
console.log(data);
await client.connect();
const database = client.db("users");
const users = database.collection("users");
const result = await users.insertOne({ _id: nanoid(), response: data.completions.choices[0].message.content, userid: req.body.userid, date: new Date() });
console.log(`New user created: ${result}`);
res.status(201).json({ result: result });
})
.catch((error) => {
console.error('Error:', error);
res.status(400).json({ error: error });
});
// Print the document returned
} finally {
await client.close();
}
}
Heres the response:
{
id: 'chatcmpl-98tash2sZiegFqgI0JxhOa6zqr0xV',
object: 'chat.completion',
created: 1711907354,
model: 'gpt-3.5-turbo-0125',
choices: [
{
index: 0,
message: [Object],
logprobs: null,
finish_reason: 'stop'
}
],
usage: { prompt_tokens: 22, completion_tokens: 586, total_tokens: 608 },
system_fingerprint: 'fp_3bc1b5746c'
}
I cant seem to figure out why the respneded message is an empty object. I bought the credits I need btw and don’t want to run through all of them just trying to figure this out.