Explanation:
- Class Initialization: The GptApi class is created with a constructor to initialize the API key.
- Get Response: The getResponse method calls the private method chatWithGpt to get the response from the API.
- Chat with GPT: The chatWithGpt method sends a POST request to the ChatGPT API with the prompt and necessary headers using the Fetch API. It handles the response and errors gracefully.
- Error Handling: The code checks for fetch errors and API errors, providing appropriate messages.
How to Use:
- Replace 'Enter your OpenAI API key here' with your actual OpenAI API key.
- Replace 'Enter your prompt here' with your actual prompt.
- Run the script in a Node.js environment or in the browser to get the response from ChatGPT.
JavaScript:
class GptApi {
constructor(apiKey) {
this.apiKey = apiKey;
this.model = 'gpt-3.5-turbo';
}
async getResponse(prompt) {
const response = await this.chatWithGpt(prompt);
return response;
}
async chatWithGpt(prompt) {
const data = {
model: this.model,
messages: [
{ role: 'user', content: prompt }
],
max_tokens: 150, // You can optimize this value
temperature: 0.7,
top_p: 1,
n: 1,
stop: null
};
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.apiKey
};
const url = 'https://api.openai.com/v1/chat/completions';
try {
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(data)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`API error: ${errorData.error.message}`);
}
const responseData = await response.json();
return responseData.choices[0].message.content || 'No response';
} catch (error) {
return `Fetch error: ${error.message}`;
}
}
}
// Enter your API key here
const apiKey = 'Enter your OpenAI API key here';
const prompt = 'Enter your prompt here';
const gptApi = new GptApi(apiKey);
gptApi.getResponse(prompt).then(response => {
console.log(response);
});