How to generate output based on user input

Hey all,

I have an idea for an app where the user will input a category for a business idea and based on what the user input was, the interface will spit out a list of business ideas for that category.

(e.g. user enters category: VR, interface response: <3 ideas for VR>)

I’m programming in javascript, so any suggestions using this language would be helpful.

Hi Orlundo,

I would start by interacting with OpenAI’s API and then work towards building an app. Here’s a video tutorial that shows you how to get started using node.js. When you start building your app, OpenAI’s API documentation can be helpful.

If you find that you’re not moving quickly enough in JavaScript, you might consider using a no code solution like Bubble.io. Here’s a video showing a similar solution being built using their platform.

Thanks @josephfrusetta I’ll check out those resources. I actually got it figured out!

I do have another question though - I’m getting a 500 error to my deployed site through vercel. It’s to my understanding that 500 errors are due to server errors (so, essentially on openai’s side). Are you familiar with solutions to this?

A 500 error means something went wrong on the server’s side. It could be that there’s a temporary issue on OpenAI’s end. But if your app hasn’t worked just yet, it likely means that there’s an error in the code. You might be setting the url variable to the wrong string, or making some other small mistake.

Are you able to post the code?

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.

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/

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 :slightly_smiling_face:

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.