Skip to content

Instantly share code, notes, and snippets.

@designly1
Created January 6, 2023 04:30
Show Gist options
  • Save designly1/6bf9a48aa05a8273b36577090f38118a to your computer and use it in GitHub Desktop.
Save designly1/6bf9a48aa05a8273b36577090f38118a to your computer and use it in GitHub Desktop.
import { Configuration, OpenAIApi } from "openai";
import NextCors from 'nextjs-cors';
const configuration = new Configuration({
apiKey: process.env.NEXT_PUBLIC_OPENAI_KEY,
});
const openai = new OpenAIApi(configuration);
export default async function handler(req, res) {
// Create our CORS policy to allow remote hosts
await NextCors(req, res, {
methods: ['POST', 'HEAD'],
origin: '*',
optionsSuccessStatus: 200,
});
// Destruct request body
const { prompt, token } = req.body;
// Validate our API token from Twilio
if (token !== process.env.NEXT_PUBLIC_API_KEY) {
res.status(403).send("HTTP 403 / Unauthorized");
return;
}
// Make our API request to ChatGPT and send the result to Twilio
try {
const completion = await openai.createCompletion({
model: "text-davinci-003", // ChatGPT latest version
prompt: prompt,
max_tokens: 2048 // Max length of response (2048 is highest)
});
const result = completion?.data?.choices[0]?.text;
if (result) {
res.status(200).json({ result: result });
} else {
const error = completion?.data?.error;
console.log(error);
res.status(200).json({ result: "I'm sorry, an error occurred." });
}
} catch (e) {
console.log(e)
res.status(200).json({ result: "I'm sorry, an error occured." });
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment