Sub topic 1
Why Every Request Carries the Whole Conversation
Prerequisites
This chapter assumes you have:
- Basic Python or comparable programming experience.
- Some familiarity with chat-style LLM APIs and the message roles
system,user, andassistant. - A general idea of what a token is: a chunk of text, often a word or part of a word, that the model reads and writes.
You do not need to have called a specific provider's API. The examples use a fake model function, so everything runs without a network connection or an API key.
The problem this chapter explains
A chat product feels like a continuing conversation. You ask a question, the assistant answers, and you ask a follow-up that says "what about the second one?" The assistant seems to remember what "the second one" means.
The model does not remember anything between requests. Your application creates that illusion by resending the conversation each time. This chapter explains why that is so, what it costs, and why it leads to the rest of this tutorial: truncation, summaries, and combinations of the two.
Stateless APIs
Most chat model APIs are stateless. A stateless service does not keep information about earlier requests. Each request is handled using only the data inside it. Once the response is returned, the model holds nothing about that exchange.
The model itself is a function from input text to output text. It has no session variable that says "this user said X two minutes ago." If X is not in the input, X does not exist for the model.
A typical request looks like this:
{
"model": "example-model",
"max_tokens": 500,
"messages": [
{"role": "system", "content": "You are a helpful travel assistant."},
{"role": "user", "content": "I'm planning a trip to Lisbon in May."},
{"role": "assistant", "content": "Great choice. How many days will you stay?"},
{"role": "user", "content": "Five days. What should I see on the second day?"}
]
}The last user message refers to "the second day" of a five-day trip to Lisbon. The model can only answer well because the earlier messages travel in the same request.
Some providers offer features that store conversation state on their side, such as stored threads or response IDs that refer to earlier turns. These change who keeps the history. They do not change what the model reads. The stored messages are still placed in the model's input, and they still count against its size limit.
A runnable demonstration
The following program simulates a stateless model. The fake model can answer only from what is in the messages it receives. It looks for a city name in the input.
def fake_model(messages):
"""A stand-in for a stateless chat model.
It can only use the messages passed in. It knows nothing else.
"""
text = " ".join(m["content"] for m in messages).lower()
if "lisbon" in text:
return "For day two in Lisbon, try the Alfama district."
return "Which city are you visiting?"
# Attempt 1: send only the newest message.
latest_only = [
{"role": "user", "content": "Five days. What should I see on the second day?"}
]
print("Latest only:", fake_model(latest_only))
# Attempt 2: send the whole conversation.
full_history = [
{"role": "system", "content": "You are a helpful travel assistant."},
{"role": "user", "content": "I'm planning a trip to Lisbon in May."},
{"role": "assistant", "content": "Great choice. How many days will you stay?"},
{"role": "user", "content": "Five days. What should I see on the second day?"},
]
print("Full history:", fake_model(full_history))Running it prints:
Latest only: Which city are you visiting?
Full history: For day two in Lisbon, try the Alfama district.The only difference between the two calls is the input. This is the whole mechanism behind a "memory" in a plain chat application.
The standard chat loop
Your application owns the history. A minimal loop does four things on every turn:
- Append the new user message to the history list.
- Send the entire list to the model.
- Receive the reply.
- Append the reply to the history list.
def fake_model(messages):
# Replace with a real API call. It returns the assistant's reply text.
return f"(reply based on {len(messages)} messages)"
def chat_turn(history, user_text):
history.append({"role": "user", "content": user_text})
reply = fake_model(history)
history.append({"role": "assistant", "content": reply})
return reply
history = [{"role": "system", "content": "You are a helpful travel assistant."}]
for text in ["Hi", "I'm going to Lisbon.", "Five days.", "Day two?"]:
print(chat_turn(history, text))Output:
(reply based on 2 messages)
(reply based on 4 messages)
(reply based on 6 messages)
(reply based on 8 messages)The number of messages sent grows by two on every turn: one user message and one assistant message. The history list is the only memory in the system. If your process restarts and the list is lost, the conversation is lost with it, unless you saved the list somewhere.
Why the cost grows faster than the conversation
Because every request includes everything so far, the input size on turn n is roughly the sum of all earlier messages. The total amount of text you send over a whole conversation grows faster than the conversation itself.
Suppose each user message and each assistant reply averages 200 tokens, and the system prompt is 300 tokens. On turn n, the input is about:
300 + 400 × (n − 1) + 200 tokens
That is the system prompt, plus all earlier user and assistant pairs, plus the new user message. The table shows how it builds up.
| Turn | Input tokens sent | Cumulative input tokens sent |
|---|---|---|
| 1 | 500 | 500 |
| 5 | 2,100 | 5,500 |
| 10 | 4,100 | 21,500 |
| 20 | 8,100 | 83,500 |
| 50 | 20,100 | 511,500 |
You can verify the numbers with a short script:
SYSTEM = 300
USER = 200
ASSISTANT = 200
def input_tokens(turn):
# System prompt + earlier user/assistant pairs + the new user message.
return SYSTEM + (USER + ASSISTANT) * (turn - 1) + USER
total = 0
for turn in range(1, 51):
total += input_tokens(turn)
if turn in (1, 5, 10, 20, 50):
print(f"turn {turn:>2}: input={input_tokens(turn):>6,} cumulative={total:>8,}")Two separate effects follow:
- Per-request size grows linearly. Each request is a little larger than the last. This is what eventually hits the model's size limit.
- Total cost grows quadratically. Summing a linearly growing series gives a quadratic total. A 50-turn conversation sends about 100 times as many input tokens as the first request in aggregate, not 50 times.
Most providers bill by input and output tokens, and larger inputs also take longer to process. Cost and latency both rise as a conversation continues, even when each new message is short.
Some providers offer prompt caching, which lowers the price or latency of repeating an identical prefix. It reduces the cost of resending, but it does not remove the size limit. The history still has to fit.
The size limit
A model can read only a fixed amount of input at once. This limit is its context window, measured in tokens. The next chapter covers it in detail. For now, you need one fact: the window includes everything you send, so the history cannot grow forever.
When the history grows past the limit, one of three things happens, depending on the provider and your code:
- The API rejects the request with an error.
- The provider silently drops some of the input.
- Your own code cuts the history before sending, which is the approach this tutorial teaches.
Relying on the first two is a bad plan. An error ends the conversation for the user, and silent dropping removes content you did not choose to remove. The point of the following chapters is to make that choice deliberately.
What "managing" a conversation means
Because the application owns the history, the application decides what the model sees. You can send more or less than the full record. This leads to a set of strategies, which this tutorial covers in order:
| Strategy | What you send | Main risk |
|---|---|---|
| Send everything | The full history | Hits the size limit, high cost |
| Truncate | The most recent messages that fit | Forgets older facts completely |
| Summarize | A model-written summary of older turns | The summary may lose or distort details |
| Hybrid | A summary plus recent messages verbatim | More moving parts to test |
| External memory | Retrieved pieces from stored history | Retrieval can miss the right piece |
None of these is correct for every application. A short customer-support chat may never need any of them. A coding assistant that runs for hours certainly does.
Common mistakes
- Assuming the model remembers. A bug report that says "the assistant forgot my name" usually means the name was not in the request. Log the exact messages you send when you debug.
- Sharing one history list between users. Because the list is the memory, a list shared across users leaks one person's conversation into another's. Keep one history per conversation.
- Mutating history while a request is in flight. In concurrent code, a second message can be appended before the first reply arrives, which produces two user messages in a row or replies attached to the wrong turn. Process one turn per conversation at a time, or lock the history.
- Forgetting to store the reply. If you do not append the assistant's answer, the next request shows the model a conversation where it never spoke, and it may repeat itself or contradict its earlier answer.
- Ignoring the system prompt in cost estimates. The system prompt is resent every turn too. A 2,000-token system prompt adds 2,000 tokens to every request.
Summary
- Chat models are stateless. They see only the messages in the current request.
- Your application keeps the history and sends the whole list on each turn.
- Input size grows linearly with the number of turns, and total tokens sent grows quadratically.
- The context window caps the input, so long conversations eventually need trimming.
- Truncation, summarization, and combinations of them let you choose what to keep. The rest of this tutorial builds those tools.
Exercise
A conversation has a 400-token system prompt. Every user message and every assistant reply is 150 tokens. How many input tokens does the request for turn 8 contain, counting the new user message and all earlier messages? Then explain in one sentence why the assistant would "forget" the user's name if your code sent only the newest message.
Show answer
Turn 8 includes the system prompt (400), seven earlier user and assistant pairs (7 × 300 = 2,100), and the new user message (150). The total is 400 + 2,100 + 150 = 2,650 tokens. The assistant would forget the name because the model is stateless: the name appeared in an earlier message, and anything not in the current request does not exist for the model.
Exercise
A teammate says, "Our provider stores the conversation on its servers, so we don't need to worry about the context window." Is that correct? Explain.
Show answer
No. Server-side storage changes who keeps the history, but the stored messages are still placed in the model's input for each request. They count against the context window, and they still add to cost and latency. A long stored conversation can still exceed the limit, so you still need a plan for trimming or summarizing it.