Conversation Memory
Memory is just a list of past messages you keep sending back - and trim before it gets too big.
Watch the lesson
Lesson 1.8: Agentic AI from Scratch | Conversation Memory – How AI Remembers Previous Messages▶ Watch on YouTubeWhat you will be able to do
- Explain why a model does not remember previous calls
- Give an agent memory by keeping and resending the message list
- Explain the context window, and what happens when a conversation outgrows it
- Trim history by whole exchanges while keeping the system message
- Predict what an agent forgets when history is trimmed
- Keep each conversation separate by giving each agent its own list
The idea, in plain English
A model remembers nothing between calls. Say "My name is Chandu" in one call and ask "What’s my name?" in the next, and it has no idea. We tried it: "I’m afraid I don’t know your name!"
So memory is simple: your code keeps a list of every message so far, and sends the WHOLE list on every call. The model seems to remember because the history is right in front of it. Your code remembers; the model just reads.
The list cannot grow forever - every call reads all of it again, and a model can only take in so much text at once. So you trim the oldest messages. But trimming is forgetting: in our runs, after five small questions the agent no longer knew the name it was told at the start.
Worked example: A chat agent that remembers your name.
Call 1 - the introduction
Two messages go out: the system message and "Hi, my name is Chandu." The reply is appended to the list by your code.
A real run with max_history=10. Each step shows what is sent to the model on that call, and the prompt tokens it processed.
An everyday example: the helper’s notebook
Back to the shop - with one odd fact about the owner: he forgets everything the moment he finishes a sentence. A model is like that between calls.
- A customer says "I’m Chandu." Later the customer asks "What’s my name?" - and the owner has no idea.
- So the helper keeps a notebook. Page 1 holds the shop’s rules. After that, every line of the conversation goes in.
- Before the owner answers anything, the helper reads him the WHOLE notebook. Now he "remembers" - because he just heard it all again.
- The notebook gets longer, so the reading takes longer every time.
- The notebook has only so many pages. When it is full, the oldest pages fall out - and nobody says anything.
- So the helper tears out old pages on purpose, but always keeps page 1, the rules.
- If the page with "I’m Chandu" is torn out, the owner forgets the name. Not because he is broken - because nobody read it to him.
- At closing time the notebook goes in the bin. Tomorrow starts blank - unless the name was copied into the customer register in the drawer.
The owner forgets after each sentenceEvery model call starts from nothing.The notebookself.messages - the list of every message so far.Page 1, the shop’s rulesThe system message - never trimmed.Reading the whole notebook out each timeSending the whole list on every call.Reading takes longer each timeMore tokens to process on every call.The notebook’s page limitThe context window. Past it, Ollama drops the oldest messages silently.Tearing out old pages on purposeTrimming the history.The torn-out page with the nameTrimming is forgetting.The notebook in the bin at closingConversation memory ends with the program.The customer register in the drawerPersistent memory: a file or a database (POC 2).Memory is the message list
ChatAgent keeps the notebook. Each call to ask() does three things:
- 1. Append the user’s message to self.messages.
- 2. Send the whole list to the model.
- 3. Append the reply - so next time the model sees it too.
- Then, if the list is longer than max_history, it keeps the system message plus the most recent messages.
- Nothing is stored on the model side. Two separate calls know nothing about each other, and a NEW ChatAgent - a new list - does not know your name either. Each agent has its own memory.
import ollama
class ChatAgent:
def __init__(self, model="llama3.1", max_history=10):
self.model = model
self.max_history = max_history
self.messages = [{"role": "system", "content": "You are a friendly assistant."}]
def ask(self, user_input):
self.messages.append({"role": "user", "content": user_input})
response = ollama.chat(model=self.model, messages=self.messages)
reply = response["message"]["content"]
self.messages.append({"role": "assistant", "content": reply})
# trim: keep system message + last N messages
if len(self.messages) > self.max_history:
self.messages = [self.messages[0]] + self.messages[-(self.max_history - 1):]
return reply
agent = ChatAgent()
print(agent.ask("Hi, my name is Chandu."))
print(agent.ask("What's my name?"))With the history:
Nice to meet you, Chandu! I'm happy to chat with you. ...
I remember! Your name is Chandu!
Two independent calls, no history:
I'm afraid I don't know your name! ...
A new ChatAgent():
I'm happy to help! However, I don't actually know your name. ...What memory costs - and what trimming forgets
We told the agent a name, asked five small questions, then asked the name again - with max_history=10:
- Every call reads the whole list. Prompt tokens went 29, 67, 90, 111, 131 - each call more work than the last, though every question was one short line.
- Locally that costs time. On a paid API it costs money per token.
- After call 6 the list passed max_history and was trimmed. The introduction was among the messages dropped.
- So "What’s my name?" got: "I don’t think you told me your name!" With max_history=40, the same conversation still knew it.
call 1 2 messages sent 29 prompt tokens "Hi, my name is Chandu."
call 2 4 messages sent 67 prompt tokens "Name a fruit."
call 3 6 messages sent 90 prompt tokens "Name a colour."
call 4 8 messages sent 111 prompt tokens "Name a planet."
call 5 10 messages sent 131 prompt tokens "Name a river."
call 6 11 messages sent 136 prompt tokens "Name a mountain." <- trimmed after this
call 7 11 messages sent 116 prompt tokens "What's my name?"
Reply: "I don't think you told me your name! ..."
Roles after trimming: system, assistant, user, assistant, ... <- an orphaned reply
Same conversation with max_history=40:
Reply: "I remember! Your name is Chandu!"The context window: how much the model can read at once
Every call sends the whole list. But a model can only read so much in one call - like the notebook having only so many pages. Step by step:
- 1. Text is counted in TOKENS - small pieces of words. A token is roughly three-quarters of an English word. A one-line question is about 10-15 tokens; a page of text is several hundred.
- 2. The CONTEXT WINDOW is the most tokens the model reads in one call. llama3.1 can handle up to 131,072 - but Ollama runs it with a window of 4,096 unless you ask for more. (ollama ps shows the window it is using.)
- 3. If the conversation is LONGER than the window, Ollama cuts it to fit by dropping the OLDEST messages. There is no error and no warning.
- 4. We tested it: a name, then three long notes, then "What’s my name?" - about 8,000 tokens in all.
- 5. With the default window of 4,096, only 2,584 tokens were read. The message with the name had been dropped, and the model answered "You didn’t mention your name."
- 6. With options={"num_ctx": 8192}, all 8,032 tokens were read, and it answered "Your name is Chandu."
- 7. So you can raise the window - but it is not free. Memory use went from 5.6 GB to 6.3 GB, and the long call took many minutes on this laptop’s CPU. And the bigger window still has an end: talk long enough, and the oldest messages are dropped again.
- 8. Two habits keep you safe: put facts the agent must never lose (a name, a goal, a rule) in the system message, and check response["prompt_eval_count"] - the number of tokens actually read. If it is far smaller than you expect, something was cut.
What we sent - about 8,000 tokens:
[system] [my name is Chandu] [long note 1] [long note 2] [long note 3] ["What's my name?"]
Default window, 4,096 tokens - Ollama drops the oldest messages until the rest fits:
[system] ................................................ [long note 3] ["What's my name?"]
read: 2,584 tokens -> "You didn't mention your name. Would you like to share it with me?"
num_ctx 8192 - everything fits:
[system] [my name is Chandu] [long note 1] [long note 2] [long note 3] ["What's my name?"]
read: 8,032 tokens -> "Your name is Chandu."import ollama
def long_note(topic):
return " ".join(
f"This is sentence {i} of a long note about {topic}, written only to make the conversation long."
for i in range(110)
)
messages = [
{"role": "system", "content": "You are a friendly assistant."},
{"role": "user", "content": "Hi, my name is Chandu."},
{"role": "assistant", "content": "Nice to meet you, Chandu!"},
]
for topic in ["the history of railways in India", "how monsoon rains form", "the rules of cricket"]:
messages.append({"role": "user", "content": "Please keep this note for later:\n" + long_note(topic)})
messages.append({"role": "assistant", "content": "Noted."})
messages.append({"role": "user", "content": "What's my name?"})
# 1. Ollama's default window (4,096 tokens)
r = ollama.chat(model="llama3.1", messages=messages, options={"temperature": 0})
print(r["prompt_eval_count"], r["message"]["content"])
# 2. A bigger window
r = ollama.chat(model="llama3.1", messages=messages,
options={"temperature": 0, "num_ctx": 8192, "num_predict": 60})
print(r["prompt_eval_count"], r["message"]["content"])
# 2584 You didn't mention your name. Would you like to share it with me?
# 8032 Your name is Chandu.Watch out: Ollama does not raise an error when a conversation is too long - it drops the oldest messages without telling you. If an agent suddenly forgets something, check prompt_eval_count before you blame the model.
Two small bugs in the first ChatAgent
The first ChatAgent works, but it has two bugs that are easy to miss. Both are about keeping the list in the right SHAPE: a system message, then question, answer, question, answer...
- BUG 1 - THE TRIM CUTS A PAIR IN HALF.
- A conversation is pairs: each question (user) has its answer (assistant).
- The old trim keeps the system message plus the last 9 messages. 9 is an odd number, so it cannot be whole pairs.
- Look at "old trim" below: the list now starts with "answer 1" - but "question 1" was thrown away. The model sees an answer to a question it never saw.
- The fix: count whole PAIRS (we call them exchanges), not single messages. Keep the last 4 exchanges = the last 8 messages: history[-2 * max_exchanges:]. Now the list starts with "question 2", and every answer has its question.
- BUG 2 - A FAILED CALL LEAVES A QUESTION BEHIND.
- ask() adds the question to the list FIRST, then calls the model.
- If the call fails - Ollama is not running, or it times out - the question is already in the list, with no answer after it.
- Ask again, and the model receives TWO questions in a row: system, user, user. The old, failed question is mixed into the new one.
- The fix: if the call fails, take the question back out with self.messages.pop(), then let the error continue. After the retry the list is clean again: system, user, assistant.
- And in both versions the system message is never trimmed. It holds the instructions - lose it, and the agent forgets how to behave halfway through a long chat.
# 5 exchanges: system + 5 x (question, answer) = 11 messages
messages = [{"role": "system", "content": "You are a friendly assistant."}]
for i in range(1, 6):
messages.append({"role": "user", "content": f"question {i}"})
messages.append({"role": "assistant", "content": f"answer {i}"})
def show(label, msgs):
print(f"{label:<12}", ", ".join(m["content"] if m["role"] != "system" else "SYSTEM" for m in msgs))
show("before", messages)
# The first ChatAgent: system message + the last (max_history - 1) messages
max_history = 10
old = [messages[0]] + messages[-(max_history - 1):]
show("old trim", old)
# The fix: system message + the last N whole exchanges (2 messages each)
max_exchanges = 4
history = messages[1:]
new = [messages[0]] + history[-2 * max_exchanges:]
show("new trim", new)
# before SYSTEM, question 1, answer 1, question 2, answer 2, question 3, answer 3, question 4, answer 4, question 5, answer 5
# old trim SYSTEM, answer 1, question 2, answer 2, question 3, answer 3, question 4, answer 4, question 5, answer 5
# new trim SYSTEM, question 2, answer 2, question 3, answer 3, question 4, answer 4, question 5, answer 5
#
# old trim starts with "answer 1" - its question was thrown away.
# new trim starts with "question 2" - whole pairs only.calls = {"n": 0}
def fake_chat(messages): # fails the first time, as if Ollama were down
calls["n"] += 1
if calls["n"] == 1:
raise ConnectionError("Ollama is not running")
return {"message": {"content": f"reply to {messages[-1]['content']!r}"}}
def roles(msgs):
return ", ".join(m["role"] for m in msgs)
def ask_old(messages, text):
messages.append({"role": "user", "content": text}) # added BEFORE the call
reply = fake_chat(messages)["message"]["content"]
messages.append({"role": "assistant", "content": reply})
def ask_fixed(messages, text):
messages.append({"role": "user", "content": text})
try:
reply = fake_chat(messages)["message"]["content"]
except Exception:
messages.pop() # take the question back out
raise
messages.append({"role": "assistant", "content": reply})
for ask in (ask_old, ask_fixed):
calls["n"] = 0
messages = [{"role": "system", "content": "..."}]
try:
ask(messages, "What is a list?")
except ConnectionError as e:
print(f"{ask.__name__:<10} call 1 failed: {e}")
print(f"{'':<10} after the failure: {roles(messages)}")
ask(messages, "What is a tuple?")
print(f"{'':<10} after the retry: {roles(messages)}")
# ask_old call 1 failed: Ollama is not running
# after the failure: system, user
# after the retry: system, user, user, assistant <- two questions in a row
# ask_fixed call 1 failed: Ollama is not running
# after the failure: system
# after the retry: system, user, assistant <- cleanimport ollama
class ChatAgent:
def __init__(self, model="llama3.1", max_exchanges=4):
self.model = model
self.max_exchanges = max_exchanges # one exchange = a question and its reply
self.messages = [{"role": "system", "content": "You are a friendly assistant."}]
def ask(self, user_input):
self.messages.append({"role": "user", "content": user_input})
try:
response = ollama.chat(model=self.model, messages=self.messages)
except Exception:
self.messages.pop() # bug 2: never leave a question without its answer
raise
reply = response["message"]["content"]
self.messages.append({"role": "assistant", "content": reply})
# bug 1: keep the system message and the last N WHOLE exchanges
system, history = self.messages[0], self.messages[1:]
self.messages = [system] + history[-2 * self.max_exchanges:]
return reply
agent = ChatAgent()
print(agent.ask("Hi, my name is Chandu."))
print(agent.ask("What's my name?"))
# Nice to meet you, Chandu! I'm happy to chat with you. ...
# I remember! Your name is Chandu!This memory ends with the program
- self.messages lives in your program’s memory. Close the program and the conversation is gone. That is conversation memory.
- Memory that survives a restart needs a file or a database. POC 2 at the end of this module adds one with a notes.json file.
- Anything the agent must ALWAYS know - the user’s name, a goal, a rule - belongs in the system message or in that file, not in an old turn that will be trimmed.
- Module 2 shows another option: summarise old turns instead of simply dropping them.
Conversation memoryself.messages - gone when the program stops.Persistent memoryA file or database - survives restarts (POC 2).Memory at a glance
self.messagesThe conversation - the only memory there is.
self.messages.append({...})System messageInstructions; never trimmed.
self.messages[0]
Context windowThe most tokens a model takes in at once.
options={"num_ctx": 8192}prompt_eval_countTokens actually processed on a call.
response["prompt_eval_count"]
Trim by exchangesKeep the last N question-and-answer pairs.
history[-2 * max_exchanges:]
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Hi, my name is Chandu. -> What's my name?”
“Tell it your name, ask five unrelated questions, then ask your name again.”
“Tell agent1 your name, then ask agent2 what it is.”
“Print response["prompt_eval_count"] on every call and watch it grow.”
What usually goes wrong
Every call is independent. Without the history in messages, the model knows nothing about earlier turns.
Slicing the whole list drops the instructions along with the oldest turns.
✗ self.messages = self.messages[-10:]✓ self.messages = [self.messages[0]] + self.messages[1:][-8:]The oldest message kept is a reply whose question was dropped. Count whole exchanges.
✗ self.messages[-(self.max_history - 1):]✓ history[-2 * self.max_exchanges:]If the call fails after the user message is appended, the next call sends two user messages in a row.
✗ self.messages.append(user_message)
response = ollama.chat(...)✓ try:
response = ollama.chat(...)
except Exception:
self.messages.pop()
raisePast the context window, Ollama drops the oldest messages silently. Check prompt_eval_count.
They are the first thing trimming removes. Put what must persist in the system message or a file.
Key points
- A model remembers nothing between calls; memory is the history your code resends.
- The message list is the memory, and each ChatAgent has its own.
- Every call reprocesses the whole list - in our run 29, 67, 90, 111, 131 tokens.
- Past the context window, Ollama silently drops the oldest messages.
- A bigger window (num_ctx) lets more in, but costs memory and time - and still has an end.
- Trim by whole exchanges, and never trim the system message.
- Trimming is forgetting: after five small questions, the agent lost the name.
- This memory ends with the program; persistent memory needs a file (POC 2).
Quick check before you move on
Quiz
- 1.
Where does "memory" actually live in this code?
- 2.
Why do we trim self.messages instead of letting it grow forever?
- 3.
What would happen if you created a new ChatAgent() before asking "What’s my name?"
- 4.
With max_history=10, why is the oldest kept message an assistant reply?
- 5.
An agent was told a fact early on and later cannot recall it. Name two possible causes.
Interview questions
Does an LLM really have memory?
Not between requests. In a basic chat application the model is stateless: the application keeps the conversation history and sends it with each new request. As the history grows it has to be trimmed or otherwise managed to stay within the context window.
What happens when a conversation exceeds the context window?
Depending on the runtime it either errors or truncates. Ollama drops the oldest messages silently, so the model loses early context without any signal. You detect it by counting tokens, and manage it by trimming, summarising, or moving durable facts into a system message or external store.
How would you give an agent memory that survives restarts?
Store it outside the process - a file or database - and load the relevant parts into the prompt on each call. Keep short-term conversation history separate from long-term facts, which should be saved deliberately rather than kept as old turns.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...