By the end of this lesson you will be able to:
- Explain how a chat app "remembers" a conversation, and why it sometimes forgets.
- Manage the context window by trimming or summarising history.
- Design for a good user experience: streaming, personality, accessibility and safety.
- Make your app reliable with retries, timeouts and monitoring.
Chat apps vs text generation apps
The worksheet generator from Lesson 6 answers one request and is done. A chat app is a conversation: a student asks a doubt, then a follow-up ("can you explain step 2 again?"), then another. Each reply must make sense in light of everything said before.
Here's the surprise: LLMs have no memory. Every API call is independent. A chat app creates memory by sending the whole conversation (system message plus all earlier messages) with every new request.
- My name is Arjun and I'm preparing for the Class 10 boards.
- Nice to meet you, Arjun! Which subject shall we start with?
- Maths. What's my name, by the way? 😄
- You're Arjun! I know because your earlier message is sent back to me with this question.
- Behind the scenes, request #2 contained all 3 earlier messages, not just the last one.
The context window fills up
Every model has a context window, the maximum number of tokens it can read in one request. Modern models have large windows, but long conversations, long documents and many users add up quickly, and every resent token costs money and time. So chat apps need a strategy for when history gets too long:
- Drop the oldest messages (a "sliding window"). Simple, but the model forgets early details.
- Summarise old messages into a short note and keep the summary. Key facts survive, and it costs one extra call.
- Store facts separately (name, class, goals) and add them to the system message every time.
Try both strategies below. Keep chatting and watch the token budget.
The core loop in Python
A complete chat app is surprisingly small. Run this on your machine with a real key (same setup as Lesson 6):
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
history = [{"role": "system", "content": "You are Vidya, a patient tutor for Class 6-12 students in India."}]
while True:
question = input("You: ")
if question.lower() in {"bye", "exit"}:
break
history.append({"role": "user", "content": question})
reply = client.chat.completions.create(model="gpt-4o-mini", messages=history, temperature=0.5)
answer = reply.choices[0].message.content
history.append({"role": "assistant", "content": answer}) # this is the "memory"
print("Vidya:", answer)
Designing a great chat experience
Speed
Turn on streaming so words appear immediately. Show a typing indicator. Keep prompts lean, because every extra token adds latency.
Personality and consistency
The system message sets tone and rules: friendly, encouraging, never condescending. Give the assistant a name and a consistent voice. For a tutor, add "guide the student to the answer rather than just giving it."
Accessibility and language
Support the languages your users actually speak, including Hinglish. Consider voice input and text-to-speech for students who find reading hard. Keep replies short on mobile, with an offer to "explain more".
Safety
Everything from Lesson 3 applies: content filters on input and output, a clear system message, a report button, and extra care because many users are minors.
Making it reliable
Real APIs sometimes fail: rate limits (HTTP 429), timeouts and temporary server errors. Production chat apps:
- Retry with exponential backoff: wait 1s, then 2s, then 4s before giving up. Don't hammer a struggling server.
- Set timeouts so a stuck request doesn't freeze the app.
- Show a friendly error ("I'm having trouble right now, please try again") instead of a crash.
- Monitor: track latency, errors, tokens per conversation and thumbs-up/down feedback.
Hands-on
Your task: complete trim(). It must always keep the system message, then drop the oldest other messages until the total is within the budget. Expected: Kept 4 messages, 44 tokens, system first: True.
def count_tokens(message):
# rough estimate: 4 characters per token + 4 tokens of overhead per message
return len(message["content"]) // 4 + 4
history = [
{"role": "system", "content": "You are Vidya, a patient tutor."},
{"role": "user", "content": "Hi! I'm in Class 9 and need help with chemistry."},
{"role": "assistant", "content": "Sure! Which chapter are you studying?"},
{"role": "user", "content": "Atoms and molecules."},
{"role": "assistant", "content": "Great. An atom is the smallest unit of an element."},
{"role": "user", "content": "What is a molecule?"},
]
def total(messages):
return sum(count_tokens(m) for m in messages)
def trim(messages, budget):
system, rest = messages[0], messages[1:]
# TODO: while total([system] + rest) > budget, remove the oldest message from rest
return [system] + rest
print("Before:", len(history), "messages,", total(history), "tokens")
kept = trim(history, budget=50)
print(f"Kept {len(kept)} messages, {total(kept)} tokens, system first: {kept[0]['role'] == 'system'}")
Show solution
while total([system] + rest) > budget and rest:
rest.pop(0)
Your task: flaky_api() fails twice (like a rate limit) and then works. Complete call_with_retry() so it catches the error, waits base_delay * 2**attempt seconds, and tries again, up to max_attempts times. Expected: Succeeded on attempt 3.
import time
calls = {"n": 0}
class RateLimitError(Exception):
pass
def flaky_api():
calls["n"] += 1
if calls["n"] < 3:
raise RateLimitError("429 Too Many Requests")
return "An atom is the smallest unit of an element."
def call_with_retry(fn, max_attempts=4, base_delay=0.1):
for attempt in range(max_attempts):
# TODO: try fn(); on success print f"Succeeded on attempt {attempt + 1}" and return the result
# on RateLimitError: print the wait time, sleep base_delay * 2**attempt, and loop again
pass
raise RuntimeError("Gave up after retries")
try:
print("Reply:", call_with_retry(flaky_api))
except RuntimeError as err:
print("Error:", err)
Show solution
try:
result = fn()
print(f"Succeeded on attempt {attempt + 1}")
return result
except RateLimitError as err:
wait = base_delay * 2 ** attempt
print(f"Attempt {attempt + 1} failed ({err}), retrying in {wait:.1f}s")
time.sleep(wait)
Check your understanding
How does a chat app "remember" what the user said earlier?
- The model stores each user's memory on its servers
- The app resends the conversation history with every request
- The temperature is set to 0
- It fine-tunes the model after each message
Chat APIs are stateless. Memory is created by your app sending past messages again.
Your tutor forgets the student's name after a long chat. What's the best fix?
- Raise the temperature
- Delete the system message to save space
- Ask the student to repeat their name
- Summarise old messages, or store key facts and add them to the system message
Summaries and stored facts keep important details in the context even when old messages are trimmed.
The API returns HTTP 429. What should your app do?
- Wait and retry with exponential backoff
- Retry immediately in a tight loop
- Show the raw error to the user
- Switch off safety filters
429 means "too many requests". Waiting progressively longer gives the service time to recover.
Key takeaways
- LLMs are stateless, so chat apps create memory by resending history.
- Manage the context window: trim, summarise, or store key facts.
- Great chat UX means streaming, a consistent personality, accessibility and safety.
- Production apps retry with backoff, set timeouts, handle errors kindly and monitor everything.
Next: search applications. Find answers by meaning, not just matching words.
Your progress is saved in this browser.
Adapted from Lesson 7 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source