Skip to content
Dashboard

Building a GPT-3 app with Next.js and streaming (historical)

Senior Developer Advocate

A full-stack template for building fast GPT-3 apps.

Copy link to headingThe frontend

const prompt = `Generate 2 ${vibe} twitter bios with no hashtags and clearly labeled "1."
and "2.". Make sure each generated bio is at least 14 words and at max 20 words and base
them on this context: ${bio}`;

GenerateBio.tsx
<textarea
value={bio}
onChange={(e) => setBio(e.target.value)}
rows={4}
className="..."
placeholder={"e.g. Senior Engineer @vercel. Tweeting about web dev & AI."}
/>
<div className="...">
<Image src="/2-black.png" width={30} height={30} alt="1 icon" />
<p className="...">Select your vibe.</p>
</div>
<div className="block">
<DropDown vibe={vibe} setVibe={(newVibe) => setVibe(newVibe)} />
</div>
<button className="..." onClick={(e) => generateBio(e)}>
Generate your bio &rarr;
</button>
<hr className="..." />
<div className="...">
{generatedBios && (
<>
<div>
<h2 className="...">Your generated bios</h2>
</div>
<div className="...">
{generatedBios
.substring(generatedBios.indexOf("1") + 3)
.split("2.")
.map((generatedBio: any) => {
return (
<div className="..." key={generatedBio}>
<p>{generatedBio}</p>
</div>
);
})}
</div>
</>
)}
</div>

GenerateBio.tsx
const generateBio = async (e: any) => {
e.preventDefault();
setGeneratedBios("");
setLoading(true);
const response = await fetch("/api/generate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
prompt,
}),
});
if (!response.ok) {
throw new Error(response.statusText);
}
let answer = await response.json();
setGeneratedBios(answer.choices[0].text);
setLoading(false);
};

Copy link to headingThe backend

generate.js
export default async function handler(req, res) {
const { prompt } = req.body;
const payload = {
model: "text-davinci-003",
prompt,
temperature: 0.7,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
max_tokens: 200,
n: 1,
};
const response = await fetch("https://api.openai.com/v1/completions", {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY ?? ""}`,
},
method: "POST",
body: JSON.stringify(payload),
});
const json = await response.json();
res.status(200).json(json);
}

Copy link to headingCurrent guidance: use Vercel Functions with streaming

Copy link to headingResources

Ready to deploy?