Hi, im trying to integrate chatgpt into my html js program, however I don’t want to use node.js or any server side sort of thing. This is my code that I’m testing does anyone know why its not working? I’ve replaced my API key with “xxxx”. Thanks
ChatGPT API ExampleChat with ChatGPT
Send<script>
const apiKey = 'sk-proj-xxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // Replace this with your actual API key
async function sendMessage() {
const userInput = document.getElementById('userInput').value;
const outputDiv = document.getElementById('output');
outputDiv.textContent = "Processing...";
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}` // Insert API Key correctly here
},
body: JSON.stringify({
model: 'gpt-3.5-turbo', // Ensure you're using the correct model
messages: [{ role: 'user', content: userInput }],
temperature: 0.7
})
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
outputDiv.textContent = data.choices[0].message.content;
} catch (error) {
outputDiv.textContent = `Error: ${error.message}`;
}
}
</script>