Yes. See below:
Code for connecting the API -
const OpenAI = require("openai-api");
const openai = new OpenAI(process.env.OPENAI_API_KEY);
export default async (req, res) => {
// Promt values
const beforePromt = ``;
const afterPromt = ``;
const breakPoint = `\n\n'''\n\n`;
// Construct the prompt
// let prompt = `${beforePromt} ${breakPoint} ${req.body.name} ${breakPoint} ${afterPromt}`;
let prompt = `Generate blog ideas: ${req.body.name}`;
// Log promt
console.log(prompt);
// Call OpenAI API
const gptResponse = await openai.complete({
engine: "text-davinci-002",
prompt: `${prompt}`,
maxTokens: 1500,
temperature: 0.7,
topP: 1,
presencePenalty: 0,
frequencyPenalty: 0.5,
bestOf: 1,
n: 1,
});
res.status(200).json({ text: `${gptResponse.data.choices[0].text}` });
};
Code for Connecting API to frontend -
import Head from "next/head";
import styles from "../styles/Home.module.css";
import { useState, useEffect } from "react";
export default function Home() {
// React Hooks
const [data, setData] = useState({ text: "" });
const [query, setQuery] = useState();
const [search, setSearch] = useState();
const [isLoading, setIsLoading] = useState(false);
// Fetch data from API
useEffect(() => {
const fetchData = async () => {
if (search) {
setIsLoading(true);
const res = await fetch(`/api/openai`, {
body: JSON.stringify({
name: search,
}),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
const data = await res.json();
setData(data);
setIsLoading(false);
}
};
fetchData();
}, [search]);
// What we want to render
return (
<>
<div className={styles.generateIdeasWrapper}>
<form className={styles.generateIdeasForm}>
<input
className={styles.generateIdeasInput}
type="text"
name="idea"
placeholder="Type any idea"
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
</form>
<button
onClick={() => setSearch(query)}
className={styles.generateIdeasButton}
>
Generate Ideayaz
</button>
<div className={styles.dataContainer}>
{isLoading ? <div>Loading...</div> : <span>{data.text}</span>}
</div>
</div>
</>
);
}
**The two errors that I am seeing -**
Failed to load resource: the server responded with a status of 500 ()
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
That JSON error usually means you’re receiving unexpected or blank input. It looks like this is happening when you’re using JSON.stringify
Try creating a variable and setting it equal to the same key value pair: ({name: search,}) Then JSON.stringify the variable.
@josephfrusetta ok got it in regards to the JSON.stringify. what about the 500 error? Could it be because Openai has an app review process. The reason I believe this is the case is because the app works for me locally, it’s just when I try and use the deployed site, it crashes.
It’s unlikely that the 500 error is on OpenAI’s end. Their status page shows no issues at the moment. This means there’s something amiss with your implementation.
Let’s take a look at Steve T’s Content Filtering code. He uses JSON.stringify on a parameter variable before passing it. If that doesn’t resolve the issue, try adding an Authorization header like the one Steve T has implemented.
1 Like
Hmmm. One question in regards to that - what if it works locally, just not on the deployed site? Because that is the case. It runs without issue locally however when I try to run the app on the deployed site, the error occurs.
Here’s a link to the deployed site if you would like to test it and check the error - https://ideayaz.vercel.app/
1 Like
I have had a lot of luck putting the error throwing code, and the development environment into ‘edit’ codex. I put the error stack and directions to fix the error in the directions prompt.
This works really well
@jhsmith12345 thank you. can you link me to codex so that I can try this out.
It is in beta right now, so you will need to get on the waiting list. I was accepted in a day or two, so shouldn’t be a long wait. It is somewhere on the open AI website, I’m sure you can find it 
I found it. Going to see if I can get access to the beta. Thank you
1 Like
There can be lots of reasons why errors would only appear in prod and not local e.g. the environment variables are not the same, or the references are not up to date. Troubleshooting the errors further will help determine why they are present only present in production.
I don’t think waiting for Codex is the best way to address these errors. I just tried running the code/error through Codex without any luck.
Have you tried using JSON.stringify on a variable with the same string? Did adding the Authorization header help?
@josephfrusetta I think I’m going to try and rebuild the entire thing. Maybe in a different language. There are a few tutorials that I’m looking to follow.
Can I follow up with you on this in the event that I do a rebuild and the problem persists?
Sure thing. Just reach out in this thread and I’ll see what I can do.
1 Like
@josephfrusetta have you ever seen this error? When typing something into the input that I built, this error shows up. I seemed to have it fixed for a while but it randomly showed up again and it persists. I believe that the API call is hitting HTML instead of JSON but I am not sure. Any thoughts? GitHub - OrlundoHubbard/open_ai_playground - here is a link to the repo also if you want to take a look.
I haven’t, but in the error we see <!DOCTYPE> which is the start of an HTML page, not valid JSON.
Find the place in your code that is expecting JSON, but receiving HTML. That should point to the cause.
Hello mate, was wondering if you later found a solution to this.
If you check the API docs, you will see that there is no engine parameter for the completion API endpoint. The required parameter is model (not engine).
Therefore it is not likely (nor possible) your API call will succeed until you correct this API param error.
Hope this helps.
See Also:
OpenAI API: Completions
Oh wow. Thank you so much I’m going to try this out.
I might have. Are you facing the same issue?
Yeah… but I am a complete novice.
I used Chatgpt to create the script for a WordPress site.
Not until I read this thread did I discover that I would have to connect the script to openAI API so it can output ideas in real time.
Would appreciate if you can help out with this.
Ok. I can try and help. Can you send me your code?