Skip to content

Commit

Permalink
added pages/api/open-ai.tsx
Browse files Browse the repository at this point in the history
  • Loading branch information
nheek committed Jan 28, 2024
1 parent d504e7d commit 434cfb5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,6 @@ dist
.pnp.*

# custom
pages/api
.DS_Store
.htaccess

Expand Down
39 changes: 39 additions & 0 deletions pages/api/open-ai.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const fetchChatGPT = async (messages) => {
try {
// Retrieve the OpenAI API key from environment variables
const apiKey = process.env.NEXT_PUBLIC_OPEN_AI_API_KEY;

// Set the API URL for the Chat API
const apiUrl = 'https://api.openai.com/v1/chat/completions';

// Make a POST request to the OpenAI API with the provided messages
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
'OpenAI-Beta': 'assistants=v1',
},
body: JSON.stringify({
model: 'gpt-3.5-turbo-1106',
messages,
}),
});

// Check if the API request was successful
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}

// Parse the response JSON and extract the generated content
const data = await response.json();
return { role: 'system', content: data.choices[0].message.content.trim()};
} catch (error) {
// Handle any errors that occur during the API request
console.error('Error fetching from ChatGPT API:', error);
return null;
}
};

// Export the function for use in other parts of the application
export default fetchChatGPT;

0 comments on commit 434cfb5

Please sign in to comment.