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 also be comfortable with Python lists and dictionaries.
The API has no memory
A chat-completions endpoint is stateless. Each request is independent, and the server keeps nothing between calls. If you send "What is my name?" alone, the model has no way to know the answer.
The "memory" in a chat product is the client program. It stores the list of messages and sends the whole list again with every call. The model reads the entire list from the top each time.
A working example
The program below keeps a messages list. Each call appends the user's message, sends the full list, then appends the assistant's reply so the next call includes it.
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 second answer works only because the second request contains the first exchange. Roles must alternate sensibly: user for what the person said, assistant for what the model said. The system message normally stays first.
Common errors
- Forgetting to append the reply. If you skip the
assistantmessage, the model sees two user messages in a row and has no record of what it said. - Sharing one global list between users. The example uses a module-level list for brevity. A real service needs one history per conversation, stored by a conversation ID.
- Appending before a failed call. If the request raises an error after you appended the user message, the history now ends with an unanswered user turn. Either remove it on failure or retry with the same list.
- Editing history by accident. The model treats everything in the list as true. A stale or altered message changes its answers.
History grows, and so does cost
Every turn resends everything, so the input size grows with each exchange. Token usage for a conversation of N turns grows roughly with the square of N, because turn k pays for all earlier turns. You pay for these input tokens each time, and latency rises with them.
The context window caps the total. When the history approaches the limit, the request fails or the output is cut short. Common strategies:
| Strategy | How it works | Trade-off |
|---|---|---|
| Sliding window | Keep the system message and the last N messages | Simple, but the model forgets early facts |
| Summarization | Ask the model to summarize old turns, then replace them with the summary | Keeps key facts, costs an extra call, may lose detail |
| Pinned facts | Store important facts in the system message | Reliable, but you must decide what to pin |
You can check usage.prompt_tokens in each response to see how large the history has become before you hit the limit.
Exercise
A chatbot answers the first question correctly but cannot recall anything from earlier turns on the second. The code builds a fresh messages list inside ask() on every call. What is wrong, and what is the fix?
Show answer
The API is stateless, so the model only knows what is in the current request. Creating a new list on each call discards the earlier turns. Keep the list outside the function (or in per-conversation storage), append each user message and each assistant reply to it, and send the full list every time.
Exercise
Your conversation's prompt_tokens is close to the model's context window. Name one strategy to keep the conversation going and one cost of it.
Show answer
Use a sliding window that keeps the system message and the most recent message pairs. The cost is that the model forgets facts from the dropped turns. Summarizing old turns is an alternative, at the cost of an extra API call and possible loss of detail.