Error 400 when using GPT API (in JavaScript) - javascript

I keep getting a 400 Error when I try to run my very basic chatbot using the GPT API:
error
Attached is my code; am I doing something wrong with the API key?
const chatHistoryContent = document.querySelector("#chat-history-content");
const chatMessageInput = document.querySelector("#chat-message-input");
const chatMessageSubmit = document.querySelector("#chat-message-submit");
chatMessageSubmit.addEventListener("click", async function () {
const message = chatMessageInput.value;
chatMessageInput.value = "";
// Add the user's message to the chat history
const userMessageDiv = document.createElement("div");
userMessageDiv.innerHTML = `You: ${message}`;
chatHistoryContent.appendChild(userMessageDiv);
// Use the OpenAI GPT-3 API to get a response from the chatbot
const response = await getResponseFromAPI(message);
// Add the chatbot's response to the chat history
const chatbotMessageDiv = document.createElement("div");
chatbotMessageDiv.innerHTML = `Max: ${response}`;
chatHistoryContent.appendChild(chatbotMessageDiv);
});
async function getResponseFromAPI(message) {
const apiKey = "sk-myapikey";
const endpoint = `https://api.openai.com/v1/engines/davinci/jobs`;
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": `application/json`,
"Authorization": `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "text-davinci-003",
prompt: "test prompt",
temperature: 0.5,
max_tokens: 512,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
})
});
const data = await response.json();
return data.choices[0].text;
}
Thanks
I have tried consulting many websites to see solutions to this but have had no luck.

400 (Bad Request) error code typically means that client request's data is incorrect. So yes, must be something with your auth headers/body of request. Quite often response contains a reason, please try to print the text of response (before trying to get json output), e.g.
console.log(response.text());
or just check Network Tab in Dev Console

You are almost there, you just have the wrong endpoint. If you change that your code will work.
The correct endpoint:
https://api.openai.com/v1/completions
I tested it with your code and it worked. Here is your code rewritten with the correct endpoint.
async function getResponseFromAPI(message) {
const apiKey = "sk-myapikey";
const endpoint = `https://api.openai.com/v1/completions`;
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": `application/json`,
"Authorization": `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "text-davinci-003",
prompt: "test prompt",
temperature: 0.5,
max_tokens: 512,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
})
});
const data = await response.json();
return data.choices[0].text;
}
Source: https://platform.openai.com/docs/api-reference/completions/create

Related

Fetch - get HTML text as a response

I have a problem. I have rate-limit that returns HTML:
const Limiter = rateLimit({
windowMs: 5 * 60 * 1000,
message: "Too many requests created from this IP, please try again later.",
max: 10
})
And I have fetch request in Client side that gets that Message:
const body = { email, password }
const res = await fetch("http://localhost:5000/api/auth/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(body)
})
const parseRes = await res.json()
if(parseRes.JwtToken) {
localStorage.setItem("JwtToken", parseRes.JwtToken)
setAuth(true)
toast.success("Login successfuly")
} else {
setAuth(false)
toast.error(parseRes)
}
My problem here is that when I get json object back it displays on the screen. But when I get that message object it does nothing. It just shows that failure 429 in the console. My question here is how can I get/display that HTML that returns normally like I would get an JSON object.
So before you parse the JSON check the status
if (!res.ok) {
/* handle the error */
return;
}
const parseRes = await res.json()

Error while sending a request to fluxpoint api

it's me again... Sorry for asking so many times a day, but I'm really an idiot.
So basically I'm trying to send a request to the fluxpoint api by using this code:
async welcome(username, avatarurl, background, membercount, icon, backgroundname, filename){
let req = {}
req.username = username;
req.avatar = avatarurl;
if (background == null) {req.background = "#aaaaaa"} else {req.background = background}
if (membercount) req.members = "Member #"+membercount
if (icon) req.icon = icon
if (backgroundname) req.banner = backgroundname
console.log(req)
let usedClient = axios.create({
baseURL: apiUrls[0],
timeout: 5000,
headers: {
'Authorization': this.token,
'Content-Length': 0,
'Content-Type': 'application/json'
},
data: JSON.parse(req),
responseType: 'arraybuffer'
})
console.log(usedClient)
console.log(apiUrls[0]+api1endpoints[1])
let res = await usedClient.get(api1endpoints[1])
return res
}
Here is the code I'm using for testing it:
const fluxpoint = require('./index')
const Client = new fluxpoint.Client("my fluxpoint token")
async function tt(){
let t = await Client.welcome("Koro~ (Baka)#7963", "https://cdn.discordapp.com/avatars/304541381798658048/36806f6ae648b9ebc8303443b0be101c.png", "#FFFFFF", 1, "neko", "space")
console.log(t)
}
tt()
And, here is the error the fluxpoint api sends me:
Failed to parse json, The input does not contain any JSON tokens. Excepted the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
I tried everything, but JSON.parse(my data) sends me Unexcepted token o in JSON at position 1
I'm being desesperate and I hope somebody can help me!
It seems you are parsing the raw json.It throws an error
JSON.parse takes string as parameter.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
And from official doc you cannot use data in get request.
https://github.com/axios/axios#request-config
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
}
So try passing the data
let res = await usedClient.get(api1endpoints[1],{
params: {
data: res
}
})
I've tested the endpoint it works only if responseType is 'text' or 'stream'

SyntaxError: Unexpected token r in JSON at position 0 on reactjs login page

I have been trying to make a login page in reactjs but it's throwing me an error in console like
SyntaxError: Unexpected token r in JSON at position 0 but I got 200 status code in network tab and also I'm getting "redirect" in both response and preview tab under the network tab.
I tried the same code(except it was if(response.ok) this time) with another server of my friend and it successfully redirects it to another page
This is the code that I've been trying: is response.data not correct for reactjs?
performLogin = async () => {
var body = {
password: this.state.password,
email: this.state.email
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/authenticate";
try {
const response = await fetch(url, options);
const result = await response.json();
console.log(response); //nothing is showing in console for this statement
if (response.data == "redirect") {
this.props.history.push(`/verifyOtp/${this.state.email}`);
} else {
console.log("login failed");
window.alert("login failed");
}
} catch (error) {
console.error(error);
}
};
edit: I also tried it in postman and it gives "redirect" as response in postman so the api must be working fine
Your problem is in this line
const result = await response.json();
Your response is ok, everything is ok, but when you try to do response.json() and the response from the request isn't a valid json (maybe just a normal text), it will give you that error.
Because response can be a text or a json, you need to do some checking. Where is how to check if response is a json
This is kind of bad because on every request you will need to do this type of checking (transform it to text, try to parse, bla bla...), so What I recommend it you to use something better than fetch.
Axios is very good because it already do that checking.
For your example:
performLogin = async () => {
var body = {
password: this.state.password,
email: this.state.email
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/authenticate";
try {
const response = await fetch(url, options); // Fetch the resource
const text = await response.text(); // Parse it as text
const data = JSON.parse(text); // Try to parse it as json
// Do your JSON handling here
} catch(err) {
// This probably means your response is text, do you text handling here
}
}

I'm trying to send JavaScript data to my NodeJS server

So I'm trying to send geolocation data to NodeJS via a POST request but when I console log the data in my NodeJS code it just shows an empty object.
I tested it already with postman and I can receive the data without a problem. I think the problem resides in the client side of my app
//**This is in the client Side(pure JS);
async function getWeather(position){
let coords ={
lat: position.coords.latitude,
long: position.coords.longitude
}
const options = {
method: "POST",
body: JSON.stringify(coords),
headers: {
"Content-Type": "aplication/json"
}
};
let response = await fetch("http://localhost:3000/weather", options);
let location = await response.json();
}
.
//**This is in the server side
app.post('/weather',(req,res)=>{
let coords = req.body;
console.log(coords); //This shows an empty object
res.sendStatus(200);
});
On your client side you can try this code. You can replace the url with your endpoint and try to fetch the result. As shown below, I'm getting the response back in data after executing the script.
I hope this helps.
(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({lat: 10, long: 20})
});
const content = await rawResponse.json();
console.log(content);
})();

coinmarketcap api integration - 401 error - JavaScript

I am trying to integrate coinmarketcap api but cannot really get the data. I registered, got the API key, and wrote the following method to fetch the data:
let getPostsList = async () => {
const options = {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': 'api-key-goes-here'
},
mode: 'no-cors'
};
try {
const response = await fetch(`https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest`, options);
const json = await response.body;
// console.log(json)
return json
} catch (err) {
console.log('Error: ', err)
}
};
All I get is 401 error, like this:
GET https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest
401
Any suggestions what I should fix? Docs says that 401 is likely connected to API key, but they say to provide it in the headers like the above...
From what I've tested after getting my own API key, the no-cors mode is problematic. You will need to use CORS, where https://cors-anywhere.herokuapp.com/ comes into handy.
Just send the request like this :
const options = {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': 'api-key-goes-here'
},
};
try {
const response = await fetch(`https://cors-anywhere.herokuapp.com/https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest`, options);

Categories

Resources