gpt

<script>
document.addEventListener("DOMContentLoaded", function () {
    // Get elements by their IDs
    const chatInput = document.getElementById("chatInput");
    const chatSubmitButton = document.getElementById("chatSubmitButton");
    const chatOutput = document.getElementById("chatOutput");

    // Event listener for the submit button
    chatSubmitButton.addEventListener("click", async function (e) {
        e.preventDefault(); // Prevent the form from reloading the page

        const userInput = chatInput.value; // Get the user input
        if (userInput) {
            const apiKey = "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"; // Replace with your OpenAI API key
            const apiUrl = "https://api.openai.com/v1/completions"; // Correct API endpoint for completions

            try {
                const response = await fetch(apiUrl, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "Authorization": `Bearer ${apiKey}`
                    },
                    body: JSON.stringify({
                        model: "gpt-3.5-turbo", // Choose the correct model
                        messages: [{ role: "user", content: userInput }]
                    })
                });

                const data = await response.json();
                if (data && data.choices && data.choices.length > 0) {
                    chatOutput.innerHTML = `<p>${data.choices[0].message.content}</p>`;
                } else {
                    chatOutput.innerHTML = "<p>Sorry, no response from the API.</p>";
                }
            } catch (error) {
                console.error("Error with API request:", error);
                chatOutput.innerHTML = "<p>There was an error processing your request.</p>";
            }
        } else {
            chatOutput.innerHTML = "<p>Please enter a query.</p>";
        }
    });
});
</script>