Lesson 8 of 8 · Real-World Use
Keeping Conversation History
Build multi-turn chats on a stateless AI API: store turns, send the right history, trim to a token budget, summarise old turns and store chats per user safely.
- 6 min read
- Beginner
- Reviewed
- Why your program, not the API, must keep the conversation
- How to store turns and send history with each request
- How to keep long conversations within a token budget
- Good practices for storing conversations per user
The app remembers, not the model
AI APIs are stateless: each request stands alone. For a conversation, your program keeps the list of messages and sends the relevant part with every new request. Forget to do that, and every message starts a brand-new conversation.
After each exchange, store both sides:
- The user's message, with the role user.
- The model's reply, with the role assistant.
A small chat with a budget
The program below keeps the full history but sends only what fits within a token budget. A fake model stands in for the API and reports what it can see.
def fake_model(messages):
# Stands in for a real API call: it reports what it can "see"
questions = []
for message in messages:
if message["role"] == "user":
questions.append(message["content"])
return f"(I can see {len(messages)} messages; the earliest question I see is {questions[0]!r})"
def tokens(text):
return len(text) // 4 + 1 # rough estimate
system = "You are a helpful cooking assistant."
budget = 60 # maximum input tokens per request
history = [] # every turn, kept by OUR program
def ask(question):
history.append({"role": "user", "content": question})
# Choose the newest messages that fit in the budget
sending = []
used = tokens(system)
for message in reversed(history):
if used + tokens(message["content"]) > budget:
break
sending.insert(0, message)
used += tokens(message["content"])
reply = fake_model([{"role": "system", "content": system}] + sending)
history.append({"role": "assistant", "content": reply}) # remember the answer too
return reply
for question in ["What can I cook with rice and eggs?",
"Is it OK for someone who is vegetarian?",
"How long does it take?"]:
print("Q:", question)
print("A:", ask(question))
print("Turns stored by the app:", len(history))The app stored all 6 messages, but by the third question the model no longer sees "rice and eggs", so "How long does it take?" has lost its meaning. Trimming keeps requests within budget, but it needs help to keep the meaning.
Better ways to keep context
| Technique | How | Good for |
|---|---|---|
| Sliding window | Send the last N turns | Simple chats where only recent turns matter |
| Summarise older turns | Replace old turns with a short summary written by a model | Long conversations |
| Pin key facts | Keep a short list of essentials (name, goal, preferences) in the system prompt | Personal assistants, tutors |
| Retrieve old turns | Search earlier messages and include only relevant ones | Very long histories |
Storing conversations
In a real app, history lives in a database, keyed by user and conversation, not in a variable:
- Store every message with its role, time and the token usage of each reply.
- Keep conversations separate per user. Never mix one user's history into another user's request; that would leak private information.
- Decide how long to keep them, tell users, and let them delete their history.
- Treat stored history as untrusted if users can edit or import it, because fake assistant messages can be used to manipulate the model.
Common mistakes
Store each completed turn, the user's question and the model's answer, so the next request can include them.
history = []
def add_turn(question, answer):
# Append the question as a "user" message and the answer as an
# "assistant" message to history
pass
add_turn("Hi!", "Hello! How can I help?")
add_turn("What is 2 + 2?", "4")
print(len(history), "messages")
for message in history:
print(message["role"], "->", message["content"])
A user asks a follow-up question and the model answers as if it has never seen the conversation. What is the most likely bug?
Summary
- AI APIs are stateless: your app keeps the conversation and sends it with each request.
- Store both user and assistant messages after every turn.
- Keep requests within budget with a sliding window, summaries, pinned facts or retrieval.
- In production, store history in a database per user, with clear retention and deletion.
Course complete
You can now call AI models from your own code: you know how requests and responses are shaped, how to keep keys safe, make calls with SDKs or plain HTTP, read responses, stream output, handle errors and retries, track costs and manage conversation history.
Next steps: provider-specific courses such as the Anthropic API or OpenAI API, or Prompt Engineering to improve what you send.
Finished reading? Tick it off to track your progress.