Sub topic 7
Multi-turn conversations: you resend the history
This chapter assumes you can send a basic chat request, read the response, and know what tokens and the context window are. You should be comfortable with Python lists and dictionaries. The examples use the chat-completions request shape. Field names differ between providers, so check your provider's documentation.
The API does not remember anything
A chat model feels like it remembers you. It does not. Each HTTP request to a chat-completions endpoint is independent. The server reads the messages list in that request, generates a reply, and keeps nothing for the next call.
The conversation lives in your program. You hold a list of messages. For each new turn you append the user's message, send the whole list, and append the model's reply. The model can answer "What is my name?" only because the earlier message "My name is Sam." is included in the second request.
A minimal conversation loop
This program keeps one list, messages, and updates it on each call to ask.
import os
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
MODEL = os.environ["LLM_MODEL"]
messages = [{"role": "system", "content": "You are a concise assistant."}]
def ask(question):
messages.append({"role": "user", "content": question})
resp = requests.post(
URL, headers=HEADERS, json={"model": MODEL, "messages": messages}, timeout=30
)
resp.raise_for_status()
reply = resp.json()["choices"][0]["message"]["content"]
messages.append({"role": "assistant", "content": reply})
return reply
print(ask("My name is Sam."))
print(ask("What is my name?"))The order of operations matters:
- Append the user message before the request, so it is part of what you send.
- Send the full list.
- Append the assistant reply only after a successful response, so the history stays consistent with what the model actually said.
If you remove the history, for example by sending only [{"role": "user", "content": "What is my name?"}], the model has no way to know the name. It will usually say it does not know, or it may guess.
What a message list looks like on the wire
After two turns, the second request body contains this:
{
"model": "your-model-name",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "My name is Sam."},
{"role": "assistant", "content": "Nice to meet you, Sam."},
{"role": "user", "content": "What is my name?"}
]
}Each turn adds two messages: one from the user and one from the assistant. The list always ends with a user message when you ask for a reply. The system message stays at the front and acts as standing instructions.
Why this design has consequences
Because you resend everything, three things follow.
- Input size grows every turn. Turn 10 sends the content of turns 1 to 9 again. Input tokens, and therefore cost and latency, rise with conversation length. The
usage.prompt_tokensvalue in the response shows this directly. - The context window is a hard ceiling. The history plus the space reserved for the reply must fit in the model's context window. When it does not, the API returns an error, usually a 400 that mentions context length.
- You control the history. You can edit, trim, summarize, or reorder it. The model sees only what you send. This is powerful, and it is also where most bugs come from.
def show_usage(resp_json):
usage = resp_json["usage"]
print("prompt:", usage["prompt_tokens"], "completion:", usage["completion_tokens"])Log prompt_tokens each turn while you are developing. You will see it climb even when the user's messages are short.
Keeping history within the context window
You need a policy for what to do when the history gets long. The common options are below.
| Strategy | How it works | Cost | Main risk |
|---|---|---|---|
| Truncate oldest turns | Drop the earliest user/assistant pairs, keep the system message | Cheapest | Model forgets early facts |
| Sliding window by tokens | Keep the newest messages that fit a token budget | Cheap | Same as above, but predictable size |
| Summarize old turns | Ask the model to condense old messages into one message | Extra API call | Summary may lose or distort details |
| Pin key facts | Store important facts separately and add them to the system message | Small | You must decide what counts as key |
Truncating with a budget
Counting tokens exactly requires the provider's tokenizer. A rough estimate is enough for a safety margin. A common rule of thumb for English is about four characters per token. Treat it as an approximation and leave headroom.
def estimate_tokens(message):
return len(message["content"]) // 4 + 4
def trim_history(messages, budget):
system = messages[:1]
rest = messages[1:]
kept = []
total = sum(estimate_tokens(m) for m in system)
for m in reversed(rest):
cost = estimate_tokens(m)
if total + cost > budget:
break
kept.append(m)
total += cost
kept.reverse()
return system + keptThis keeps the system message, then adds messages from newest to oldest until the budget is reached. The budget should be the context window minus the tokens you reserve for the reply (max_tokens or your provider's equivalent), minus a margin for estimation error.
There is one gotcha. Trimming can cut a conversation so that the first kept message is an assistant message. Some providers reject that, and the model may be confused by a reply that answers nothing. After trimming, drop leading assistant messages:
def trim_history_safe(messages, budget):
trimmed = trim_history(messages, budget)
while len(trimmed) > 1 and trimmed[1]["role"] != "user":
del trimmed[1]
return trimmedWhen tool calls are involved, a related rule applies. A tool result message must stay next to the assistant message that requested it. Trim them together or not at all.
Summarizing
Summarization keeps the gist of old turns in far fewer tokens. You send the old messages to the model with an instruction such as "Summarize this conversation in under 150 words, keeping names, decisions and open questions." Then you replace those messages with one message holding the summary.
def summarize(old_messages):
transcript = "\n".join(f"{m['role']}: {m['content']}" for m in old_messages)
resp = requests.post(
URL,
headers=HEADERS,
json={
"model": MODEL,
"messages": [
{
"role": "system",
"content": "Summarize the conversation in under 150 words. "
"Keep names, decisions and open questions.",
},
{"role": "user", "content": transcript},
],
},
timeout=30,
)
resp.raise_for_status()
return resp.json()["choices"][0]["message"]["content"]Then rebuild the history:
def compact(messages, keep_last=4):
system, rest = messages[:1], messages[1:]
if len(rest) <= keep_last:
return messages
old, recent = rest[:-keep_last], rest[-keep_last:]
summary = {
"role": "system",
"content": "Summary of earlier conversation: " + summarize(old),
}
return system + [summary] + recentSummaries are lossy. A number or a name that mattered may disappear. If a fact must never be lost, store it yourself and put it in the system message instead of relying on a summary.
Common errors
- Forgetting to append the assistant reply. The next request has two user messages in a row, and the model has no record of what it said. Follow-up questions such as "make it shorter" then fail.
- Appending a failed reply. If the request raised an error, do not append anything for the assistant. Decide whether to keep or remove the user message you already added, so a retry does not send it twice.
- Sharing one list across users. A module-level
messageslist, as in the demo above, is fine for a script. In a web service it mixes conversations. Keep one history per conversation, keyed by a session or conversation ID. - Mutating the list while a request is in flight. In concurrent code, two calls on the same conversation can interleave and produce a history with the wrong order. Serialize calls per conversation.
- Ignoring
finish_reason. If it islength, the reply was cut off. Storing the truncated reply as if it were complete makes later turns build on a fragment. - Resending huge pasted content on every turn. A large document in turn 1 is billed again each turn. Consider keeping it only while needed.
Making the loop safer
A version of ask that avoids the first three errors works on a copy of the history and commits only on success.
def ask_safe(history, question, max_budget=6000):
candidate = history + [{"role": "user", "content": question}]
candidate = trim_history_safe(candidate, max_budget)
resp = requests.post(
URL,
headers=HEADERS,
json={"model": MODEL, "messages": candidate},
timeout=30,
)
resp.raise_for_status()
choice = resp.json()["choices"][0]
candidate.append({"role": "assistant", "content": choice["message"]["content"]})
return candidate, choice["finish_reason"]The caller replaces its stored history with the returned list. If raise_for_status raises, the stored history is unchanged, so retrying cannot create duplicate user messages. The function returns finish_reason so the caller can warn about truncated replies.
Where conversation state can live
Where you keep the list depends on the application.
- In memory. Fine for a script or a single-process demo. The history is lost on restart.
- A database or cache, keyed by conversation ID. Needed for web apps and for any app with more than one server process. Store each message with a role, content, and timestamp.
- The client. Some apps send the history from the browser on every request. This is simple, but users can edit it, so do not trust it for anything security-relevant.
Some providers offer server-side conversation storage as a separate feature. Those features change what you send per request, and they have their own retention and billing rules. The plain chat-completions pattern in this chapter is stateless, so the examples here always resend the history.
Exercise
A chat app works for the first three turns. On turn 4 the model ignores a constraint the user gave in turn 1, and the response shows prompt_tokens far lower than in turn 3. The code trims the history to a token budget. What most likely happened, and what are two ways to fix it?
Show answer
The trimming dropped the oldest messages, including the turn 1 constraint, so the model never saw it. The lower prompt_tokens confirms that less was sent. Fixes: put standing constraints in the system message, which the trimming function always keeps, or summarize old turns into a message that preserves the constraint. Raising the budget also helps if the context window allows it.
Exercise
Why can't you make the second request in a conversation send only the new user message and rely on the server to remember the first?
Show answer
The chat-completions API is stateless. The server uses only the messages in the current request and stores nothing between calls. Without the earlier messages in the list, the model has no access to them.