admin管理员组文章数量:1315286
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 badges1 Answer
Reset to default 6There 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:
- Function
- Completions API:
- OpenAI NodeJS SDK
v3
:openai.createCompletion
- OpenAI NodeJS SDK
v4
:openai.pletions.create
- OpenAI NodeJS SDK
- Chat Completions API:
- OpenAI NodeJS SDK
v3
:openai.createChatCompletion
- OpenAI NodeJS SDK
v4
:openai.chat.pletions.create
- OpenAI NodeJS SDK
- Completions API:
- The
prompt
parameter (Completions API) is replaced by themessages
parameter (Chat Completions API) - Response access
- Completions API:
- OpenAI NodeJS SDK
v3
:return response.data.choices[0].text;
- OpenAI NodeJS SDK
v4
:return response.choices[0].text;
- OpenAI NodeJS SDK
- Chat Completions API:
- OpenAI NodeJS SDK
v3
:return response.data.choices[0].message.content;
- OpenAI NodeJS SDK
v4
:return response.choices[0].message.content;
- OpenAI NodeJS SDK
- Completions API:
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:
- API endpoint
- Completions API:
https://api.openai./v1/pletions
- Chat Completions API:
https://api.openai./v1/chat/pletions
- Completions API:
- The
prompt
parameter (Completions API) is replaced by themessages
parameter (Chat Completions API) - 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;
- OpenAI NodeJS SDK
- 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;
- OpenAI NodeJS SDK
- Completions API:
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}`);
});
版权声明:本文标题:javascript - OpenAI Chat Completions API error: "Request failed with status code 404" - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741978873a2408280.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论