Sub topic 1
Why the model forgets: stateless APIs
Prerequisites
This chapter assumes you can read and write basic Python: functions, lists, dictionaries, and exceptions. You should be comfortable running a program in a terminal. You should also know the general shape of a chat model API: you send messages in, and you get a reply out. You do not need an account with any provider. The code here uses a fake model so it runs as shown.
The problem: a bot that seems to forget
Suppose you build a chatbot and try this conversation:
you> My name is Priya.
bot> Nice to meet you, Priya!
you> What is my name?
bot> I don't know your name. You haven't told me.The model is not broken. It did what its API is designed to do. A chat model API is stateless: the server keeps no record of earlier requests from you. Each request is processed on its own, and the server discards everything once it has sent the reply.
This chapter explains what stateless means in practice, how to see it in code, and what it implies for the design of the rest of the tutorial.
What "stateless" means
A stateless service treats every request as complete and self-contained. It does not look up who you are, what you asked before, or what it answered. Everything it needs must arrive in the request itself.
Many web services you already use work this way. An HTTP server does not remember your previous request unless you send a cookie or a token. Chat model APIs follow the same idea, with one difference: the thing you must resend is the conversation itself.
| Property | Stateless API | Stateful session |
|---|---|---|
| Where the conversation lives | In the client program | On the server |
| What each request contains | The full conversation so far, plus the new message | Only the new message |
| Server memory between requests | None | A stored session |
| Who controls the content | The client, fully | The server, partly |
| Failure of one request | Does not affect others | May corrupt the session |
Some providers offer optional stateful features, such as stored threads or conversation IDs. Those are conveniences built on top of the same model. The model itself still reads one block of text per call. This tutorial uses the plain stateless style because it works with every provider and shows you what is really happening.
What a request contains
A chat request is a list of messages. Each message is a dictionary with a role and content. The role says who is speaking. The common roles are:
system: instructions that set the bot's behavior.user: what the person typed.assistant: what the model replied earlier.
Providers differ in details. Some take the system text as a separate parameter, and some use other names for the roles. The idea is the same everywhere: the request carries an ordered list of role-tagged messages.
The model reads the list from top to bottom and writes the next assistant message. It has no other source of information about the conversation.
Seeing statelessness in code
Here is the simplest version of the bug. Each turn sends only the latest user message. The complete function below is a fake model. It only reports what it received, so we can see exactly what a real model would see.
def complete(messages):
"""A fake model that describes the request it received."""
user_texts = [m["content"] for m in messages if m["role"] == "user"]
if "My name is Priya." in user_texts and messages[-1]["content"] == "What is my name?":
return "Your name is Priya."
return f"I received {len(messages)} message(s). I can only see: {user_texts}"
def forgetful_turn(user_text):
# Bug: only the new message is sent.
messages = [{"role": "user", "content": user_text}]
return complete(messages)
def remembering_turn(history, user_text):
# Fix: append to a growing list and send all of it.
history.append({"role": "user", "content": user_text})
reply = complete(history)
history.append({"role": "assistant", "content": reply})
return reply
print("--- forgetful ---")
print(forgetful_turn("My name is Priya."))
print(forgetful_turn("What is my name?"))
print("--- remembering ---")
history = []
print(remembering_turn(history, "My name is Priya."))
print(remembering_turn(history, "What is my name?"))Running it prints:
--- forgetful ---
I received 1 message(s). I can only see: ['My name is Priya.']
I received 1 message(s). I can only see: ['What is my name?']
--- remembering ---
I received 1 message(s). I can only see: ['My name is Priya.']
Your name is Priya.In the forgetful version, the second call carries one message. The name never reaches the model, so it cannot be used. In the remembering version, the second call carries three messages: the first user message, the first reply, and the new question. The fake model can now find the name.
A real model does not search for strings like this fake one does. It reads the whole list and predicts a fitting reply. The effect is the same: information in the request can influence the answer, and information outside it cannot.
The request grows with every turn
Because the full conversation is resent, each request is larger than the one before it. This diagram shows the flow for three turns.
The pattern has several consequences:
- The client owns the memory. If your program loses the list, the conversation is gone. Nothing on the server can bring it back.
- Cost grows. Providers usually bill by the number of tokens processed. A token is a small chunk of text, often a word or part of a word. Resending the history means you pay for the old turns again on every call. Total tokens across a conversation grow faster than the number of turns.
- Latency grows. A longer input takes longer to process.
- There is a hard limit. Each model accepts only a maximum number of tokens per request. This is the context window, covered in a later chapter. A conversation that grows without bound will eventually fail.
You can check the growth with a quick calculation. If every message is about 50 tokens, then the request on turn n holds about 2n - 1 messages, because each earlier turn added a user message and a reply.
TOKENS_PER_MESSAGE = 50
total = 0
for turn in range(1, 11):
messages_sent = 2 * turn - 1
sent = messages_sent * TOKENS_PER_MESSAGE
total += sent
print(f"turn {turn:2d}: {messages_sent:2d} messages, {sent:4d} tokens sent, {total:5d} total")After ten turns the program has sent 5,000 tokens in total, although the conversation itself holds only 950 tokens of text. Ten turns cost far more than ten times a single turn. The cost is quadratic in the number of turns, not linear.
Common misconceptions
"The model learned my name." It did not. Model weights do not change during a chat. If the name appears in a later answer, it is because the name was in that request.
"Memory is a feature I switch on." For the plain API there is no switch. Memory is something your program builds by storing messages and sending them back.
"The reply is part of the conversation automatically." It is not. After you receive a reply, you must append it to your list as an assistant message. If you forget this step, the model will see your questions but not its own earlier answers, and its behavior will become confusing.
"Sending the history guarantees the model uses it." The model sees the history, but it may still weigh it poorly, especially when the history is very long. Sending history is necessary for memory, not a guarantee of perfect recall.
Common errors
- Rebuilding the list on every turn. Creating
messages = []inside the loop discards the past. Create the list once, before the loop. - Forgetting to append the assistant reply. The list then contains only user messages, and some providers reject two user messages in a row.
- Mutating the list after a failed call. If the request fails, a user message may remain in the list with no reply. A later chapter shows how to keep the history valid in that case.
- Sharing one list between users. In a program that serves several people, one shared list leaks one person's messages into another's conversation. Each conversation needs its own list.
What this means for the design
The rest of the tutorial follows from one fact: the client owns the conversation. That leads to these tasks, each a later chapter:
- Keep a list of role-tagged messages and send all of it each turn.
- Put the system message at the start and keep it there.
- Hide the provider behind one function, so the logic is testable.
- Stop the list from exceeding the context window.
- Save the list to disk, so a restart does not erase it.
- Handle errors without leaving the list in a broken state.
Exercise
A learner's chatbot answers the first question well, but on the second turn it behaves as if the first never happened. The loop contains messages = [{"role": "user", "content": user_text}] followed by reply = complete(messages) and a print. Explain the cause and give the smallest fix.
Show answer
The list is rebuilt from scratch on every iteration, so each request holds only the newest user message, and the API keeps no state to fill in the rest. The fix is to create history once before the loop, append the user message to it each turn, call complete(history), and then append the reply as an assistant message. This way, each request carries the full conversation.
Exercise
Each message in a conversation is about 40 tokens. A bot resends the full history every turn, and each turn adds one user message and one assistant message. How many tokens are sent on turn 5 alone, and how many in total across turns 1 to 5? (Ignore any system message.)
Show answer
On turn n the request holds 2n - 1 messages. Turn 5 sends 9 messages, which is 360 tokens. The counts for turns 1 to 5 are 1, 3, 5, 7, and 9 messages, which add up to 25 messages, or 1,000 tokens in total.