OpenAI API error, please help!

I’m trying to build a chat web where I can get a response from a bot using OpenAI API, and I can get the answer from the terminal but not on the web, been trying to solve it but I can’t, any help would be much appreciated!

import express from “express”;
import axios from “axios”;
import dotenv from “dotenv”;
import { openai } from “…/index.js”;

dotenv.config();
const router = express.Router();

router.post(“/text”, async (req, res) => {
try {
const { text, activeChatId } = req.body;
console.log(“req.body:”, req.body);

const response = await openai.chat.completions.create({
  model: "gpt-3.5-turbo",
  messages: [
    { role: "system", content: "You are a helpful assistant." }, // what role they will assume
    { role: "user", content: text }, // the message that the user sends
  ],
});
console.log("response data", response.data);

const chatEngineResponse = await axios.post(
  `https://api.chatengine.io/chats/${activeChatId}/messages/`,
  { text: response.choices[0].message },
  {
    headers: {
      "Project-ID": process.env.PROJECT_ID,
      "User-Name": process.env.BOT_USER_NAME,
      "User-Secret": process.env.BOT_USER_SECRET,
    },
  }
);
console.log("chatEngineResponse:", chatEngineResponse.data);

res.status(200).json({ text: response.choices[0].message });

} catch (error) {
console.error(“error”, error);
res.status(500).json({ error: error.message });
}
});

export default router;

And I get this error on my terminal
response data undefined
error AxiosError: Request failed with status code 400

But also get the response on the terminal only like:
text: ‘how are you?’,
data: {"text":{"role":"assistant","content":"I'm just a computer program, so I don't have feelings, but I'm here and ready to help you with anything you need. How can I assist you today?"}}

The format of return value of Chat completions is like this:

{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "model": "gpt-3.5-turbo-0125",
  "system_fingerprint": "fp_44709d6fcb",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "\n\nHello there, how may I assist you today?",
    },
    "logprobs": null,
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21
  }
}

There is no response.data hence you get undefined. As for the second API call, you are getting response.choices[0].message which is correct hence the result.

Check the API reference page

1 Like