Chat Memory with an LLM API in Python: History, Token Budget and Summaries
Generative AI course · Build with Gen AI (APIs, RAG) · Estimated reading time: 20 minutes, plus the lab
Kesarwadi Polytechnic builds a small admissions help-desk chatbot for its website. In the first test, a student types “Hello, my name is Asha,” and the bot replies politely. In the very next message she asks, “What is my name?” and the bot says it does not know. The developer is confused, because ChatGPT always remembers the earlier messages. The reason is simple: the ChatGPT app keeps the conversation for you, but a chat API does not. Every API request starts from zero, and your own code must decide what the model sees each time. In this chapter we build that memory step by step in plain Python, keep it inside a token budget, and test everything offline.
What you will learn in this chapter
- You will understand why a chat API forgets earlier messages and what the official documentation says about it.
- You will send the conversation history with every request in the correct order.
- You will estimate tokens and plan an input budget that leaves room for the reply.
- You will drop the oldest turns safely when the history no longer fits.
- You will pin a few small facts and summarise old turns so that important details are not lost.
- You will save and reload a session safely, with basic masking of personal details.
Everything in this chapter is made up for learning
Synthetic classroom data only. Kesarwadi Polytechnic, the student Asha, her messages, the e-mail address and the phone number in the lab are all fictional and hand typed. The lab uses a fake model called FakeChatModel, which is not a real AI model. It can only answer from the messages that it is sent, which is exactly how a stateless chat API behaves. The lab needs no API key, no internet and no installation beyond Python. All token numbers in the demo are rough estimates, not real counts or prices from any provider.
1. Why the chatbot forgets: each API request starts from zero
A chat API is stateless. That means the server does not keep your earlier messages for the next request unless you use a special feature that asks it to. We checked the official pages on 17 November 2026 (IST), and they say this clearly.
- OpenAI's conversation state guide says that each text generation request is independent and stateless, and that you can build a multi-turn conversation by sending the earlier messages as part of the request.
- Anthropic's guide to working with messages says that the Messages API is stateless, which means you always send the full conversation history to the API.
- Google's Gemini text generation guide describes a stateless mode in which you keep the conversation history on your side and send it in each request, and a stateful mode that links a new turn to the previous one.
| Request | Messages sent to the model | Reply from the fake model |
|---|---|---|
| Turn 1 | The instructions, then “Hello, my name is Asha.” | Noted. |
| Turn 2 without history | The instructions, then “What is my name?” | Sorry, I do not know your name yet. |
| Turn 2 with history | The instructions, turn 1 and its reply, then “What is my name?” | Your name is Asha. |
The second row is the bug that the polytechnic saw. The third row is the fix: the earlier messages travel with the new question, so the model can read them again.
Ravindra Bagale's Tip
Before you write any memory code, test the plain API once with two separate calls. Tell it your name in the first call, and ask for your name in the second call without sending the first one again. When the model says it does not know, you will never again forget that the history is your job, not the model's.
Ravindra Bagale's Tip – मराठी
Memory चा code लिहायच्या आधी साधा API एकदा दोन वेगळ्या calls ने test करा. पहिल्या call मध्ये तुमचं नाव सांगा, आणि दुसऱ्या call मध्ये पहिला message परत न पाठवता नाव विचारा. Model म्हणेल की त्याला माहीत नाही, आणि मग तुम्ही कधीच विसरणार नाही की history सांभाळणं हे तुमचं काम आहे, model चं नाही.
Ravindra Bagale's Tip – हिंदी
Memory का code लिखने से पहले सादा API एक बार दो अलग calls से test करो. पहले call में अपना नाम बताओ, और दूसरे call में पहला message दोबारा भेजे बिना नाम पूछो. Model बोलेगा कि उसे नहीं पता, और फिर तुम कभी नहीं भूलोगे कि history संभालना तुम्हारा काम है, model का नहीं.
2. Three ways to keep a conversation going
There are three common ways to give a model the earlier messages. In the first way your code keeps the history and sends it every time. In the second way you pass the id of the previous response, and the provider finds the history for you. In the third way you create a long-lived conversation object on the provider's side. The table below lists only facts that the official pages stated when we checked them on 17 November 2026 (IST).
| Way | Who keeps the history | What the official page says about cost or storage |
|---|---|---|
| Send the history yourself (OpenAI, Anthropic and Gemini all support this) | Your app keeps it and sends it in every request. | Anthropic says you always send the full history. Gemini's stateless mode asks you to set store to false and keep the history on your side. |
Chain to the previous response with previous_response_id (OpenAI) or previous_interaction_id (Gemini) | The provider keeps it, and you send only the new message and the previous id. | OpenAI says that all earlier input tokens in the chain are still billed as input tokens. OpenAI stores response objects for 30 days by default. Gemini stores interactions for 55 days on the paid tier and 1 day on the free tier by default, and setting store to false stops you from using the previous id. |
| A conversation object (the OpenAI Conversations API) | The provider keeps it as a durable object with its own id. | OpenAI says conversation objects and their items are not subject to the 30-day limit. |
Two more details from the same pages are easy to miss. OpenAI says the 30-day storage of responses can be turned off by setting store to false. Google says that previous_interaction_id carries only the conversation history, so the system instruction, the tools and the generation settings must be sent again in every new interaction. In this chapter we use the first way, because it works with every provider, it runs offline, and it shows you exactly what the model receives.
3. The message list: instructions, user and assistant
A conversation is a list of messages in time order. Each message has a role and some text. The lab keeps the list in a provider-neutral shape and converts it at the last moment, because each provider places the instructions in a slightly different field.
| Role in the lab | What it holds | Where it goes in a real request |
|---|---|---|
| system | The bot's fixed instructions, plus any pinned facts and the summary of older turns. | OpenAI's Responses API takes it in the instructions field, Anthropic's Messages API takes it in the top-level system field, and Gemini takes it as system_instruction. |
| user | Each message typed by the student. | A message with the role user. |
| assistant | Each earlier reply from the bot. | A message with the role assistant. Gemini's own format calls the model's turns by different names, so follow its guide for the exact shape. |
The functions to_openai_input() and to_anthropic() in the lab split the list into the instructions and the remaining messages. They return copies, so changing the request can never change the stored conversation by accident.
4. Why every turn costs more than the last one
When you send the full history, each request carries all the earlier messages plus the new one. The input therefore grows with every turn, and you pay for the whole input on every request. The lab prints the estimated input tokens for each of Asha's nine synthetic messages.
| Turn | Asha's new message (synthetic) | Estimated input tokens |
|---|---|---|
| 1 | Hello, my name is Asha. | 38 |
| 2 | I want to apply for the Computer Engineering diploma. | 66 |
| 3 | What documents do I need for admission? | 90 |
| 4 | Is there a hostel for girls? | 111 |
| 5 | What is the last date for the form? | 134 |
| 6 | Can I pay the fee in two parts? | 156 |
| 7 | Is the library open on Sunday? | 178 |
| 8 | Do you have a bus from Shivajinagar? | 201 |
| 9 | My e-mail is ... and phone ... (masked before storage) | 229 |
| Total | All nine requests together | 1,203 |
The last turn needs about six times the input of the first turn, and the nine requests together carry an estimated 1,203 input tokens. A real chat with long answers grows much faster. The official pages also say that the context window covers more than the input. OpenAI says it includes input, output and reasoning tokens, and Anthropic says everything in the request counts, including the system prompt, every message, tool definitions and the reply itself.
The lab estimates tokens with a simple rule of about four characters per token, plus four extra tokens per message for the role markers. Google's token counting page gives the four-characters rule for Gemini models. Other models count differently, and Marathi or Hindi text often needs more tokens than English, as the tokens and context window chapter shows. For real numbers, read the usage fields in each API response, or use the provider's token counting tool before you send a request.
5. Plan a token budget before you trim anything
A token budget is the largest input that your app will send in one request. It should be much smaller than the model's real context window, because long inputs cost more, run slower and can make answers worse. Anthropic's context window page even warns that accuracy and recall can drop as the token count grows. Work out the budget in these steps.
- Choose a limit for the whole request that suits your cost and speed, and keep it well below the model's published context window.
- Decide the largest reply you allow, and set that as the output token limit on the request.
- Keep a small safety margin, because your token estimate is only a guess.
- Subtract the reply limit and the margin from the request limit. What is left is the input budget for the instructions, the history and the new message.
| Part of the budget | Tokens in the lab |
|---|---|
Limit for the whole request (the lab calls it context_window) | 330 |
Space kept for the reply (max_output_tokens) | 100 |
| Safety margin | 50 |
| Input budget that is left for instructions, history and the new message | 180 |
Real apps use far bigger numbers. The lab uses tiny ones only so that you can see trimming after a few short messages.
6. Drop the oldest turns safely when the history is too long
The simplest way to stay inside the budget is a sliding window, which means the newest turns stay and the oldest turns fall away. Our function build_messages() follows these rules in order.
- It always keeps the system message and the new user message. If those two alone do not fit, it raises
MessageTooLonginstead of sending a broken request. - It walks backwards from the newest turn to the oldest turn.
- It adds a whole turn at a time, meaning the user message together with the reply that followed it, so the model never sees a reply without its question.
- It stops at the first turn that would go over the budget, so the kept turns are always the most recent ones in their original order.
- It returns the messages, the number of dropped turns and the estimated input tokens, and it never changes the stored conversation.
In the demo, the budget of 180 input tokens keeps the six newest turns and drops the three oldest. The first turn was “Hello, my name is Asha,” so when Asha asks for her name again, the fake model answers, “Sorry, I do not know your name yet.” Trimming saved tokens, but it threw away the most important fact in the chat.
Be careful with reasoning models and tools
This simple text history matches the manual example in OpenAI's conversation state guide. If your model uses reasoning or calls tools, the providers ask for more care. OpenAI's guide says to keep every item from the response's output when you replay a stateless reasoning request, and Google's guide says that thought and function call steps must be sent back exactly as received. Do not cut such items by hand. Use the provider's own state or compaction feature instead, as section 8 explains.
Ravindra Bagale's Tip
Print the number of dropped turns on every request while you are testing. If you suddenly see a big number, open the history and check what was thrown away. Very often it is the student's name or the first question, and that is exactly the moment to pin a fact or write a summary.
Ravindra Bagale's Tip – मराठी
Testing करताना प्रत्येक request ला किती turns drop झाले ते print करा. अचानक मोठा आकडा दिसला, तर history उघडा आणि काय फेकलं गेलं ते बघा. बऱ्याच वेळा ते student चं नाव किंवा पहिला प्रश्न असतो, आणि तीच वेळ आहे fact pin करायची किंवा summary लिहायची.
Ravindra Bagale's Tip – हिंदी
Testing के समय हर request पर कितने turns drop हुए वो print करो. अचानक बड़ा number दिखे, तो history खोलो और देखो क्या फेंका गया. ज़्यादातर वो student का नाम या पहला सवाल होता है, और वही समय है fact pin करने का या summary लिखने का.
7. Pin a few small facts that must never be dropped
Some details matter for the whole chat, such as the student's name, the course and the preferred language. The lab keeps these in a small dictionary called facts and adds them to the system message on every request, so the sliding window can never remove them.
- The method
remember()accepts only keys from an allowed list, which in the lab is name, course and language. Anything else, such as an identity number, is refused with an error. - Each value is masked for e-mail addresses and phone numbers and cut to 60 characters, so one long value cannot fill the budget.
- The facts are written into the system message as one short sentence.
In the demo, after we pin the name and the course, the same tiny budget now drops four turns instead of three, because the system message became a little longer. Even so, the fake model answers, “Your name is Asha,” because the name now travels inside the system message.
8. Summarise old turns instead of throwing them away
Pinned facts work for a few known details, but a long chat also contains decisions and questions that nobody planned for. A rolling summary keeps the gist of the old turns in a few lines. This is often called compaction. Our function compact() works in these steps.
- It keeps the newest turns, two in the demo, exactly as they are.
- It passes the older turns and the previous summary to a summariser function.
- It stores the new summary in the conversation and removes the old turns from the list.
- It cuts the summary to a fixed size, 90 estimated tokens by default, so the summary itself cannot grow without limit.
In a real app the summariser is one more model call with an instruction such as “Summarise these turns in three short lines, and keep names, dates and decisions.” The lab uses fake_summarize(), which simply keeps the start of each old user message, so the output is the same on every run. In the demo, seven turns move into the summary and two remain. When Asha then asks which course she enquired about, the answer is still correct, because the summary and the pinned facts both carry it.
Providers also offer this on their servers. OpenAI's compaction guide describes server-side compaction that runs when the token count crosses a threshold that you set. Anthropic's compaction overview says that compaction replaces older turns with a summary written on the server. Check which models support it on the day you build, because these features are new and change often.
| Technique | What it keeps | What it can lose | When to use it |
|---|---|---|---|
| Sliding window | The newest turns, word for word. | Everything older, including early facts. | Short chats where only recent messages matter. |
| Pinned facts | A few planned details, such as the name and the course. | Anything that was not on the allowed list. | Details that the bot needs in every answer. |
| Rolling summary | The gist of the older turns. | Exact wording and small details that the summary skipped. | Long chats, together with a sliding window for the newest turns. |
One more cost detail is worth knowing. OpenAI's prompt caching guide says that cache reuse needs the whole starting part of the prompt to match. Pinned facts and the summary sit inside the system message at the very start, so update them in occasional bigger steps rather than on every single turn.
9. Save and resume a session safely
A real chatbot must remember a conversation after the page reloads or the server restarts. The lab saves each conversation as one JSON file and loads it again later.
- The session id must match a strict pattern of 1 to 64 letters, digits, hyphens or underscores. An id such as “../other-student” is refused, so one student can never open another student's file by changing the id.
- The function
save_session()writes to a temporary file first, forces it onto the disk, and then renames it withos.replace(). The Python os documentation says that a successful rename is atomic on POSIX systems, so a crash never leaves half a file behind. - The function
load_session()rebuilds the conversation, including its facts and summary, and the bot carries on as if nothing happened. - Every user message and reply is masked by
redact()before it is stored, which replaces e-mail addresses and 10-digit mobile numbers with a placeholder.
The masking in the lab is basic, and it will miss many kinds of personal data, such as addresses or numbers written with spaces. The OWASP page on sensitive information disclosure lists personal information, financial details, health records and security credentials as sensitive data that LLM applications can leak, so treat the lab as a starting point and not as complete protection.
| Store this | Avoid storing this |
|---|---|
| The fixed instructions and the session id. | API keys, passwords or one-time codes, even if a user pastes them. |
| A few pinned facts from an allowed list. | Identity numbers, bank details or health details that the bot does not need. |
| The recent turns and a short summary, after masking. | Full raw chats kept forever with no way to delete them. |
| The token usage of each request, for cost tracking. | One shared history file for all users. |
Ravindra Bagale's Tip
Ask yourself one question before you save a chat to disk: would this student be comfortable if they saw this exact file? Keep only what the bot really needs, mask phone numbers and e-mail addresses, and give the student a simple way to delete the whole session.
Ravindra Bagale's Tip – मराठी
Chat disk वर save करण्याआधी स्वतःला एक प्रश्न विचारा: हीच file त्या student ने बघितली तर त्याला चालेल का? Bot ला खरंच लागणारं तेवढंच ठेवा, phone numbers आणि e-mail addresses लपवा, आणि student ला पूर्ण session delete करायचा सोपा मार्ग द्या.
Ravindra Bagale's Tip – हिंदी
Chat को disk पर save करने से पहले खुद से एक सवाल पूछो: अगर वो student यही file देखे तो क्या उसे ठीक लगेगा? Bot को सच में जो चाहिए बस उतना ही रखो, phone numbers और e-mail addresses छुपाओ, और student को पूरा session delete करने का आसान तरीका दो.
10. Run the offline lab
Save the two files below in one folder. Use Python 3.9 or newer. No package installation is needed. Run python3 -B chat_memory.py to see the demo, then run python3 -B -m unittest -v test_chat_memory. You should see 46 tests pass. The demo creates a folder called lab_sessions next to the script, so you can open the saved session file afterwards.
Demo output (synthetic)
== 1. Stateless: each call is new
turn 1 reply: Noted. (simulated reply)
turn 2 without history: Sorry, I do not know your name yet.
turn 2 with history: Your name is Asha.
== 2. Full history: input tokens grow every turn
input tokens per turn: [38, 66, 90, 111, 134, 156, 178, 201, 229]
total billed input tokens for 9 turns: 1203
stored turn 9: My e-mail is [email removed] and phone [phone removed].
== 3. Small budget: oldest turns are dropped
dropped 3 old turns, kept 14 messages, 175 input tokens
reply without pinned facts: Sorry, I do not know your name yet.
with pinned facts: dropped 4, 175 input tokens
reply with pinned facts: Your name is Asha.
== 4. Compact old turns into a summary
moved 7 turns into the summary; 2 turns left
summary: Hello, my name is Asha; I want to apply for the Computer Engineering diploma; What documents do I need for admission; Is there a hostel for girls; What is the last date for the form; Can I pay the fee in two parts; Is the library open on Sunday.
after compaction: dropped 1, 159 input tokens
reply: You asked about the Computer Engineering diploma.
== 5. Save and resume the session
saved to student-S104.json | reply after reload: Your name is Asha.
blocked session id: bad session id
Test runner tail
Ran 46 tests in 0.030s
OK
Read the demo from top to bottom. Part 1 shows that the model forgets when the history is not sent. Part 2 shows the input growing on every turn, and it also shows that the e-mail address and phone number in turn 9 were masked before storage. Part 3 shows trimming losing the name and a pinned fact bringing it back. Part 4 moves seven turns into a summary. Part 5 saves the session, reloads it and refuses a session id that tries to leave the folder.
chat_memory.py
"""Chat memory for an LLM API, offline lab (SYNTHETIC data, no API key, no internet).
Kesarwadi Polytechnic and the student "Asha" are made up for this lesson.
FakeChatModel is NOT a real AI model: it only answers from the messages it is sent,
which is exactly how a stateless chat API behaves.
"""
import json, math, os, re, tempfile
CHARS_PER_TOKEN = 4 # rough planning rule only; real tokenizers differ
MESSAGE_OVERHEAD = 4 # rough extra tokens per message for role markers
SESSION_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
ALLOWED_FACTS = ("name", "course", "language")
class MessageTooLong(Exception):
"""The instructions plus the new message do not fit in the input budget."""
def estimate_tokens(text):
"""Rough token estimate: about 4 characters per token, rounded up."""
return math.ceil(len(text) / CHARS_PER_TOKEN) if text else 0
def message_tokens(msg):
return estimate_tokens(msg["content"]) + MESSAGE_OVERHEAD
def redact(text):
"""Basic masking of e-mail addresses and 10-digit mobile numbers. NOT complete."""
text = re.sub(r"[\w.+-]+@[\w-]+(\.[\w-]+)+", "[email removed]", text)
return re.sub(r"(?<!\d)(\+91[ -]?)?[6-9]\d{9}(?!\d)", "[phone removed]", text)
class Conversation:
"""Everything your app stores for one chat session."""
def __init__(self, instructions):
self.instructions = instructions
self.facts = {} # small pinned facts that must never be trimmed
self.summary = "" # short summary of turns that were moved out
self.turns = [] # list of [user_msg, assistant_msg] pairs
def add_turn(self, user_text, assistant_text):
self.turns.append([{"role": "user", "content": redact(user_text)},
{"role": "assistant", "content": redact(assistant_text)}])
def remember(self, key, value):
if key not in ALLOWED_FACTS:
raise ValueError(f"fact '{key}' is not on the allowed list")
self.facts[key] = redact(str(value))[:60]
def to_dict(self):
return {"instructions": self.instructions, "facts": self.facts,
"summary": self.summary, "turns": self.turns}
@classmethod
def from_dict(cls, d):
c = cls(d["instructions"])
c.facts, c.summary, c.turns = dict(d["facts"]), d["summary"], [list(t) for t in d["turns"]]
return c
def system_text(conv):
parts = [conv.instructions]
if conv.facts:
parts.append("Known facts about this student: " +
"; ".join(f"{k} = {v}" for k, v in sorted(conv.facts.items())) + ".")
if conv.summary:
parts.append("Summary of earlier conversation: " + conv.summary)
return "\n".join(parts)
def build_messages(conv, user_text, context_window, max_output_tokens, margin=50, use_memory=True):
"""Return (messages, dropped_turn_count, input_tokens) that fit the budget.
Budget for input = context_window - max_output_tokens - margin.
The system message and the new user message are always kept.
Older turns are added newest first, as whole user+assistant pairs, while they fit.
"""
budget = context_window - max_output_tokens - margin
system = {"role": "system", "content": system_text(conv) if use_memory else conv.instructions}
new = {"role": "user", "content": redact(user_text)}
used = message_tokens(system) + message_tokens(new)
if used > budget:
raise MessageTooLong(f"needs {used} tokens but the input budget is {budget}")
kept = []
for pair in reversed(conv.turns):
cost = sum(message_tokens(m) for m in pair)
if used + cost > budget:
break
kept.insert(0, pair)
used += cost
dropped = len(conv.turns) - len(kept)
messages = [system] + [m for pair in kept for m in pair] + [new]
return messages, dropped, used
def compact(conv, summarize, keep_last=2, max_summary_tokens=90):
"""Move all but the last `keep_last` turns into conv.summary using `summarize`."""
if len(conv.turns) <= keep_last:
return 0
old = conv.turns[:-keep_last] if keep_last else conv.turns[:]
conv.turns = conv.turns[len(old):]
text = summarize(conv.summary, old)
limit = max_summary_tokens * CHARS_PER_TOKEN
conv.summary = text if len(text) <= limit else text[:limit - 3].rstrip() + "..."
return len(old)
def fake_summarize(previous_summary, old_turns):
"""Stand-in for a model call that writes a summary. Keeps each old user message, shortened."""
notes = [pair[0]["content"].rstrip(".?!")[:60] for pair in old_turns]
return "; ".join(([previous_summary.rstrip(".")] if previous_summary else []) + notes) + "."
class FakeChatModel:
"""SIMULATED model. It can only use what is inside `messages`, like a stateless API."""
def __init__(self):
self.calls, self.billed_input_tokens = 0, 0
def reply(self, messages):
self.calls += 1
self.billed_input_tokens += sum(message_tokens(m) for m in messages)
question = messages[-1]["content"].lower()
everything = " ".join(m["content"] for m in messages[:-1])
if "what is my name" in question:
m = re.search(r"(?:my name is |name = )([A-Z][a-z]+)", everything)
return f"Your name is {m.group(1)}." if m else "Sorry, I do not know your name yet."
if "which course" in question:
m = re.search(r"(?:apply for the |course = )([A-Za-z ]+?) (?:course|diploma)", everything)
return f"You asked about the {m.group(1)} diploma." if m else "Sorry, I do not know which course you mean."
return "Noted. (simulated reply)"
def to_openai_input(messages):
"""Shape for the OpenAI Responses API: instructions string + input list."""
return messages[0]["content"], [dict(m) for m in messages[1:]]
def to_anthropic(messages):
"""Shape for the Anthropic Messages API: separate system string + messages list."""
return messages[0]["content"], [dict(m) for m in messages[1:]]
def save_session(conv, folder, session_id):
if not SESSION_ID_RE.match(session_id):
raise ValueError("bad session id")
os.makedirs(folder, exist_ok=True)
path = os.path.join(folder, session_id + ".json")
fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(conv.to_dict(), f, ensure_ascii=False, indent=1)
f.flush(); os.fsync(f.fileno())
os.replace(tmp, path)
return path
def load_session(folder, session_id):
if not SESSION_ID_RE.match(session_id):
raise ValueError("bad session id")
with open(os.path.join(folder, session_id + ".json"), encoding="utf-8") as f:
return Conversation.from_dict(json.load(f))
INSTRUCTIONS = "You are the admissions help-desk assistant of Kesarwadi Polytechnic (made up). Answer briefly."
CHAT = [ # SYNTHETIC student messages
"Hello, my name is Asha.",
"I want to apply for the Computer Engineering diploma.",
"What documents do I need for admission?",
"Is there a hostel for girls?",
"What is the last date for the form?",
"Can I pay the fee in two parts?",
"Is the library open on Sunday?",
"Do you have a bus from Shivajinagar?",
"My e-mail is asha.test@example.com and phone 9876543210.",
]
def demo(folder="lab_sessions"):
model = FakeChatModel()
print("== 1. Stateless: each call is new")
first = [{"role": "system", "content": INSTRUCTIONS}, {"role": "user", "content": CHAT[0]}]
print("turn 1 reply:", model.reply(first))
second = [{"role": "system", "content": INSTRUCTIONS}, {"role": "user", "content": "What is my name?"}]
print("turn 2 without history:", model.reply(second))
print("turn 2 with history: ",
model.reply(first + [{"role": "assistant", "content": "Noted. (simulated reply)"},
{"role": "user", "content": "What is my name?"}]))
print("== 2. Full history: input tokens grow every turn")
conv, model = Conversation(INSTRUCTIONS), FakeChatModel()
sizes = []
for text in CHAT:
msgs, _, used = build_messages(conv, text, context_window=100000, max_output_tokens=200)
conv.add_turn(text, model.reply(msgs))
sizes.append(used)
print("input tokens per turn:", sizes)
print("total billed input tokens for 9 turns:", model.billed_input_tokens)
print("stored turn 9:", conv.turns[-1][0]["content"])
print("== 3. Small budget: oldest turns are dropped")
msgs, dropped, used = build_messages(conv, "What is my name?", context_window=330,
max_output_tokens=100, use_memory=False)
print(f"dropped {dropped} old turns, kept {len(msgs)} messages, {used} input tokens")
print("reply without pinned facts:", model.reply(msgs))
conv.remember("name", "Asha")
conv.remember("course", "Computer Engineering diploma")
msgs, dropped, used = build_messages(conv, "What is my name?", context_window=330, max_output_tokens=100)
print(f"with pinned facts: dropped {dropped}, {used} input tokens")
print("reply with pinned facts: ", model.reply(msgs))
print("== 4. Compact old turns into a summary")
moved = compact(conv, fake_summarize, keep_last=2)
print(f"moved {moved} turns into the summary; {len(conv.turns)} turns left")
print("summary:", conv.summary)
msgs, dropped, used = build_messages(conv, "Which course did I ask about?", context_window=330, max_output_tokens=100)
print(f"after compaction: dropped {dropped}, {used} input tokens")
print("reply:", model.reply(msgs))
print("== 5. Save and resume the session")
path = save_session(conv, folder, "student-S104")
again = load_session(folder, "student-S104")
msgs, _, _ = build_messages(again, "What is my name?", context_window=330, max_output_tokens=100)
print("saved to", os.path.basename(path), "| reply after reload:", model.reply(msgs))
try:
load_session(folder, "../other-student")
except ValueError as e:
print("blocked session id:", e)
if __name__ == "__main__":
demo(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lab_sessions"))
test_chat_memory.py
"""Tests for chat_memory.py (offline, synthetic). Run: python3 -B -m unittest -v test_chat_memory"""
import json, os, tempfile, unittest
import chat_memory as cm
def filled(n=9):
conv, model = cm.Conversation(cm.INSTRUCTIONS), cm.FakeChatModel()
for text in cm.CHAT[:n]:
msgs, _, _ = cm.build_messages(conv, text, 100000, 200)
conv.add_turn(text, model.reply(msgs))
return conv
class TestTokens(unittest.TestCase):
def test_empty_is_zero(self):
self.assertEqual(cm.estimate_tokens(""), 0)
def test_rounds_up(self):
self.assertEqual(cm.estimate_tokens("abcde"), 2)
def test_four_chars_is_one(self):
self.assertEqual(cm.estimate_tokens("abcd"), 1)
def test_message_overhead(self):
self.assertEqual(cm.message_tokens({"role": "user", "content": "abcd"}), 1 + cm.MESSAGE_OVERHEAD)
class TestRedact(unittest.TestCase):
def test_email(self):
self.assertEqual(cm.redact("mail a.b@example.com now"), "mail [email removed] now")
def test_mobile(self):
self.assertIn("[phone removed]", cm.redact("call 9876543210"))
def test_mobile_with_code(self):
self.assertEqual(cm.redact("call +91 9876543210"), "call [phone removed]")
def test_short_number_kept(self):
self.assertEqual(cm.redact("room 12345"), "room 12345")
def test_longer_number_kept(self):
self.assertEqual(cm.redact("id 98765432101234"), "id 98765432101234")
class TestStateless(unittest.TestCase):
def test_forgets_without_history(self):
m = cm.FakeChatModel()
r = m.reply([{"role": "system", "content": cm.INSTRUCTIONS}, {"role": "user", "content": "What is my name?"}])
self.assertIn("do not know", r)
def test_remembers_with_history(self):
m = cm.FakeChatModel()
msgs = [{"role": "system", "content": cm.INSTRUCTIONS}, {"role": "user", "content": "Hello, my name is Asha."},
{"role": "assistant", "content": "Noted."}, {"role": "user", "content": "What is my name?"}]
self.assertEqual(m.reply(msgs), "Your name is Asha.")
def test_billing_counts_every_call(self):
m = cm.FakeChatModel()
msgs = [{"role": "user", "content": "abcd"}]
m.reply(msgs); m.reply(msgs)
self.assertEqual(m.calls, 2)
self.assertEqual(m.billed_input_tokens, 2 * (1 + cm.MESSAGE_OVERHEAD))
class TestBuildMessages(unittest.TestCase):
def test_order_system_first_user_last(self):
conv = filled(3)
msgs, _, _ = cm.build_messages(conv, "Next?", 100000, 200)
self.assertEqual(msgs[0]["role"], "system")
self.assertEqual(msgs[-1], {"role": "user", "content": "Next?"})
def test_big_window_keeps_everything(self):
conv = filled()
msgs, dropped, _ = cm.build_messages(conv, "Next?", 100000, 200)
self.assertEqual(dropped, 0)
self.assertEqual(len(msgs), 2 + 2 * len(conv.turns))
def test_roles_alternate(self):
msgs, _, _ = cm.build_messages(filled(), "Next?", 330, 100)
roles = [m["role"] for m in msgs[1:]]
self.assertEqual(roles, ["user", "assistant"] * ((len(roles) - 1) // 2) + ["user"])
def test_small_window_drops_oldest(self):
conv = filled()
msgs, dropped, _ = cm.build_messages(conv, "Next?", 330, 100, use_memory=False)
self.assertGreater(dropped, 0)
self.assertEqual(msgs[1], conv.turns[dropped][0])
def test_never_over_budget(self):
conv = filled()
for window in range(150, 600, 7):
try:
msgs, _, used = cm.build_messages(conv, "Next?", window, 100)
except cm.MessageTooLong:
continue
self.assertLessEqual(used, window - 100 - 50)
self.assertEqual(used, sum(cm.message_tokens(m) for m in msgs))
def test_whole_pairs_only(self):
msgs, _, _ = cm.build_messages(filled(), "Next?", 300, 100)
self.assertEqual((len(msgs) - 2) % 2, 0)
def test_too_long_raises(self):
with self.assertRaises(cm.MessageTooLong):
cm.build_messages(cm.Conversation("x"), "y" * 2000, 300, 100)
def test_does_not_change_conversation(self):
conv = filled()
before = json.dumps(conv.to_dict())
cm.build_messages(conv, "Next?", 300, 100)
self.assertEqual(before, json.dumps(conv.to_dict()))
def test_new_message_is_redacted(self):
msgs, _, _ = cm.build_messages(cm.Conversation("x"), "phone 9876543210", 1000, 100)
self.assertEqual(msgs[-1]["content"], "phone [phone removed]")
def test_tokens_grow_with_full_history(self):
conv, model, sizes = cm.Conversation(cm.INSTRUCTIONS), cm.FakeChatModel(), []
for text in cm.CHAT:
msgs, _, used = cm.build_messages(conv, text, 100000, 200)
conv.add_turn(text, model.reply(msgs)); sizes.append(used)
self.assertEqual(sizes, sorted(sizes))
self.assertEqual(model.billed_input_tokens, sum(sizes))
class TestFacts(unittest.TestCase):
def test_pinned_fact_survives_trimming(self):
conv = filled()
conv.remember("name", "Asha")
msgs, dropped, _ = cm.build_messages(conv, "What is my name?", 330, 100)
self.assertGreater(dropped, 0)
self.assertEqual(cm.FakeChatModel().reply(msgs), "Your name is Asha.")
def test_without_fact_name_is_lost(self):
msgs, _, _ = cm.build_messages(filled(), "What is my name?", 330, 100, use_memory=False)
self.assertIn("do not know", cm.FakeChatModel().reply(msgs))
def test_unknown_fact_rejected(self):
with self.assertRaises(ValueError):
cm.Conversation("x").remember("aadhaar", "1234")
def test_fact_is_redacted_and_short(self):
c = cm.Conversation("x")
c.remember("name", "Asha 9876543210 " + "x" * 100)
self.assertNotIn("9876543210", c.facts["name"])
self.assertLessEqual(len(c.facts["name"]), 60)
def test_facts_in_system_text(self):
c = cm.Conversation("Base.")
c.remember("course", "Civil diploma")
self.assertIn("course = Civil diploma", cm.system_text(c))
def test_stored_turn_redacted(self):
c = cm.Conversation("x")
c.add_turn("mail me at a@b.co", "ok")
self.assertEqual(c.turns[0][0]["content"], "mail me at [email removed]")
class TestCompact(unittest.TestCase):
def test_keeps_last_turns(self):
conv = filled()
last = conv.turns[-2:]
moved = cm.compact(conv, cm.fake_summarize, keep_last=2)
self.assertEqual(moved, 7)
self.assertEqual(conv.turns, last)
def test_nothing_to_compact(self):
conv = filled(2)
self.assertEqual(cm.compact(conv, cm.fake_summarize, keep_last=2), 0)
self.assertEqual(conv.summary, "")
def test_keep_zero_moves_all(self):
conv = filled(3)
self.assertEqual(cm.compact(conv, cm.fake_summarize, keep_last=0), 3)
self.assertEqual(conv.turns, [])
def test_summary_is_capped(self):
conv = filled()
cm.compact(conv, lambda prev, old: "z" * 5000, keep_last=1, max_summary_tokens=10)
self.assertLessEqual(len(conv.summary), 40)
self.assertTrue(conv.summary.endswith("..."))
def test_summary_builds_on_previous(self):
conv = filled()
cm.compact(conv, cm.fake_summarize, keep_last=5)
first = conv.summary.rstrip(".")
cm.compact(conv, cm.fake_summarize, keep_last=2)
self.assertTrue(conv.summary.startswith(first))
def test_course_answer_after_compaction(self):
conv = filled()
cm.compact(conv, cm.fake_summarize, keep_last=2)
msgs, _, _ = cm.build_messages(conv, "Which course did I ask about?", 330, 100)
self.assertEqual(cm.FakeChatModel().reply(msgs), "You asked about the Computer Engineering diploma.")
def test_summary_in_system_message(self):
conv = filled()
cm.compact(conv, cm.fake_summarize, keep_last=2)
msgs, _, _ = cm.build_messages(conv, "Hi", 1000, 100)
self.assertIn("Summary of earlier conversation:", msgs[0]["content"])
class TestSessions(unittest.TestCase):
def setUp(self):
self.dir = tempfile.mkdtemp()
def test_round_trip(self):
conv = filled(4); conv.remember("name", "Asha"); conv.summary = "s"
cm.save_session(conv, self.dir, "student-S104")
again = cm.load_session(self.dir, "student-S104")
self.assertEqual(again.to_dict(), conv.to_dict())
def test_bad_id_on_save(self):
with self.assertRaises(ValueError):
cm.save_session(cm.Conversation("x"), self.dir, "../x")
def test_bad_id_on_load(self):
for bad in ("../other", "a/b", "", "x" * 65, "a b"):
with self.assertRaises(ValueError):
cm.load_session(self.dir, bad)
def test_no_temp_files_left(self):
cm.save_session(cm.Conversation("x"), self.dir, "s1")
self.assertEqual(os.listdir(self.dir), ["s1.json"])
def test_overwrite_is_whole_file(self):
cm.save_session(filled(5), self.dir, "s1")
cm.save_session(cm.Conversation("short"), self.dir, "s1")
self.assertEqual(cm.load_session(self.dir, "s1").instructions, "short")
def test_sessions_are_separate(self):
a, b = cm.Conversation("x"), cm.Conversation("x")
a.remember("name", "Asha"); b.remember("name", "Ravi")
cm.save_session(a, self.dir, "s-a"); cm.save_session(b, self.dir, "s-b")
self.assertEqual(cm.load_session(self.dir, "s-a").facts["name"], "Asha")
self.assertEqual(cm.load_session(self.dir, "s-b").facts["name"], "Ravi")
def test_unicode_kept(self):
c = cm.Conversation("x"); c.add_turn("माझं नाव आशा आहे", "ठीक आहे")
cm.save_session(c, self.dir, "mr")
self.assertEqual(cm.load_session(self.dir, "mr").turns[0][0]["content"], "माझं नाव आशा आहे")
class TestAdapters(unittest.TestCase):
def test_openai_shape(self):
msgs, _, _ = cm.build_messages(filled(2), "Hi", 1000, 100)
instructions, items = cm.to_openai_input(msgs)
self.assertEqual(instructions, msgs[0]["content"])
self.assertEqual([m["role"] for m in items], ["user", "assistant", "user", "assistant", "user"])
def test_anthropic_shape(self):
msgs, _, _ = cm.build_messages(filled(1), "Hi", 1000, 100)
system, items = cm.to_anthropic(msgs)
self.assertNotIn("system", [m["role"] for m in items])
self.assertEqual(items[0]["role"], "user")
def test_adapters_copy(self):
msgs, _, _ = cm.build_messages(filled(1), "Hi", 1000, 100)
_, items = cm.to_openai_input(msgs)
items[0]["content"] = "changed"
self.assertNotEqual(msgs[1]["content"], "changed")
class TestDemo(unittest.TestCase):
def test_demo_runs(self):
import io, contextlib
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
cm.demo(tempfile.mkdtemp())
out = buf.getvalue()
self.assertIn("turn 2 without history: Sorry, I do not know your name yet.", out)
self.assertIn("reply with pinned facts: Your name is Asha.", out)
self.assertIn("blocked session id: bad session id", out)
if __name__ == "__main__":
unittest.main()
11. Connect a real model later
The memory code does not depend on any provider. To use a real model, you only replace the fake model with one API call. The file below shows this for the OpenAI Responses API. It needs your own API key and a developer account that is billed separately from a ChatGPT subscription, so it is not part of the offline lab. We checked that the parameters it uses exist in version 3.52.0 of the official openai Python package, and we tested the glue code with a fake client, but we did not call the real API.
real_model_example.py (needs your own key)
"""Connect chat_memory.py to the OpenAI Responses API.
Needs your own API key and a paid developer account, so it is NOT part of the offline lab.
Install with: pip install openai Then keep the key in the OPENAI_API_KEY environment variable."""
import os
from chat_memory import Conversation, build_messages, to_openai_input, INSTRUCTIONS
MODEL = os.environ.get("CHAT_MODEL", "") # copy a current model name from the provider's models page
CONTEXT_WINDOW = int(os.environ.get("CHAT_BUDGET", "8000")) # your own budget, far below the model's real limit
MAX_OUTPUT = 300
def ask(client, conv, user_text):
msgs, dropped, estimate = build_messages(conv, user_text, CONTEXT_WINDOW, MAX_OUTPUT)
instructions, items = to_openai_input(msgs)
resp = client.responses.create(model=MODEL, instructions=instructions, input=items,
max_output_tokens=MAX_OUTPUT, store=False)
conv.add_turn(user_text, resp.output_text)
print(f"dropped {dropped} old turns | estimated {estimate} | real input tokens {resp.usage.input_tokens}")
return resp.output_text
if __name__ == "__main__":
from openai import OpenAI
if not MODEL:
raise SystemExit("Set CHAT_MODEL to a current model name first.")
client, conv = OpenAI(), Conversation(INSTRUCTIONS)
while True:
text = input("You: ").strip()
if not text:
break
print("Bot:", ask(client, conv, text))
- Keep your API key in an environment variable or a
.envfile, as shown in the first API call chapter, and never put it in the code or in the saved session files. - Copy a current model name from the provider's models page, and set your own budget far below that model's context window.
- The example sets
storeto false, because the app already keeps the history itself. - Compare the estimated input tokens with the real
input_tokensnumber printed after each reply, and adjust your margin if the estimate is often too low. - Handle rate limits and timeouts as the API errors chapter explains, and save the session only after a reply arrives.
12. Beginner mistakes and quick fixes
| Mistake | Quick fix |
|---|---|
| Expecting the API to remember the last message by itself. | Send the history in every request, or use the provider's documented state feature on purpose. |
| Sending the whole history forever. | Set an input budget and drop or summarise the oldest turns. |
| Dropping a user message but keeping its reply. | Trim whole turns, so each reply keeps its question. |
| Forgetting to leave room for the answer. | Subtract the output token limit and a margin before you fill the input. |
| Losing the user's name after trimming. | Pin a few important facts in the system message. |
| Letting the summary grow on every turn. | Cap the summary size and rewrite it only now and then. |
| Keeping one history list for every visitor. | Keep a separate session per user with a strictly checked session id. |
| Saving phone numbers, e-mail addresses or keys in chat logs. | Mask personal details before storage and never store secrets. |
13. Practise before you connect a real model
- Change the lab budget from 330 to 400 and predict how many turns will be dropped in Part 3 before you run the demo.
- Add “language” as a pinned fact with the value Marathi, and check that it appears in the system message.
- Write a test that proves an assistant reply is never kept without the user message before it.
- Add a function called
delete_session()that removes one saved session file, and test that it refuses a bad session id. - Change
fake_summarize()so that it keeps only messages that contain a number, and see whether the course answer still works. - Print the total estimated input tokens for the nine turns with a budget of 180 and compare it with the 1,203 tokens of the full history.
Quick self-check quiz (5 questions)
Client-only quiz — not saved. Browser-only practice. Your answers are not sent anywhere, are not saved, and do not count towards any course progress or certificate.
Recap
- A chat API is stateless, so your code must send the earlier messages or use a documented state feature on purpose.
- Sending the full history makes every turn more expensive than the last one, because you pay for the whole input each time.
- Plan an input budget by subtracting the reply limit and a safety margin from your request limit.
- Drop the oldest turns as whole user and assistant pairs, and always keep the instructions and the new message.
- Pin a few allowed facts and keep a capped rolling summary, so trimming does not lose what matters.
- Save each session separately with a strict session id and an atomic write, and mask personal details before storage.
Continue learning
- Revise tokens and the context window, and why long chats drift.
- Make your first real API call and keep the key safe.
- Handle 429, server errors and timeouts with backoff and a cost budget.
- Build a small AI agent in Python with tools, memory and guardrails.
- Learn what never to paste into an AI tool.
Ravindra Bagale, trainer: linkedin.com/in/ravindra-bagale. Kesarwadi Polytechnic, the student Asha, her messages, the e-mail address, the phone number, every model reply in the lab and all token numbers are made up / SYNTHETIC classroom material. Official interface details were checked against the linked documentation on 17 Nov 2026 (Asia/Calcutta); real limits, storage periods, prices and features vary by account and model and can change, and no provider endorsement or guarantee is claimed.