Skip to content

Commit

Permalink
Merge pull request #30 from openai/error-handling
Browse files Browse the repository at this point in the history
Add error handling logic
  • Loading branch information
schnerd authored Dec 24, 2022
2 parents 8082102 + 175c4df commit ca6492d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 16 deletions.
36 changes: 30 additions & 6 deletions pages/api/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,36 @@ const configuration = new Configuration({
const openai = new OpenAIApi(configuration);

export default async function (req, res) {
const completion = await openai.createCompletion({
model: "text-davinci-002",
prompt: generatePrompt(req.body.animal),
temperature: 0.6,
});
res.status(200).json({ result: completion.data.choices[0].text });
if (!configuration.apiKey) {
res.status(500).json({
error: {
message: "OpenAI API key not configured, please follow instructions in README.md",
}
});
return;
}

try {
const completion = await openai.createCompletion({
model: "text-davinci-002",
prompt: generatePrompt(req.body.animal),
temperature: 0.6,
});
res.status(200).json({ result: completion.data.choices[0].text });
} catch(error) {
// Consider adjusting the error handling logic for your use case
if (error.response) {
console.error(error.response.status, error.response.data);
res.status(error.response.status).json(error.response.data);
} else {
console.error(`Error with OpenAI API request: ${error.message}`);
res.status(500).json({
error: {
message: 'An error occurred during your request.',
}
});
}
}
}

function generatePrompt(animal) {
Expand Down
31 changes: 21 additions & 10 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,27 @@ export default function Home() {

async function onSubmit(event) {
event.preventDefault();
const response = await fetch("/api/generate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ animal: animalInput }),
});
const data = await response.json();
setResult(data.result);
setAnimalInput("");
try {
const response = await fetch("/api/generate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ animal: animalInput }),
});

const data = await response.json();
if (response.status !== 200) {
throw data.error || new Error(`Request failed with status ${response.status}`);
}

setResult(data.result);
setAnimalInput("");
} catch(error) {
// Consider implementing your own error handling logic here
console.error(error);
alert(error.message);
}
}

return (
Expand Down

0 comments on commit ca6492d

Please sign in to comment.