JavaScript: memory for an AI chat
Keep every message in an array and send it again as contents. The roles are user and model.
All lessons · JavaScript lessons: learn from scratch
Why it forgets
The API has no memory of its own. Every fetch is a new chat. To remember a name you keep the whole history in an array and send it as contents on every request. A human message has the role user. An AI answer has the role model. assistant and ai are wrong here. The server returns 400.
let sohbetTarixcesi = [
{ role: "user", parts: [{ text: "Mənim adım Ömərdir." }] },
{ role: "model", parts: [{ text: "Tanışlığımıza şadam, Ömər." }] },
{ role: "user", parts: [{ text: "Mənim adım nə oldu?" }] }
];Remember with push
The array is created outside the function. Inside it, every call resets it. First the user message is pushed, the array is sent, and the answer is pushed again as model. If the model answer is not added, two user messages sit in a row and the turn order breaks. In a long chat, slice(-10) sends only the last 10 messages.
const apiKey = process.env.GEMINI_API_KEY;
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`;
let sohbetTarixcesi = [];
async function mesajGonder(yeniMesaj) {
sohbetTarixcesi.push({ role: "user", parts: [{ text: yeniMesaj }] });
const cavab = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ contents: sohbetTarixcesi.slice(-10) })
});
const melumat = await cavab.json();
const aiCavabi = melumat.candidates[0].content.parts[0].text;
sohbetTarixcesi.push({ role: "model", parts: [{ text: aiCavabi }] });
console.log(aiCavabi);
}Questions
Why does the second question not know the name? The history was not sent. contents must be the whole array, not one question.
Why does the array go empty? It was created inside the function. Create it above, once.
Why do you get 400? The role is not model. Gemini does not use assistant.
How do you clear the memory? sohbetTarixcesi = []. The old array is dropped and a new empty one remains.