Conversations & Memory
LLM APIs are stateless: the model remembers nothing between requests. A chat that seems to "remember" works because the application sends the entire conversation history with every request. Managing that history — storing it, trimming it, summarising it, and adding long-term facts — is the app's job.
The history loop
Each turn appends the user's message, sends the whole list, and appends the reply:
import anthropic
client = anthropic.Anthropic()
history = []
def chat(user_text):
history.append({"role": "user", "content": user_text})
response = client.messages.create(model="claude-haiku-5-5", max_tokens=300,
system="You are a friendly cooking assistant.",
messages=history)
reply = response.content[0].text
history.append({"role": "assistant", "content": reply})
return replyTo run the same loop here without an API, we swap in a fake model — a deterministic function that only looks at the messages it receives. That makes the statelessness visible:
def fake_model(messages):
"""Answers 'what is my name?' only if the name appears somewhere in the history."""
last = messages[-1]["content"].lower()
if "my name is" in last:
name = last.split("my name is")[1].strip(" .!").title()
return f"Nice to meet you, {name}!"
if "what is my name" in last:
for m in messages:
if m["role"] == "user" and "my name is" in m["content"].lower():
return "Your name is " + m["content"].lower().split("my name is")[1].strip(" .!").title() + "."
return "I don't know your name yet."
return "Tell me more!"
history = []
def chat(text):
history.append({"role": "user", "content": text})
reply = fake_model(history)
history.append({"role": "assistant", "content": reply})
return reply
print(chat("Hi, my name is Priya."))
print(chat("What is my name?"))
# Same question, but sending only the latest message (no history):
print(fake_model([{"role": "user", "content": "What is my name?"}]))Nice to meet you, Priya!
Your name is Priya.
I don't know your name yet.
Forget to send the history and the model "forgets" — because it never had a memory in the first place.
Trimming and summarising
History grows with every turn, and every request pays for all of it in tokens and latency. Once it gets long, apps keep the recent turns verbatim and replace older ones with a summary:
def summarise(messages):
# Stand-in for a model call such as "Summarise the key facts of this conversation in 1-2 lines."
facts = [m["content"] for m in messages if m["role"] == "user"]
return "Earlier the user said: " + " / ".join(facts)
def compact(history, keep_last=4):
if len(history) <= keep_last:
return history
cut = len(history) - keep_last
while history[cut]["role"] != "user": # recent part must start with a user turn
cut -= 1
old, recent = history[:cut], history[cut:]
summary = {"role": "user", "content": f"[Summary of earlier conversation] {summarise(old)}"}
ack = {"role": "assistant", "content": "Understood."}
return [summary, ack] + recent
history = [
{"role": "user", "content": "I'm vegetarian."},
{"role": "assistant", "content": "Noted!"},
{"role": "user", "content": "I have 20 minutes to cook."},
{"role": "assistant", "content": "Quick recipes it is."},
{"role": "user", "content": "Something with chickpeas?"},
{"role": "assistant", "content": "Try a chickpea curry."},
{"role": "user", "content": "Can I use coconut milk?"},
]
for m in compact(history, keep_last=3):
print(f"{m['role']:>9}: {m['content']}") user: [Summary of earlier conversation] Earlier the user said: I'm vegetarian. / I have 20 minutes to cook.
assistant: Understood.
user: Something with chickpeas?
assistant: Try a chickpea curry.
user: Can I use coconut milk?
The while loop makes sure the kept part starts with a user message, so together with the summary and the short acknowledgement the conversation still alternates user / assistant correctly. Summaries are lossy, so for facts that must never be lost, use structured memory instead.
Long-term memory
Some apps remember things across conversations ("the user is vegetarian"). A common design stores short facts in a database and injects the relevant ones into the system prompt of new conversations:
memory_store = {
"user_42": ["Prefers metric units.", "Is vegetarian.", "Cooks for two people."],
}
def system_prompt_for(user_id):
base = "You are a friendly cooking assistant."
facts = memory_store.get(user_id, [])
if not facts:
return base
return base + "\nKnown facts about this user:\n" + "\n".join(f"- {f}" for f in facts)
print(system_prompt_for("user_42"))
print("---")
print(system_prompt_for("new_user"))You are a friendly cooking assistant.
Known facts about this user:
- Prefers metric units.
- Is vegetarian.
- Cooks for two people.
---
You are a friendly cooking assistant.
Store memories only with the user's knowledge, let them view and delete them, and never store sensitive data you don't need (see Privacy & Security).
Design choices
| Approach | Good for | Watch out for |
|---|---|---|
| Full history | short chats | cost grows each turn; window limit |
| Sliding window | long casual chats | early facts disappear |
| Summary + recent turns | long task-focused chats | summaries lose details |
| Retrieved memories (RAG over past chats) | assistants used for months | retrieval misses, privacy |
| Structured user profile | stable preferences | must be kept correct and consented |
Tip: Many providers offer prompt caching, which makes re-sending the same long prefix (system prompt, early history) cheaper and faster. See Cost, Latency & Caching.
Test yourself
How does a chat app make the model 'remember' earlier messages?
- The model stores each user's history internally
- The app sends the conversation history with every request
- The API keeps a session cookie with memory
- The model is retrained after each message
What is the main trade-off of summarising old turns?
- It increases cost
- It saves tokens but can lose details
- It breaks the API
- It makes replies random
Which is a good practice for long-term memory?
- Store everything the user ever said, forever
- Store only needed facts, with the user's knowledge and the ability to delete them
- Put memories in the API key
- Never tell users about memory