Session memory: keeping a conversation continuous
Session memory stores the conversation so far under a session id and rebuilds the prompt on each turn. Use it so a chat feels continuous without keeping every old message in the prompt.
Session memory in 60 seconds
- What: the stored history of one conversation, keyed by a session id.
- How it is used: on each turn, read the history, build a prompt from pinned items and recent turns, call the model, and write the new turn back.
- Best for: chat assistants and multi-step tasks where later messages refer to earlier ones.
- Weak spots: history grows without bound, summaries lose detail, and a session ends, taking its context with it.
- Idea behind it: MemGPT (Packer et al., 2023) borrows virtual memory from operating systems, moving information between a limited main context and external storage.
Where this type fits
In the types of memory hub, short-term memory covers working memory and session memory. Working memory is the window the model reads on one call. Session memory is the store behind it, holding the whole conversation so the window can be rebuilt on every turn. Long-term types such as semantic memory outlive the session. Session memory does not.
The problem it solves
Without stored history, every message is a fresh start. A customer writes 'my order is late' and the assistant asks for the order number. The customer replies '48213' and the assistant, seeing only that number, has no idea what it refers to. The conversation feels broken because the model never saw the first message again.
The simple fix is to resend everything. That works for a few turns, then fails in three ways. The history outgrows the window, which causes errors or silent cuts. Cost rises on each turn, because every old token is billed again. And long histories dilute attention, so the model may miss what matters now.
Session memory solves this by separating what is stored from what is sent. The full history lives in a store, safely and cheaply. For each turn, a small, chosen subset goes into the prompt: pinned items such as the goal, the latest turns in full, and a summary of what came before. The conversation stays continuous while the prompt stays small.
How it works
- Identify the session: each conversation gets a session id, tied to the signed-in user so one person can never read another's history.
- Read history: load the stored turns, any pinned items, and the running summary for that id.
- Build the prompt: place instructions first, then pinned items, then the summary, then the most recent turns that fit the budget, then the new message.
- Call the model: the model answers using only what is in the prompt.
- Write the new turn: append the user message and the reply to the store, with a timestamp and a turn number.
- Compact when needed: when stored turns pass a threshold, summarise the oldest ones into the running summary and mark them as summarised.
- Expire: after a set idle time, close the session and delete or archive its history according to your retention rules.
The store is the centre of the drawing, and the model is only one step in a loop around it. This is why session memory is a property of the application, not the model. The model call is stateless. Everything that feels like memory comes from the read and write steps either side of it.
The same idea appears in MemGPT (Packer et al., 2023), which borrows the virtual memory of an operating system: a limited main context, with information moved in and out of external storage as needed. Session memory is the simplest form of that pattern, with a fixed rule for what moves in. See tiered memory for richer versions.
A worked example
Acme's assistant helps Lena, session s-7731. Turn 1: 'My order is late.' Turn 2: the assistant asks for the order number, and Lena replies '48213'. By turn 12, the stored history is 9,000 tokens, and the prompt budget for history is 2,500.
At turn 13, Lena writes 'Can you change the address instead?' The system loads the record below. It pins Lena's goal and order number. It keeps the last four turns in full, about 900 tokens, and adds a 200 token summary of turns 1 to 8. The model sees that 'instead' refers to the late-order thread about order 48213, and it answers correctly.
{
"session_id": "s-7731",
"user_id": "u-2290",
"pinned": ["Goal: resolve late order", "Order: 48213"],
"summary": "Customer reported order 48213 as late. Carrier shows a delay at the depot. Offered a 5 percent credit; customer has not decided.",
"summarised_through_turn": 8,
"turns": [
{"n": 9, "role": "user", "text": "I will wait a day."},
{"n": 10, "role": "assistant", "text": "Understood. I will note that."},
{"n": 11, "role": "user", "text": "Actually, check the address on file."},
{"n": 12, "role": "assistant", "text": "The address is 12 Elm Road. Is it correct?"}
],
"expires_at": "2026-03-04T10:00:00Z"
}Without the pinned order number, the model would have to rely on the summary alone, and a summary might drop a detail like that. Pinning makes the critical facts survive every compaction. After the reply, turns 13 and 14 are appended. When the stored recent turns pass 12, turns 9 to 12 will be folded into the summary.
Building it
import time
# store, count_tokens(), and llm are placeholders for your own key-value
# store, tokeniser, and model call.
HISTORY_BUDGET = 2500 # tokens of history allowed in the prompt
COMPACT_AFTER = 12 # stored recent turns before we summarise
SESSION_TTL = 30 * 60 # seconds of idle time before the session expires
def load_session(session_id, user_id):
record = store.get(session_id)
if record is None or time.time() > record['expires_at']:
return {'user_id': user_id, 'pinned': [], 'summary': '', 'turns': []}
if record['user_id'] != user_id:
# Never serve another user's history, even with a valid id.
raise PermissionError('session does not belong to this user')
return record
def recent_within_budget(turns, budget):
kept, used = [], 0
for turn in reversed(turns): # newest first
cost = count_tokens(turn['text'])
if used + cost > budget:
break
kept.append(turn)
used += cost
return list(reversed(kept))
def compact(record):
if len(record['turns']) <= COMPACT_AFTER:
return
old, record['turns'] = record['turns'][:-4], record['turns'][-4:]
text = '\n'.join(t['role'] + ': ' + t['text'] for t in old)
# The summary must keep names, numbers, and decisions. Pinned items
# are kept separately in case the summary drops them.
record['summary'] = llm.generate(
'Update this summary. Keep names, numbers, and decisions.\n'
f"Current: {record['summary']}\nNew turns: {text}")
def handle_turn(session_id, user_id, message, instructions):
record = load_session(session_id, user_id)
recent = recent_within_budget(record['turns'], HISTORY_BUDGET)
prompt = '\n\n'.join([
instructions,
'Pinned: ' + '; '.join(record['pinned']),
'Summary: ' + record['summary'],
'\n'.join(t['role'] + ': ' + t['text'] for t in recent),
'user: ' + message,
])
reply = llm.generate(prompt)
record['turns'] += [{'role': 'user', 'text': message}, {'role': 'assistant', 'text': reply}]
compact(record)
record['expires_at'] = time.time() + SESSION_TTL # refresh idle timer
store.put(session_id, record)
return replyTwo checks are easy to forget. The owner check stops a guessed session id from exposing another user's chat. The write happens after the reply, so a failed model call does not leave a half-saved turn. For concurrent requests on one session, add a version number or lock so two writes cannot overwrite each other.
Design decisions
- Storage: default to a key-value store keyed by session id with a time-to-live. It is fast, simple, and expiry comes built in.
- What to send: pinned items, a running summary, and the newest turns that fit a fixed budget. Keep the budget below the full window.
- Summarising: compact in batches rather than every turn, and instruct the summary to keep names, numbers, and decisions.
- Pinning: let the application or the model pin critical facts, so compaction cannot erase them.
- Lifetime: set an idle timeout, such as 30 minutes for chat or days for a support case, and a hard retention limit.
- Access control: bind each session to a user, and check the owner on every read. Never trust the session id alone.
- Concurrency and failure: use versioned writes, save after the reply, and decide what happens if the store is down: fail clearly rather than answer without history.
Measuring it
- Follow-up success: build test chats where turn N depends on turn 1. Measure how often the final answer is right. Compute it as correct answers divided by test chats.
- Fact retention after compaction: list the facts in a conversation, compact it, and check how many facts the summary still holds.
- Prompt tokens per turn: average and 95th percentile. It should plateau as sessions grow, not climb.
- Summary drift: compare a summary of summaries against the original transcript, and flag lost or changed facts.
- Cross-session leakage: run tests with two users and confirm no text from one appears for the other. The target is zero.
- Expiry effects: the share of returning users who restart a task because the session expired.
def fact_retention(facts, summary):
# facts: short strings such as '48213' or '5 percent credit'
kept = [f for f in facts if f.lower() in summary.lower()]
return len(kept) / len(facts) if facts else 1.0When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Chat assistant with follow-up questions | Yes | Later messages depend on earlier ones, so history is essential. |
| Multi-step task such as filling a form | Yes | The state of the task must survive between turns. |
| One-shot questions with no follow-up | No | There is nothing to remember, and storage adds cost. |
| Users who return days later and expect to be known | Not alone | A session expires. Add semantic memory for lasting facts. |
| Very long sessions with many details | Yes, plus tiering | A single summary will lose detail. Consider tiered memory. |
| Sensitive conversations | Yes, with short retention | Keep the history only as long as needed, and apply access rules. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Continuity improves, but summaries can lose or distort details | Pin critical facts and test retention after compaction. |
| Latency | One store read and one write per turn, which is small | Use a fast store and write after the reply is sent. |
| Cost | Resent history raises tokens per turn | Cap the history budget and summarise older turns. |
| Complexity | Needs a store, expiry, compaction, and owner checks | Start with recent turns only, then add summaries when sessions grow. |
| Failure modes | Lost sessions, stale summaries, overwritten turns, and leaked history | Use versioned writes, owner checks, and clear fallback messages. |
Compared with related types
Working memory is what the model reads on this call, while session memory is the stored source it is built from. Semantic memory keeps stable facts about a user across sessions, where session memory keeps the story of one conversation. Tiered memory generalises session memory into several layers with rules for moving items between them.
If your assistant also searches documents, see RAG with memory, which uses history to rewrite follow-up questions before retrieval.
What this means for your role
Common mistakes
Further reading
- Types of memory: the hub that compares every memory type.
- MemGPT, Packer et al., 2023: borrows the idea of an operating system's virtual memory, moving information between a limited main context and external storage.
- Working memory: how to budget the window that session memory feeds.
- RAG with memory: using conversation history to improve retrieval.
Session memory is a simple store with a few firm rules: scope it to the user, keep the prompt small, and let it expire. Get those right and conversations feel continuous at a steady cost.