Task: Create a simple web application that integrates a chatbot using a language model API.
Requirements:
- Frontend:
- Design a simple chat interface using HTML, CSS, and JavaScript
- Implement a text input field for user messages
- Display chat history (bot and user messages)
- Backend:
- Set up a basic server using Node.js and Express.js
- Implement an API endpoint to handle user messages
- AI Integration:
- Integrate a language model API (e.g., OpenAI’s GPT-3.5 or a similar service)
- Send user messages to the language model and receive responses
- Database:
- Store chat history in a simple database (e.g., MongoDB or postgre )
- Deployment:
- Deploy the application to a free hosting service (e.g., Heroku or Vercel)
This is my task i did all the frontend part and this is the output i got for frontendfrontend output
and when i add api key from openai and when i run on the node js server i’m not getting the response This is the error i,m getting
give me the solution how will i rectify this error and get the correct output like how chatgpt works in that way i want my chatbot to work.
[this is my server.js code]:
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const app = express();
const port = 3000; // You can change this port if needed
app.use(cors()); // To allow cross-origin requests from your client
app.use(bodyParser.json());
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
// Define your chat API endpoint
app.post('/api/chat', async (req, res) => {
const { message } = req.body;
const apiUrl = "https://api.openai.com/v1/chat/completions";
const apiKey = "sk-None-60qqAyJu0nEC1Ux7hB4MT3BlbkFJR6VwhrQJS5mwENY8qnLc"; // Replace with your actual OpenAI API key
const data = {
"model": "gpt-3.5-turbo",
"messages": [
{ "role": "system", "content": "Welcome to Curious Advisor! How can I assist you today?" },
{ "role": "user", "content": message }
]
};
try {
const response = await axios.post(apiUrl, data, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
}
});
if (response.data && response.data.choices && response.data.choices.length > 0) {
res.json({ response: response.data.choices[0].message.content });
} else {
res.status(500).json({ error: 'No response from OpenAI API' });
}
} catch (error) {
console.error(error);
res.status(500).json({ error: 'An error occurred while sending the chat message.' });
}
});
// Serve index.html for the root route
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
[This is my chatbot.js file]
document.addEventListener("DOMContentLoaded", function (e) {
let chatbotName = "";
let chatLog = document.getElementById("chat-log");
let scrollPosition = 0;
let sendBtn = document.getElementById("send-btn");
let userInput = document.querySelector(".user-input");
const serverUrl = "http://localhost:3000/api/chat"; // Update to your server URL if different
function showWelcomeMessage(chatName) {
const welcomeMessage = document.getElementById("welcome-message");
welcomeMessage.textContent = `Welcome to ${chatName}! How can I assist you today?`;
}
function generateChatbotName() {
const adjectives = ["Amazing", "Brilliant", "Creative", "Dynamic", "Energetic"];
const nouns = ["Bot", "Assistant", "Companion", "Guide", "Helper"];
const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
return `${randomAdjective} ${randomNoun}`;
}
function setChatBotName() {
chatbotName = generateChatbotName();
document.querySelector(".chatbot-name").textContent = chatbotName;
document.title = chatbotName;
showWelcomeMessage(chatbotName);
}
setChatBotName();
function processSpecialCommand(command) {
if (command === "/help") {
displayMessage("sent", "You can ask questions or seek assistance. How may I help you?");
} else if (command === "/about") {
displayMessage("sent", "I am a chatbot designed to assist you. Feel free to ask me anything!");
} else {
displayMessage("sent", "I'm sorry, I don't understand that command. Type /help for assistance.");
}
}
sendBtn.addEventListener("click", async function () {
let userMessage = userInput.value.trim();
if (userMessage !== "") {
if (!checkInternetConnection()) {
displayMessage("error", "Sorry, you're offline. Please check your internet connection.");
return;
} else {
if (userMessage.startsWith("/")) {
const command = userMessage.toLowerCase();
processSpecialCommand(command);
} else {
try {
displayMessage("sent", userMessage);
let response = await sendChatMessage(userMessage);
if (response) {
displayMessage("received", response.response);
scrollChatLog();
}
} catch (error) {
console.error(error);
displayMessage("error", "Error: Failed to fetch response from the server.");
}
userInput.value = "";
}
}
}
});
async function sendChatMessage(message) {
showLoadingIndicator();
try {
let response = await fetch(serverUrl, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ message })
});
hideLoadingIndicator();
if (!response.ok) {
throw new Error("An error occurred while sending the chat message.");
}
let responseData = await response.json();
return responseData;
} catch (error) {
hideLoadingIndicator();
console.error(error);
throw error;
}
}
function displayMessage(type, message) {
let messageContainer = document.createElement("div");
messageContainer.classList.add("message", type);
let messageText = document.createElement("p");
messageText.textContent = message;
messageContainer.appendChild(messageText);
chatLog.appendChild(messageContainer);
chatLog.scrollTop = chatLog.scrollHeight;
}
function checkInternetConnection() {
return navigator.onLine;
}
function showLoadingIndicator() {
document.getElementById("loading-indicator").style.display = "flex";
}
function hideLoadingIndicator() {
document.getElementById("loading-indicator").style.display = "none";
}
function scrollChatLog() {
let isScrolledToBottom = chatLog.scrollHeight - chatLog.clientHeight <= chatLog.scrollTop + 1;
chatLog.scrollTop = chatLog.scrollHeight;
if (isScrolledToBottom) {
restoreScrollPosition();
}
}
function restoreScrollPosition() {
chatLog.scrollTop = scrollPosition;
}
});
check if i have any error in my code
i’m trying to make a chatbot by using html,css,js by using api key from openai . but i’m not getting response. i don’t know weather i have problem with my code or the api key. but i this i have problem with my openai api key. can you please tell hoe to fetch data from openai api key