DEV Community

Cover image for Stop Expecting the AI to Remember You - Build Chat Memory in Express for Beginners
FredAbod
FredAbod

Posted on

Stop Expecting the AI to Remember You - Build Chat Memory in Express for Beginners

So you've used ChatGPT. You told it your name. Three messages later it still knows your name.

So you think the model remembers you. ๐Ÿฅฐ

Then you build your first AI feature. You call the API with the user's new message. The user says "My name is Tolu". Next message: "What is my name?"

The AI: "I don't know your name." ๐Ÿ˜ญ๐Ÿ˜ญ

You check your code. You check the API key. You blame the model. You blame your network provider.

It was you. It was always you ๐Ÿ˜…

Here's the thing most people (including many developers) don't know: the model (the actual AI behind apps like ChatGPT) doesn't remember anything between requests. Every chat app you've used is quietly sending the whole conversation back to the model on every single message.

Today we'll build that ourselves in Express and TypeScript: a forgetful chat route (the bug), one that remembers by resending the history, and one that trims the history so long chats don't blow up.

confused person looking at laptop

The analogy: the mechanic with no notebook ๐Ÿ”ง

Picture a roadside mechanic. Great hands. Fixes anything. But he has no notebook. The moment you drive off, he forgets you completely.

So every time you come back, you bring a job card with everything so far: "Customer: Tolu. Car: Corolla 2012. Last visit: brake pads. Today: a new noise." He reads the whole card, then he answers.

That's exactly how a chat API works:

  • The mechanic = the AI model. Brilliant, but no memory.
  • The job card = the messages array you send with every request.
  • The person carrying the card = your backend. Tolu is the end user, but your backend is the one walking the card to the mechanic every time. Keeping the card is YOUR job.

And one more thing: the mechanic can only read so much. Bring him a 300-page job card and he'll hand it back and say "this is too long". We'll get to that. ๐Ÿ‘€

Is this really how it works? (yes, from the docs)

First, one word you'll see everywhere: token. A token is a small chunk of text, often a piece of a word. "Hello, world!" is 4 tokens with the tool we'll use today. A tokenizer is the code that cuts text into tokens. AI providers count limits and prices in tokens, not words or characters. Input tokens are what you send to the model; output tokens are what it writes back.

Now, I don't want you to just take my word for it, so here's what the providers say:

  • Anthropic's docs for the Claude Messages API: "The Messages API is stateless, which means that you always send the full conversational history to the API." "Stateless" just means the server keeps nothing about you between requests.
  • OpenAI's docs show the same idea: you include the model's previous answers in your next request. OpenAI can also store the conversation for you, but their docs say that even then, all the earlier messages are still "billed as input tokens." So even when they keep the job card for you, the model still reads all of it, and you still pay for all of it.

In real life, your backend sends an HTTP request to the provider with a list of messages, and gets the model's reply back. Today our fake model is just a function that takes that same list of messages, so you can see the idea without paying anyone.

Prerequisites

  • Node.js 18 or newer
  • Basic JavaScript, and you've built at least one simple Express API
  • TypeScript is a bonus, not a must. I'll explain each bit of TypeScript the first time we use it
  • A terminal with curl. The test commands are written for bash (macOS, Linux, or Git Bash/WSL on Windows). In Windows PowerShell or cmd the quotes and loops work differently, so use Git Bash for those parts
  • No AI API key needed. We'll use a fake model that behaves like the real thing: it only knows what's in the messages array you send. I'll be honest about what's fake as we go.

Let's Dive Right In ๐Ÿ˜๐Ÿ˜

Create the project and install what we need:

mkdir chat-memory && cd chat-memory
npm init -y
npm install express@5 gpt-tokenizer
npm install -D typescript @types/express @types/node
mkdir -p src/routes
Enter fullscreen mode Exit fullscreen mode
  • express@5: our web server. Version 5 sends errors from async routes to our error handler automatically.
  • gpt-tokenizer: counts tokens the way OpenAI's models do.
  • typescript and @types/...: so TypeScript understands Node and Express.

Open package.json and add "type": "module" (so we can use import) and two scripts. Mine looks like this:

{
  "name": "chat-memory",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build": "tsc",
    "start": "node dist/server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^5.3.0",
    "gpt-tokenizer": "^4.1.2"
  },
  "devDependencies": {
    "@types/express": "^5.0.6",
    "@types/node": "^26.6.6",
    "typescript": "^7.0.2"
  },
  "type": "module"
}
Enter fullscreen mode Exit fullscreen mode

Your version numbers may be different. That's fine.

Now create tsconfig.json in the project root:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "strict": true,
    "outDir": "dist",
    "rootDir": "src",
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode
  • strict: true turns on TypeScript's strictest checks. Good habit.
  • rootDir is where our code lives (src), outDir is where the compiled JavaScript goes (dist).
  • The other options make TypeScript output modern JavaScript that works with Node's import. Copy them as they are.

Here's where we're going:

chat-memory/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ types.ts          # what a message looks like
โ”‚   โ”œโ”€โ”€ tokens.ts         # counts tokens
โ”‚   โ”œโ”€โ”€ fakeModel.ts      # our pretend AI (no memory!)
โ”‚   โ”œโ”€โ”€ store.ts          # where we keep the job cards
โ”‚   โ”œโ”€โ”€ trim.ts           # cuts long job cards down
โ”‚   โ”œโ”€โ”€ routes/
โ”‚   โ”‚   โ”œโ”€โ”€ forgetful.ts  # โŒ the bug
โ”‚   โ”‚   โ”œโ”€โ”€ remember.ts   # โœ… resend everything
โ”‚   โ”‚   โ””โ”€โ”€ trimmed.ts    # โœ…โœ… resend what fits
โ”‚   โ”œโ”€โ”€ app.ts
โ”‚   โ””โ”€โ”€ server.ts
โ”œโ”€โ”€ package.json
โ””โ”€โ”€ tsconfig.json
Enter fullscreen mode Exit fullscreen mode

Step 1: What's on the job card โ€” src/types.ts

This file does one thing. It describes a message.

// The three kinds of message a chat API understands.
export type Role = "system" | "user" | "assistant";

export type Message = {
  role: Role;
  content: string;
};
Enter fullscreen mode Exit fullscreen mode

Every chat API uses roughly this shape:

  • export type creates a TypeScript type: a description of what a value must look like. It disappears when the code is compiled; it's only there to catch mistakes.
  • "system" | "user" | "assistant" means "only one of these three strings is allowed".
  • system: instructions for the model ("You are a friendly support assistant"). Think of it as the rules pinned on the mechanic's wall.
  • user: what the person typed.
  • assistant: what the model replied.

Step 2: Counting the pages โ€” src/tokens.ts

The mechanic doesn't care how many words are on your job card. He cares about tokens.

import { countTokens } from "gpt-tokenizer";
import type { Message } from "./types.js";

// gpt-tokenizer uses OpenAI's o200k_base tokenizer.
// Claude, Gemini and others split text differently,
// so treat this number as a good estimate, not the exact bill.
export function countMessageTokens(messages: Message[]): number {
  let total = 0;
  for (const message of messages) {
    total += countTokens(message.content);
  }
  return total;
}
Enter fullscreen mode Exit fullscreen mode
  • Message[] means "an array of Messages". import type imports only the type, not any running code.
  • Notice the import says ./types.js, not ./types.ts. That's not a typo! TypeScript compiles every .ts file into a .js file, and Node runs the .js files, so imports point at the compiled name. Don't "fix" it to .ts ๐Ÿ˜…
  • countTokens comes from gpt-tokenizer. By default it uses a tokenizer called o200k_base, the one modern OpenAI models use.
  • Other providers cut text into tokens differently. Claude, for example, has its own token counting API. So this is a good estimate, not the exact number on your bill.

Step 3: The mechanic with no notebook โ€” src/fakeModel.ts

This is our pretend AI. It's fake on purpose, so you can run this without an API key or paying anyone. But it follows the one rule that matters: it only knows what's inside the messages you pass in right now.

import type { Message } from "./types.js";
import { countMessageTokens } from "./tokens.js";

// Tiny on purpose so we can hit it in a demo.
// Real models allow far more (often hundreds of thousands of tokens).
export const CONTEXT_LIMIT = 120;

export class ContextTooLongError extends Error {}

// A pretend AI model. Just like a real chat API, it has NO memory.
// The only thing it knows is the `messages` array you pass in right now.
export async function fakeModel(messages: Message[]): Promise<string> {
  const tokens = countMessageTokens(messages);

  if (tokens > CONTEXT_LIMIT) {
    // Real APIs reject a request that is too big with a 400 error.
    throw new ContextTooLongError(
      `prompt is too long: ${tokens} tokens > ${CONTEXT_LIMIT} maximum`
    );
  }

  // Look for "my name is ..." in anything the user has said in THIS request.
  const userText = messages
    .filter((m) => m.role === "user")
    .map((m) => m.content)
    .join(" ");
  const match = userText.match(/my name is (\w+)/i);

  const greeting = match ? `Hi ${match[1]}!` : "Hi! I don't know your name yet.";
  return `${greeting} (I can see ${messages.length} messages, ${tokens} tokens.)`;
}
Enter fullscreen mode Exit fullscreen mode

Three important things, don't skip them:

  • There is no variable outside the function that stores old messages. Nothing. Every call starts from zero, exactly like a real model.
  • It looks for "my name is ..." in the user messages it was given. If the name isn't on this job card, it doesn't know it. (The regex /my name is (\w+)/i finds "my name is" followed by a word; the brackets capture that word, so match[1] is the name. The i means "ignore upper/lower case".)
  • CONTEXT_LIMIT is the most tokens it will read in one request. Real models have a limit too, called the context window. Anthropic's docs describe it as the model's "working memory": everything the model can look at while answering, including the reply it is writing.
  • If what you send is already bigger than the window, Claude's API rejects it with a 400 error (HTTP 400 means "Bad Request": the problem is the request itself) saying prompt is too long. Our fake model copies that. (Ours is 120 tokens so we can hit it in a few messages. Real ones are much bigger.)

Two bits of TypeScript: async and Promise<string> mean "this function eventually gives back a string". Nothing inside actually waits, but a real model call goes over the network, so we keep the same shape. That way, swapping in a real API later doesn't change the routes.

ContextTooLongError is our own error type, so later we can tell "too long" apart from other errors.

Step 4: The filing cabinet โ€” src/store.ts

The mechanic has no notebook, so we keep the job cards.

import type { Message } from "./types.js";

// Our "database": conversation id -> list of messages.
// It lives in memory, so restarting the server wipes it.
// In a real app, save this in MongoDB, Postgres, Redis, etc.
const conversations = new Map<string, Message[]>();

export function getHistory(conversationId: string): Message[] {
  return conversations.get(conversationId) ?? [];
}

export function saveHistory(conversationId: string, messages: Message[]): void {
  conversations.set(conversationId, messages);
}
Enter fullscreen mode Exit fullscreen mode
  • A Map is like an object made for lookups: give it a key (the conversation id), get back the value (the messages).
  • ?? [] means "if there's nothing saved yet, use an empty list".
  • This is in memory to keep the tutorial simple. Restart the server and every job card is gone. In real life, use a database.

slamming shut

Step 5: The bug โ€” src/routes/forgetful.ts

Let's write the code most of us write on day one. Be honest. ๐Ÿ˜…

import { Router } from "express";
import { fakeModel } from "../fakeModel.js";
import type { Message } from "../types.js";

export const SYSTEM: Message = { role: "system", content: "You are a friendly support assistant." };

export const forgetfulRouter = Router();

// โŒ Sends ONLY the newest message. The model never sees anything older.
forgetfulRouter.post("/", async (req, res) => {
  const { message } = req.body as { message: string };

  const reply = await fakeModel([SYSTEM, { role: "user", content: message }]);

  res.json({ reply });
});
Enter fullscreen mode Exit fullscreen mode

req.body as { message: string } is TypeScript for "trust me, the body has a message string in it". (In a real app you'd validate that. We're keeping it short.)

It sends the system message and the newest user message. That's it. It's like driving to the mechanic and saying "the noise is back" without your job card. "What noise? Who are you?"

We export SYSTEM so the other routes can reuse the same instructions. A Router is a mini app for a group of routes. The "/" here becomes /chat/forgetful when we plug it in in Step 9.

Step 6: Bring the whole job card โ€” src/routes/remember.ts

Now the fix. We save every message, and we send all of them, every time.

import { Router } from "express";
import { fakeModel } from "../fakeModel.js";
import { getHistory, saveHistory } from "../store.js";
import { SYSTEM } from "./forgetful.js";
import type { Message } from "../types.js";

export const rememberRouter = Router();

// โœ… Keeps the whole conversation and resends ALL of it every time.
rememberRouter.post("/:id", async (req, res) => {
  const { message } = req.body as { message: string };

  const history = getHistory(req.params.id);
  const userMessage: Message = { role: "user", content: message };

  // The full "job card": instructions + every old message + the new one.
  const reply = await fakeModel([SYSTEM, ...history, userMessage]);

  // Save BOTH sides, so next time the model sees its own answers too.
  saveHistory(req.params.id, [...history, userMessage, { role: "assistant", content: reply }]);

  res.json({ reply });
});
Enter fullscreen mode Exit fullscreen mode
  • getHistory pulls out the old job card for this conversation id (the :id in the URL).
  • [SYSTEM, ...history, userMessage]: the ... (spread) copies every old message into the new list. So the model gets instructions + everything so far + the new message.
  • We save the model's reply too. If you only save the user's messages, the model forgets what it said. Then it contradicts itself and everyone is confused.

This is what ChatGPT-style apps are doing behind the scenes on every message.

Step 7: Tear out the old pages โ€” src/trim.ts

Every message makes the job card longer. Longer card = more tokens = more money, slower answers, and eventually that 400 error.

There's another reason to keep it short: Anthropic's docs say that as the token count grows, "accuracy and recall degrade, a phenomenon known as context rot." In plain English: the longer the input, the worse the model gets at finding and using the details inside it. Researchers at Chroma (a company that builds a database for AI apps) tested 18 models and found the same pattern: performance gets less reliable as the input gets longer. So a huge job card doesn't just cost more. The mechanic also reads it worse. ๐Ÿ˜ฌ

So we keep the rules page (system message) and the newest pages that fit in a budget.

import type { Message } from "./types.js";
import { countMessageTokens } from "./tokens.js";

// Keep the system message, then add messages from NEWEST to oldest
// until the next one would take us over the token budget.
export function trimToBudget(system: Message, history: Message[], budget: number): Message[] {
  const kept: Message[] = [];
  let used = countMessageTokens([system]);

  for (let i = history.length - 1; i >= 0; i--) {
    const cost = countMessageTokens([history[i]]);
    if (used + cost > budget) break; // no more space, stop here

    kept.unshift(history[i]); // unshift = add to the FRONT, so order stays oldest -> newest
    used += cost;
  }

  return [system, ...kept];
}
Enter fullscreen mode Exit fullscreen mode

Walk through it slowly:

  • We start counting with the system message, because that one always stays.
  • The for loop starts at the end of the list (the newest message) and walks backwards.
  • For each message: "If I add this one, do I go over the budget?" If yes, break (stop the loop).
  • unshift puts each message at the front of kept. We're walking backwards, so this keeps the final list in normal order: oldest first, newest last.

Fun fact: Anthropic's docs mention that chat interfaces such as claude.ai can also manage the context window on a rolling "first in, first out" basis. That's this exact idea: the oldest pages go first. ๐Ÿค—

Step 8: Keep everything, send what fits โ€” src/routes/trimmed.ts

Same as Step 6, with one change: we still save everything in our database, but we only send the trimmed version.

import { Router } from "express";
import { fakeModel } from "../fakeModel.js";
import { getHistory, saveHistory } from "../store.js";
import { trimToBudget } from "../trim.js";
import { countMessageTokens } from "../tokens.js";
import { SYSTEM } from "./forgetful.js";
import type { Message } from "../types.js";

// Stay below the model's limit (120) and leave space for the reply.
const BUDGET = 100;

export const trimmedRouter = Router();

// โœ…โœ… Keeps the whole conversation in OUR database,
// but only sends the newest part that fits in the budget.
trimmedRouter.post("/:id", async (req, res) => {
  const { message } = req.body as { message: string };

  const history = getHistory(req.params.id);
  const userMessage: Message = { role: "user", content: message };
  const fullHistory = [...history, userMessage];

  const toSend = trimToBudget(SYSTEM, fullHistory, BUDGET);
  const reply = await fakeModel(toSend);

  saveHistory(req.params.id, [...fullHistory, { role: "assistant", content: reply }]);

  res.json({
    reply,
    storedMessages: fullHistory.length + 1, // everything we saved (+1 for the new reply)
    sentMessages: toSend.length, // what the model actually saw
    sentTokens: countMessageTokens(toSend),
  });
});
Enter fullscreen mode Exit fullscreen mode
  • BUDGET is 100, below the fake model's limit of 120. In real life the reply also counts toward the context window, so you always leave room for it.
  • We return storedMessages (everything saved, including the new reply, but not the system message), sentMessages (what the model saw, including the system message) and sentTokens, only so you can see the trimming. You wouldn't send these to a real user.

Step 9: Wire it up โ€” src/app.ts

import express from "express";
import type { NextFunction, Request, Response } from "express";
import { ContextTooLongError } from "./fakeModel.js";
import { forgetfulRouter } from "./routes/forgetful.js";
import { rememberRouter } from "./routes/remember.js";
import { trimmedRouter } from "./routes/trimmed.js";

export const app = express();
app.use(express.json());

app.use("/chat/forgetful", forgetfulRouter);
app.use("/chat/remember", rememberRouter);
app.use("/chat/trimmed", trimmedRouter);

// Error handler: Express 5 sends errors from async routes here automatically.
// The 4 parameters (err, req, res, next) are how Express knows it's an error handler.
app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {
  if (err instanceof ContextTooLongError) {
    // 400 = "Bad Request": the request itself is the problem, retrying won't help.
    res.status(400).json({ error: err.message });
    return;
  }
  res.status(500).json({ error: "Something went wrong" });
});
Enter fullscreen mode Exit fullscreen mode
  • Three routes, one for each version, so we can compare them side by side.
  • The last app.use(...) is an error handler. When the fake model throws ContextTooLongError, Express 5 passes it here and we send a 400 (the same status Claude's API returns for a prompt that's too long). Anything else becomes a 500 ("something broke on our side").
  • _req and _next start with _ to say "I know I'm not using these". Express still needs all four parameters to know this is an error handler.

Step 10: Open for business โ€” src/server.ts

import { app } from "./app.js";

const PORT = 3000;

app.listen(PORT, () => {
  console.log(`Chat server running on http://localhost:${PORT} ๐Ÿš€`);
});
Enter fullscreen mode Exit fullscreen mode

That's it. Build and run:

npm run build
npm start
Enter fullscreen mode Exit fullscreen mode

You should see:

Chat server running on http://localhost:3000 ๐Ÿš€
Enter fullscreen mode Exit fullscreen mode

Let's test it ๐Ÿงช

Open a second terminal (leave the server running in the first one).

Small heads-up: curl doesn't print a new line after each response, so two replies can end up stuck together on one line. That's fine. I've put each reply on its own line below so it's easier to read. In the commands, -X POST sets the method, -H adds a header, and -d is the JSON body (same three things you'd fill in on Postman).

Test 1: The forgetful route

curl -X POST http://localhost:3000/chat/forgetful \
  -H "Content-Type: application/json" \
  -d '{"message":"Hello, my name is Tolu"}'

curl -X POST http://localhost:3000/chat/forgetful \
  -H "Content-Type: application/json" \
  -d '{"message":"What is my name?"}'
Enter fullscreen mode Exit fullscreen mode
{"reply":"Hi Tolu! (I can see 2 messages, 14 tokens.)"}
{"reply":"Hi! I don't know your name yet. (I can see 2 messages, 12 tokens.)"}
Enter fullscreen mode Exit fullscreen mode

Two messages each time: the system message and the newest user message. The second request never had your name on it. The model didn't "forget". It never had it. ๐Ÿ˜ญ

Test 2: The remembering route

The abc at the end of the URL is the conversation id. Same id = same job card.

curl -X POST http://localhost:3000/chat/remember/abc \
  -H "Content-Type: application/json" \
  -d '{"message":"Hello, my name is Tolu"}'

curl -X POST http://localhost:3000/chat/remember/abc \
  -H "Content-Type: application/json" \
  -d '{"message":"What is my name?"}'
Enter fullscreen mode Exit fullscreen mode
{"reply":"Hi Tolu! (I can see 2 messages, 14 tokens.)"}
{"reply":"Hi Tolu! (I can see 4 messages, 35 tokens.)"}
Enter fullscreen mode Exit fullscreen mode

It knows your name! ๐ŸŽ‰ Look at the second reply: 4 messages (system, your first message, its first reply, your new message). Same model. The only difference is what we sent.

Celebrate

Now keep talking. This loop sends five more messages ($i is just 3, 4, 5, 6, 7):

for i in 3 4 5 6 7; do
  curl -X POST http://localhost:3000/chat/remember/abc \
    -H "Content-Type: application/json" \
    -d "{\"message\":\"Message number $i, still there?\"}"
  echo
done
Enter fullscreen mode Exit fullscreen mode
{"reply":"Hi Tolu! (I can see 6 messages, 59 tokens.)"}
{"reply":"Hi Tolu! (I can see 8 messages, 83 tokens.)"}
{"reply":"Hi Tolu! (I can see 10 messages, 107 tokens.)"}
{"error":"prompt is too long: 131 tokens > 120 maximum"}
{"error":"prompt is too long: 131 tokens > 120 maximum"}
Enter fullscreen mode Exit fullscreen mode

Watch the tokens climb: 14, 35, 59, 83, 107... then ๐Ÿ’ฅ. The job card got too long, and now every message in this conversation fails. Notice both errors say 131 tokens: the failed request saved nothing, so the card is stuck at the same size. Nothing in this route ever makes the card shorter, so retrying fails the same way forever. That's why it's a 400 and not a temporary error like a 429 ("too many requests, slow down") or a 503 ("server busy, try again later").

(If you want to run Test 2 again, restart the server with Ctrl+C and npm start, or use a new id like abc2. Conversation abc is now full.)

Test 3: The trimmed route

Same messages, new conversation id xyz:

curl -X POST http://localhost:3000/chat/trimmed/xyz \
  -H "Content-Type: application/json" \
  -d '{"message":"Hello, my name is Tolu"}'

curl -X POST http://localhost:3000/chat/trimmed/xyz \
  -H "Content-Type: application/json" \
  -d '{"message":"What is my name?"}'

for i in 3 4 5 6 7; do
  curl -X POST http://localhost:3000/chat/trimmed/xyz \
    -H "Content-Type: application/json" \
    -d "{\"message\":\"Message number $i, still there?\"}"
  echo
done
Enter fullscreen mode Exit fullscreen mode
{"reply":"Hi Tolu! (I can see 2 messages, 14 tokens.)","storedMessages":2,"sentMessages":2,"sentTokens":14}
{"reply":"Hi Tolu! (I can see 4 messages, 35 tokens.)","storedMessages":4,"sentMessages":4,"sentTokens":35}
{"reply":"Hi Tolu! (I can see 6 messages, 59 tokens.)","storedMessages":6,"sentMessages":6,"sentTokens":59}
{"reply":"Hi Tolu! (I can see 8 messages, 83 tokens.)","storedMessages":8,"sentMessages":8,"sentTokens":83}
{"reply":"Hi! I don't know your name yet. (I can see 9 messages, 100 tokens.)","storedMessages":10,"sentMessages":9,"sentTokens":100}
{"reply":"Hi! I don't know your name yet. (I can see 8 messages, 92 tokens.)","storedMessages":12,"sentMessages":8,"sentTokens":92}
{"reply":"Hi! I don't know your name yet. (I can see 8 messages, 97 tokens.)","storedMessages":14,"sentMessages":8,"sentTokens":97}
Enter fullscreen mode Exit fullscreen mode

No more errors. ๐ŸŽ‰ storedMessages keeps growing (we keep everything), but sentTokens never goes over 100.

But look closely ๐Ÿ‘€. From the fifth message, it says "I don't know your name yet." The page with "my name is Tolu" was the oldest, so it was the first page we tore out.

That's the trade-off. Trimming keeps you under the limit, but whatever you cut, the model can't see.

shocked face

Before vs after

โŒ forgetful
   app โ”€โ”€[system + newest message]โ”€โ”€โ–ถ model
   (model never sees your name again)

โœ… remember
   app โ”€โ”€[system + EVERY old message + newest]โ”€โ”€โ–ถ model
   (works... until the card is too long: 400 ๐Ÿ’ฅ)

โœ…โœ… trimmed
   database keeps EVERYTHING
   app โ”€โ”€[system + newest messages that fit the budget]โ”€โ”€โ–ถ model
   (never too long, but the oldest pages are not sent)
Enter fullscreen mode Exit fullscreen mode

Why we do it this way (and what to do next)

  • The model is stateless. If you need it to know something, it must be in this request. No exceptions.
  • Your database is the notebook, not the model. Save every message, including the assistant's replies.
  • Trim before you send. Count tokens on your side and stay under the limit with room for the reply.
  • Important facts shouldn't live only in old messages. In a real app, put things like the user's name or their order number in the system message (that page never gets torn out), or keep a short summary of older messages and send that instead of the old pages. Anthropic even runs this on their side as a feature called compaction: their docs say it automatically summarizes earlier parts of the conversation so it can keep going past the limit.
  • Even if you just use ChatGPT or Claude: for a new task, a new chat with a short summary of what matters is often better than one endless thread.

I use AI coding agents (tools that read and write code in your project for you) every day, and this one idea explains so much of their behaviour. Once you see the job card, you can't unsee it. ๐Ÿ˜‹

Recap (say it with me)

  1. The model has no memory. It only knows what's in the messages you send right now.
  2. Chat apps "remember" by resending the whole conversation every time.
  3. Everything you send costs tokens, and every model has a context window limit. Go over it and the request fails.
  4. Long contexts also get less reliable (context rot), not just more expensive.
  5. Keep everything in your database, send only what fits, and keep important facts somewhere they won't get trimmed.

The mechanic is brilliant. But the job card is your responsibility. ๐Ÿ”ง

GitHub repo: https://github.com/FredAbod/stop-expecting-the-ai-to-remember-you-code

I hope this was helpful. Don't forget to drop a like and follow ๐Ÿ˜‹๐Ÿ˜‹

Thank you for taking the time to read ๐Ÿฅฐ๐Ÿฅฐ

See you on the next one ๐Ÿค—

Top comments (0)