Generative AI with Node.js in Hindi #8 Maintain Chat Context & Memories in AI Chatbots

Maintain Chat Context


  1. What does it means ?
  2. Update code for context and Test response
  3. Disadvantage of context
  4. Interview Questions
  5. 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