Skip to content

Instantly share code, notes, and snippets.

@vukhanhtruong
Last active March 13, 2023 11:09
Show Gist options
  • Save vukhanhtruong/cc715e2b5150898c7f49e593b6a99492 to your computer and use it in GitHub Desktop.
Save vukhanhtruong/cc715e2b5150898c7f49e593b6a99492 to your computer and use it in GitHub Desktop.
Fetch OpenAI API code snippet in JS
try {
const GPT_KEY = process.env.CHATGPT_API_KEY;
const headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${GPT_KEY}`,
};
const prompt = req.query.text;
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers,
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [
{
role: 'user',
content: prompt,
},
],
temperature: 0,
max_tokens: 550,
}),
});
console.log(`${prompt}`);
const { choices } = await response.json();
const [message] = choices;
const text =
prompt + message.message.content.replace(/(?:\r\n|\r|\n)/g, '
');
return text;
} catch (error) {
throw new Error(error.message);
}
try {
const GPT_KEY = process.env.CHATGPT_API_KEY;
const headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${GPT_KEY}`,
};
const prompt = req.query.text;
const response = await fetch('https://api.openai.com/v1/completions', {
method: 'POST',
headers,
body: JSON.stringify({
model: 'text-davinci-003',
prompt: prompt,
temperature: 0,
max_tokens: 550,
}),
});
const reply = await response.json();
const choice = reply.choices[0].text;
const text = prompt + choice.replace(/(?:\r\n|\r|\n)/g, '
');
return text;
} catch (error) {
throw new Error(error.message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment