最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - OpenAI Chat Completions API error: "Request failed with status code 404" - Stack Overflow

programmeradmin3浏览0评论

I'm working on a ChatGPT-like app using React and Axios for making API requests to OpenAI's Chat Completions API. However, I'm encountering a 404 error when trying to make a request. I'm hoping someone can help me identify the issue and guide me on how to fix it. Here's the App.js and index.js code and error message:

Frontend

App.js

function App() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");

  const sendMessage = async () => {
    if (input.trim() === "") return;
  
    const userInput = input; // Store user input in a temporary variable
    setMessages([...messages, { type: "user", text: userInput }]);
    setInput("");
  
    try {
      const response = await axios.post("http://localhost:5000/api/chat", { text: userInput });
      const gptResponse = response.data.message;
      setMessages((prevMessages) => [
        ...prevMessages,
        { type: "chatgpt", text: gptResponse },
      ]);
    } catch (error) {
      console.error("Error:", error);
    }
  };

Backend

index.js

const express = require("express");
const axios = require("axios");
const cors = require("cors");

const app = express();
app.use(express.json());
app.use(cors());

const openai_api_key = "MYOPENAI-APIKEY";
const headers = {
  "Content-Type": "application/json",
  "Authorization": `Bearer ${openai_api_key}`,
};

app.post("/api/chat", async (req, res) => {
  try {
    const input = req.body.text;
    const response = await axios.post(
      ";,
      {
        prompt: `User: ${input}\nChatGPT: `,
        max_tokens: 150,
        temperature: 0.7,
        n: 1,
      },
      { headers }
    );

    const gptResponse = response.data.choices[0].text.trim();
    res.json({ message: gptResponse });
  } catch (error) {
    console.error("Error:", error);
    res.status(500).json({ error: "An error occurred while processing your request." });
  }
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`);
});

Error message: AxiosError: Request failed with status code 404

I've verified that the API key is correct and the URL should be as well. Can anyone point me in the right direction for what's causing this error? Any help would be greatly appreciated. Thank you!

I'm working on a ChatGPT-like app using React and Axios for making API requests to OpenAI's Chat Completions API. However, I'm encountering a 404 error when trying to make a request. I'm hoping someone can help me identify the issue and guide me on how to fix it. Here's the App.js and index.js code and error message:

Frontend

App.js

function App() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");

  const sendMessage = async () => {
    if (input.trim() === "") return;
  
    const userInput = input; // Store user input in a temporary variable
    setMessages([...messages, { type: "user", text: userInput }]);
    setInput("");
  
    try {
      const response = await axios.post("http://localhost:5000/api/chat", { text: userInput });
      const gptResponse = response.data.message;
      setMessages((prevMessages) => [
        ...prevMessages,
        { type: "chatgpt", text: gptResponse },
      ]);
    } catch (error) {
      console.error("Error:", error);
    }
  };

Backend

index.js

const express = require("express");
const axios = require("axios");
const cors = require("cors");

const app = express();
app.use(express.json());
app.use(cors());

const openai_api_key = "MYOPENAI-APIKEY";
const headers = {
  "Content-Type": "application/json",
  "Authorization": `Bearer ${openai_api_key}`,
};

app.post("/api/chat", async (req, res) => {
  try {
    const input = req.body.text;
    const response = await axios.post(
      "https://api.openai./v1/engines/davinci-codex/pletions",
      {
        prompt: `User: ${input}\nChatGPT: `,
        max_tokens: 150,
        temperature: 0.7,
        n: 1,
      },
      { headers }
    );

    const gptResponse = response.data.choices[0].text.trim();
    res.json({ message: gptResponse });
  } catch (error) {
    console.error("Error:", error);
    res.status(500).json({ error: "An error occurred while processing your request." });
  }
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`);
});

Error message: AxiosError: Request failed with status code 404

I've verified that the API key is correct and the URL should be as well. Can anyone point me in the right direction for what's causing this error? Any help would be greatly appreciated. Thank you!

Share Improve this question edited Jun 12, 2024 at 17:07 Rok Benko 23.1k5 gold badges39 silver badges69 bronze badges asked Apr 1, 2023 at 22:39 babybirkinsbabybirkins 1352 gold badges3 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

There are three main differences between the Chat Completions API (i.e., the GPT-3.5 API) and the Completions API (i.e., the GPT-3 API).

If you're using OpenAI library (NodeJS or Python)

Note: OpenAI NodeJS SDK v4 was released on August 16, 2023, and is a plete rewrite of the SDK. The code below differs depending on the version you currently have. See the v3 to v4 migration guide.

The differences are the following:

  1. Function
    • Completions API:
      • OpenAI NodeJS SDK v3: openai.createCompletion
      • OpenAI NodeJS SDK v4: openai.pletions.create
    • Chat Completions API:
      • OpenAI NodeJS SDK v3: openai.createChatCompletion
      • OpenAI NodeJS SDK v4: openai.chat.pletions.create
  2. The prompt parameter (Completions API) is replaced by the messages parameter (Chat Completions API)
  3. Response access
    • Completions API:
      • OpenAI NodeJS SDK v3: return response.data.choices[0].text;
      • OpenAI NodeJS SDK v4: return response.choices[0].text;
    • Chat Completions API:
      • OpenAI NodeJS SDK v3: return response.data.choices[0].message.content;
      • OpenAI NodeJS SDK v4: return response.choices[0].message.content;

Working example (NodeJS)

• If you have the OpenAI NodeJS SDK v3:

const { Configuration, OpenAIApi } = require('openai');

const configuration = new Configuration({
  apiKey: 'sk-xxxxxxxxxxxxxxxxxxxx',
});

const openai = new OpenAIApi(configuration);

async function getChatGptResponse(request) {
  try {
    const response = await openai.createChatCompletion({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: 'Hello!' }],
    });

    console.log(response.data.choices[0].message.content);
    return response.data.choices[0].message.content;
  } catch (err) {
    console.log('Error: ' + err);
    return err;
  }
}

getChatGptResponse();

• If you have the OpenAI NodeJS SDK v4:

import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: 'sk-xxxxxxxxxxxxxxxxxxxx',
});

async function getChatGptResponse(request) {
  try {
    const response = await openai.chat.pletions.create({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: 'Hello!' }],
    });

    console.log(response.choices[0].message.content);
    return response.choices[0].message.content;
  } catch (err) {
    console.log('Error: ' + err);
    return err;
  }
}

getChatGptResponse();

If you're not using OpenAI library

The differences are the following:

  1. API endpoint
    • Completions API: https://api.openai./v1/pletions
    • Chat Completions API: https://api.openai./v1/chat/pletions
  2. The prompt parameter (Completions API) is replaced by the messages parameter (Chat Completions API)
  3. Response access
    • Completions API:
      • OpenAI NodeJS SDK v3:
        const chatGptResponse = response.data.choices[0].text;
      • OpenAI NodeJS SDK v4:
        const chatGptResponse = response.choices[0].text;
    • Chat Completions API:
      • OpenAI NodeJS SDK v3:
        const chatGptResponse = response.data.choices[0].message.content;
      • OpenAI NodeJS SDK v4:
        const chatGptResponse = response.choices[0].message.content;

Working example

• If you have the OpenAI NodeJS SDK v3:

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

const app = express();
app.use(express.json());
app.use(cors());

const openaiApiKey = 'sk-xxxxxxxxxxxxxxxxxxxx';

const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${openaiApiKey}`,
};

app.post('/api/chat', async (req, res) => {
  try {
    const input = req.body.text;

    const response = await axios.post(
      'https://api.openai./v1/chat/pletions',
      {
        model: 'gpt-3.5-turbo',
        messages: [{role: 'user', content: `${input}`}],
      },
      { headers }
    );

    const chatGptResponse = response.data.choices[0].message.content;

    console.log(chatGptResponse);
    res.status(200).json({ message: chatGptResponse });
  } catch (err) {
    console.log('Error: ' + err);
    res.status(500).json({ error: 'An error occurred while processing your request' });
  }
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`);
});

• If you have the OpenAI NodeJS SDK v4:

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

const app = express();
app.use(express.json());
app.use(cors());

const openaiApiKey = 'sk-xxxxxxxxxxxxxxxxxxxx';

const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${openaiApiKey}`,
};

app.post('/api/chat', async (req, res) => {
  try {
    const input = req.body.text;

    const response = await axios.post(
      'https://api.openai./v1/chat/pletions',
      {
        model: 'gpt-3.5-turbo',
        messages: [{role: 'user', content: `${input}`}],
      },
      { headers }
    );

    const chatGptResponse = response.choices[0].message.content;

    console.log(chatGptResponse);
    res.status(200).json({ message: chatGptResponse });
  } catch (err) {
    console.log('Error: ' + err);
    res.status(500).json({ error: 'An error occurred while processing your request' });
  }
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`);
});
发布评论

评论列表(0)

  1. 暂无评论