OpenAI is a powerful artificial intelligence platform that allows developers to create intelligent applications. Next.js is a popular React framework that provides server-side rendering and other advanced features. In this blog, I will create a simple Q&A app using OpenAI and Next.js.
OpenAI's text completion API uses AI to generate human-like text based on a given prompt, making it a powerful tool for tasks like generating creative writing, building chatbots, and creating language models. Its advanced language processing and vast data resources enable it to produce text that closely resembles human writing, making it a valuable resource for businesses and developers.
Prerequisites
Before you begin, you should have a basic understanding of React and Next.js. You should also have an OpenAI API key. If you don't have an OpenAI API key, you can sign up for a free account on their website.
I will only be using TypeScript and TailwindCSS for this project, but you can use JavaScript and any CSS framework you prefer.
Never commit your API key to your repository. You can .env out of the box to store your API key.
Create a NextJS API handler
We only need the API to handle POST requests, so we can return an error if the request method is not POST.
We can use the OpenAI client to create a completion using the createCompletion method. We can set the prompt to the question, and the model to text-davinci-003. The temperature and max_tokens can be adjusted to get different results. We can set the n to 1 to only get one result(also to save some money).
Run the application using yarn dev. Test the newly created endpoint using curl, Postman, Hoppscotch, or whatever you prefer.
We should see the response data from OpenAI.
Update the API response
Since we don't need the entire response from OpenAI, we can simplify the response to only return the data we need. Because we set the number of results to only one using n: 1, we can simplify the response to only extract the first choice.
Also, we can remove the new lines from the beginning of the response using the replace method.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import{useState}from'react';constIndexPage=()=>{const[prompt, setPrompt]=useState('');const[response, setResponse]=useState('');consthandleSubmit=async e =>{ e.preventDefault();const res =awaitfetch('/api/completion',{ method:'POST', headers:{'Content-Type':'application/json',}, body:JSON.stringify({prompt: prompt.trim()}),}).then(res => res.json());setResponse(res.data.text);};return(<divclassName="max-w-md mx-auto pt-20"><h1className="text-3xl font-bold text-center mb-6 bg-white">Ask Me Anything!</h1><formonSubmit={handleSubmit}className="bg-white shadow-md rounded p-8"><divclassName="mb-4"><labelhtmlFor="prompt"className="block text-gray-700 text-sm font-bold mb-2"> What do you want to know?</label><inputid="prompt"type="text"name="prompt"value={prompt}autoComplete="off"onChange={e =>setPrompt(e.target.value)}placeholder="How to ask a question?"className="shadow border rounded w-full py-2 px-3 text-gray-700"/></div>{response &&(<divclassName="mb-4"><h2className="font-bold">Response</h2><pclassName="pl-2 text-gray-700 whitespace-pre-line">{response}</p></div>)}<divclassName="flex gap-2"><buttontype="submit"className="bg-blue-500 text-white font-bold py-2 px-4 rounded"> Ask</button></div></form></div>);};exportdefaultIndexPage;
Here is how the markup looks like:
And here is the output when the user submits the form:
Tip: You can use the tailwind whitespace-pre-line OR vanilla CSS white-space: pre-line; style to preserve the new lines in the response.
Improve the UX a little bit
We can add a loading state to the button and disable the input field while the request is being processed. Also, instead of spamming the Ask button, we can add a Try Again button to reset the form. That way we can save some of our precious OpenAI credits.
src/pages/index.tsx
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import{useState}from'react';constIndexPage=()=>{const[response, setResponse]=useState('');const[prompt, setPrompt]=useState('');const[loading, setLoading]=useState(false);consthandleSubmit=async e =>{ e.preventDefault();setLoading(true);setResponse('');const res =awaitfetch('/api/completion',{ method:'POST', headers:{'Content-Type':'application/json',}, body:JSON.stringify({prompt: prompt.trim()}),}).then(res => res.json());setResponse(res.data.text);setLoading(false);};consthandleTryAgain=()=>{setResponse('');setPrompt('');};return(<divclassName="max-w-md mx-auto pt-20"><h1className="text-3xl font-bold text-center mb-6 bg-white"> Ask Me Anything!</h1><formonSubmit={handleSubmit}className="bg-white shadow-md rounded p-8"><divclassName="mb-4"><labelclassName="block text-gray-700 text-sm font-bold mb-2"htmlFor="prompt"> What do you want to know?</label><inputid="prompt"type="text"name="prompt"value={prompt}onChange={e =>setPrompt(e.target.value)}placeholder="How to ask a question?"autoComplete="off"disabled={!!response || loading}className="shadow border rounded w-full py-2 px-3 text-gray-700"/></div>{response &&(<divclassName="mb-4"><h2className="font-bold">Response</h2><pclassName="pl-2 text-gray-700 whitespace-pre-line">{response}</p></div>)}<divclassName="flex gap-2">{response ?(<buttononClick={handleTryAgain}className="bg-blue-500 text-white font-bold py-2 px-4 rounded"> Try again</button>):(<buttontype="submit"disabled={!!loading || prompt.length<5}className="bg-blue-500 text-white font-bold py-2 px-4 rounded disabled:opacity-50">{loading ?'Thinking...':'Ask'}</button>)}</div></form></div>);};exportdefaultIndexPage;
And here is a slightly better experience:
Source Code
The source code for this project is available on GitHub
Conclusion
In this blog post, I demonstrated how simple it is to use OpenAI text completion with Next.js. We have seen how to create an API route in Next.js, how to make an API request to the OpenAI API using the openai library, and create a client-side form to accept prompts and display the response from the API. And those three steps are all we need to create a more awesome app.