Sub topic 7
Why the Model Only Knows What You Send Each Time
This chapter assumes you can read basic Python, work with lists and dictionaries, and have a general idea of what a large language model is and how an SDK call to an HTTP API works. It covers the stateless nature of chat APIs: what that means, why it is designed that way, and what it forces you to do in your code.
The core idea: each request stands alone
A chat API is stateless. The server does not keep a record of your earlier requests. When you send a request, the model reads only the messages inside that request, writes a reply, and then forgets everything. The next request starts from nothing.
This surprises many learners, because chat apps feel like a continuing conversation. The feeling comes from the application around the model. The app stores the earlier turns and sends them again each time.
Think of it like writing to someone who loses their memory after every letter. To keep a conversation going, you must paste the whole earlier correspondence into each new letter.
What "stateless" means in practice
Three consequences follow from it.
- The model has no memory between calls. If you leave a turn out of the
messageslist, the model cannot see it. - You own the history. Your code decides what to store, in what order, and what to send.
- Every call costs more as the conversation grows. You pay for, and wait for, all the tokens you send again, not only the new ones.
Some providers offer features that store state for you, such as server-side conversation objects or prompt caching. These change where the history lives or how its cost is billed. They do not change the underlying model behavior: the model still reads a full sequence of messages each time.
Seeing the problem: a request without history
Here is what happens if you send two unrelated requests, with the second depending on the first.
from openai import OpenAI
client = OpenAI()
def ask(messages):
response = client.chat.completions.create(
model="MODEL_NAME", # replace with a chat model available to you
messages=messages,
)
return response.choices[0].message.content
# Call 1
print(ask([
{"role": "user", "content": "What is a list in Python?"},
]))
# Call 2: no history is included
print(ask([
{"role": "user", "content": "How do I add an item to it?"},
]))In the second call, the word "it" points at nothing. The model has never seen the first question. It may ask what you mean, or guess, and the guess may be wrong. The model is not failing. It is answering exactly the input it was given.
The fix: send the history every time
To make the second question work, include the earlier turns. The pattern has three steps on every turn:
- Append the new user message to the history.
- Send the entire history.
- Append the assistant reply to the history.
from openai import OpenAI
client = OpenAI()
history = [
{"role": "system", "content": "You are a helpful assistant. Keep answers under three sentences."}
]
def chat(user_text):
history.append({"role": "user", "content": user_text})
response = client.chat.completions.create(
model="MODEL_NAME", # replace with a chat model available to you
messages=history,
)
reply = response.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(chat("What is a list in Python?"))
print(chat("How do I add an item to it?"))On the second call, history holds four messages: the system message, the first question, the first answer, and the new question. Now "it" has a referent, because the earlier turns are in front of the model.
The list is the conversation. Whatever is in history at the moment you call the API is everything the model knows about the exchange.
Walking through the state of the list
It helps to track the list after each step.
| Step | Action | Messages in `history` |
|---|---|---|
| Start | Create the list | system |
| 1 | Append first user message | system, user |
| 2 | Call the API, append reply | system, user, assistant |
| 3 | Append second user message | system, user, assistant, user |
| 4 | Call the API, append reply | system, user, assistant, user, assistant |
At every API call, the list ends with a user message. The model's job is to write the next assistant message after it. This ties back to message ordering: the history alternates between user and assistant turns, with the system message at the start.
The system message must be sent too
The system message is not remembered either. It is only part of the conversation because you put it at the start of the list and send it each time. In the loop above, history is created with the system message already inside, and it stays there for every call.
If you build the list fresh on each call and forget the system message, the model drops its instructions, tone, and constraints without any warning. The reply still looks fluent, so the bug is easy to miss. With the Anthropic Messages API, the system prompt is a separate parameter, so you must pass system=... on every call as well.
Edge cases and common errors
Forgetting to store the assistant reply
If you append the user message but not the reply, the history contains only questions. The model then sees a series of user turns with its own answers missing. Its later replies may repeat earlier answers or contradict them, because it cannot see what it said.
# Bug: the reply is never added to history
def chat_broken(user_text):
history.append({"role": "user", "content": user_text})
response = client.chat.completions.create(model="MODEL_NAME", messages=history)
return response.choices[0].message.contentSome APIs also reject two consecutive user messages, which adds a second reason to store replies.
Sharing one history between users
A module-level list like history above is fine in a demo. In a web server, one global list would mix every user's messages into one conversation. That causes wrong answers and leaks private data between users. Keep one history per conversation, for example in a dictionary keyed by a session ID.
from collections import defaultdict
SYSTEM = {"role": "system", "content": "You are a helpful assistant."}
conversations = defaultdict(lambda: [dict(SYSTEM)])
def chat_for(session_id, user_text):
history = conversations[session_id]
history.append({"role": "user", "content": user_text})
# call the API with history, then append the reply
return historyMutating a list that is still in use
If you edit, reorder, or trim messages, you change what the model believes happened. This is a useful tool, since you can correct a bad turn or remove one. It is also a risk if you do it by accident. The model has no way to check that the history is true. It trusts what you send.
Treating a restart as a fresh conversation
The history lives in your program's memory. If the process restarts, the list is gone and the model "forgets" the conversation. To keep a conversation across restarts, save the list, for example as JSON in a file or a database, and load it back.
import json
def save_history(path, messages):
with open(path, "w", encoding="utf-8") as f:
json.dump(messages, f)
def load_history(path):
with open(path, "r", encoding="utf-8") as f:
return json.load(f)Cost and size grow with every turn
Because you resend everything, the input grows each turn. If each turn adds about 200 tokens, the input is roughly 200 tokens on turn one, 400 on turn two, 600 on turn three, and so on. Total tokens processed over a conversation grow faster than the number of turns.
Two limits matter:
- Context window. This is the maximum number of tokens the model can read in one request, including your input and its output. A request that exceeds it fails or gets cut off, depending on the provider.
- Price and latency. Longer inputs cost more and take longer to process.
The usual remedy is to trim or summarize old turns. A later chapter covers this in detail, but here is the simplest version: keep the system message and the most recent turns.
def trim_history(messages, max_turn_messages=10):
system_messages = [m for m in messages if m["role"] == "system"]
others = [m for m in messages if m["role"] != "system"]
return system_messages + others[-max_turn_messages:]This function always keeps the system message. It drops the oldest user and assistant messages first. The cost is that the model loses what was said in the dropped turns.
Why it is designed this way
Statelessness is not an oversight. It has practical benefits:
- Simple scaling. Any server can handle any request, because no request depends on a particular machine's memory.
- Full control. You decide exactly what the model sees. You can edit history, inject examples, or branch a conversation into two paths from the same point.
- Reproducibility. Given the same messages and settings, you can rerun a request to debug it. Outputs may still vary because sampling is random, but the input is fully known.
- Privacy options. You choose what leaves your system with each call.
Summary of the working model
- The model reads one list of messages per request and keeps nothing afterward.
- Your code stores the conversation and sends all of it, including the system message, each time.
- After each call, append the assistant reply so the next call can see it.
- Keep one history per conversation, and persist it yourself if it must survive a restart.
- Watch the size of the history, since it grows with every turn.
Exercise
A developer's chatbot answers the first question well. When the user asks "Can you explain that more simply?", the bot replies "Could you tell me what you would like explained?" The code calls the API with messages=[{"role": "user", "content": user_text}] on every turn. What is wrong, and how do you fix it?
Show answer
The API is stateless, and each call sends only the newest user message, so the model never sees the earlier question or its own answer. "That" has no referent. Fix it by keeping a history list that starts with the system message, appending each user message before the call, sending the whole list, and appending the assistant reply after the call.
Exercise
Your server uses one global history list for all users, and users report that the bot sometimes mentions things they never said. What causes this, and what is a minimal fix?
Show answer
All users' messages are appended to the same list, so each request includes other people's turns. Keep a separate history per conversation, for example a dictionary keyed by session ID, where each new entry starts with a copy of the system message.
Exercise
After 40 turns, requests become slow and expensive. Name two reasons this happens and one way to reduce it.
Show answer
The whole history is resent on every call, so input tokens, cost, and latency grow with each turn, and the history may approach the context window limit. One remedy is trimming: keep the system message and only the most recent turns, or summarize older turns.