Generative AI with Node.js in Hindi #8 Maintain Chat Context & Memories in AI Chatbots
Maintain Chat Context
- What does it means ?
- Update code for context and Test response
- Disadvantage of context
- Interview Questions
- Code and Notes link
import OpenAI from "openai";
import dotenv from "dotenv";
dotenv.config();
const client = new OpenAI({ apiKey: process.env.openAI_Key });
// Store conversation history in an array
let chatHistory = [
{ role: "system", content: "You are a helpful AI assistant." },
];
async function aiAnswer(qsn) {
// Add user message to chat history
chatHistory.push({ role: "user", content: qsn });
const response = await client.responses.create({
model: "gpt-4o-mini",
input: chatHistory,
});
const answer = response.output_text;
console.log("\nAI:", answer, "\n");
// Add assistant's reply to chat history (to maintain context)
chatHistory.push({ role: "assistant", content: answer });
}
process.stdout.write("Ask your question (type 'exit' to quit): ");
process.stdin.on("data", (data) => {
const qsn = data.toString().trim();
if (qsn.toLowerCase() === "exit") {
console.log("Goodbye!");
process.exit();
} else if (qsn.toLowerCase() === "clear") {
chatHistory = [
{ role: "s