Sub topic 3
Keeping the conversation as a list of messages
This chapter assumes you know Python lists, dictionaries, and exceptions. It also assumes you know that chat APIs are stateless, so the client has to resend the conversation on every request. Here you will see what that conversation looks like as data, which rules it must follow, and which mistakes corrupt it.
The shape of a message
Most chat APIs describe a conversation as an ordered list of messages. Each message is a dictionary with two fields:
rolesays who produced the message.contentholds the text.
history = [
{"role": "system", "content": "You are a concise, helpful assistant."},
{"role": "user", "content": "What is a list?"},
{"role": "assistant", "content": "An ordered, mutable sequence."},
{"role": "user", "content": "Can it hold mixed types?"},
]The list is the whole state of the chatbot. If you lose it, the bot forgets everything. If you corrupt it, the bot gets confused or the API rejects the request.
Plain dictionaries are a good choice for three reasons. They match what most provider SDKs accept. They print readably when you debug. They convert to JSON without extra work, which you will use when you save history to disk.
The roles
| Role | Written by | Purpose |
|---|---|---|
| `system` | You, the developer | Instructions that shape behavior for the whole conversation |
| `user` | The person at the keyboard | Questions and statements |
| `assistant` | The model | Earlier replies, sent back so the model can see what it said |
Some APIs add other roles, such as one for tool results. This chapter ignores them. Providers also differ in details. Some take the system text as a separate argument instead of a list entry. Read your provider's documentation for the exact format. The list-of-dictionaries design stays the same either way.
The model's own earlier replies must go back into the list. The model has no record of what it said, so to the API they are just more text to include.
The two-step rule
Every successful turn adds exactly two messages:
- Append the user's message.
- Call the model with the whole list, then append its reply as an
assistantmessage.
The order matters. The user message must be in the list before the call, because the model needs to see it. The reply can only be appended after the call returns.
A helper that performs both steps keeps the loop small and gives you one place to enforce rules. It takes the model function as a parameter, so you can pass a fake in tests.
def run_turn(history, user_text, complete):
history.append({"role": "user", "content": user_text})
try:
reply = complete(history)
except Exception:
history.pop()
raise
history.append({"role": "assistant", "content": reply})
return replyThe except branch removes the user message if the call fails. Without it, the list would end with a user message that never got an answer. The next attempt would then add a second user message in a row. A later chapter covers failure handling in more depth. For now, remember that a turn either adds both messages or leaves the list unchanged.
Rules worth enforcing
A well-formed history for a typical provider follows these rules:
- An optional
systemmessage comes first. - After that, roles alternate:
user,assistant,user,assistant, and so on. - The list ends with a
usermessage when you make a request. - Every
contentis a non-empty string.
Not every provider enforces all of these. Some reject two user messages in a row, and others merge them silently. Following the strictest version keeps your code portable. A small checker also turns a confusing API error into a clear message from your own code:
def check_history(history):
"""Raise ValueError if history breaks the rules for a chat request."""
if not history:
raise ValueError("history is empty")
rest = history[1:] if history[0]["role"] == "system" else history
expected = "user"
for i, message in enumerate(rest):
if message["role"] != expected:
raise ValueError(
f"message {i} has role {message['role']!r}, expected {expected!r}"
)
content = message["content"]
if not isinstance(content, str) or not content.strip():
raise ValueError(f"message {i} has empty or non-text content")
expected = "assistant" if expected == "user" else "user"
if not rest or rest[-1]["role"] != "user":
raise ValueError("history must end with a user message")Call check_history(history) just before the model call while you develop. It catches bugs early. You can remove it later or keep it as a cheap safety net.
Common errors
Forgetting to append the reply
If you print the reply but never append it, the bot remembers your questions and nothing it said. Its answers then seem to ignore earlier context, and the history contains consecutive user messages. When the bot seems to lose its own thread, print len(history) after each turn. It should grow by two.
Storing the wrong thing
SDKs usually return a response object, not a string. If you append the whole object as content, you get a history that cannot be serialized to JSON, or one that sends garbage back to the model. Extract the text inside your model function. The loop should only ever see strings.
Sharing the list by reference
Python passes a list by reference. The model function receives the same list object that your loop keeps mutating. If that function stores the list, for example to log it, the stored copy changes later. This program shows the effect:
def run_turn(history, user_text, complete):
history.append({"role": "user", "content": user_text})
try:
reply = complete(history)
except Exception:
history.pop()
raise
history.append({"role": "assistant", "content": reply})
return reply
by_reference = []
by_copy = []
def spy(messages):
by_reference.append(messages)
by_copy.append(list(messages))
return "ok"
history = [{"role": "system", "content": "s"}]
run_turn(history, "one", spy)
run_turn(history, "two", spy)
print([len(m) for m in by_reference]) # [5, 5]
print([len(m) for m in by_copy]) # [2, 4]
print(by_reference[0] is history) # TrueThe copy shows what the model actually saw on each call, which is 2 messages and then 4. The stored reference shows 5 for both, because it is the live list. list(messages) makes a shallow copy. That is enough here, because you never edit message dictionaries in place. Treat messages as immutable: add new ones and do not modify old ones.
Using a mutable default
Avoid writing def chat(history=[]). Python creates that default list once, so separate conversations would share it. Create the list inside main() or pass it in explicitly.
Sending blank input
An empty content is rejected by some APIs, and it wastes a turn on others. Strip the input and skip blank lines before you append anything. The chat loop in the previous chapter already does this with continue.
How the cost grows
Because the full list goes out on every request, each request is larger than the last. Suppose every message is about 50 tokens, and ignore the system message. Turn 1 sends 1 message, or 50 tokens. Turn 2 sends 3 messages, or 150 tokens. Turn 10 sends 19 messages, or 950 tokens. The total sent across 10 turns is 50 × 10², which is 5,000 tokens. Doubling the length of the conversation roughly quadruples the total input.
This growth explains why the list cannot stay unbounded. It costs more per turn, it slows each response, and eventually it exceeds the model's limit. Later chapters cover the context window and how a sliding window keeps the list within it.
Summary of the design
- Keep one list of
{"role", "content"}dictionaries as the only conversation state. - Add user and assistant messages together, in that order, around each model call.
- Keep roles alternating and the content as plain strings.
- Roll back the user message if the call fails.
- Treat the list as shared state. Copy it if you need a snapshot, and do not edit old messages.
Exercise
A user reports that after a network error, every later reply from your bot is strange, and a debug print shows the history has two user messages in a row. Which part of the turn logic is missing, and how do you fix it?
Show answer
The code appended the user message, then the model call raised an exception, and nothing removed that message. The next turn added another user message after it. Fix it by wrapping the call in try/except, calling history.pop() to remove the unanswered user message, and re-raising the exception. Then a failed turn leaves the history unchanged.
Exercise
After 3 successful turns with a system message, how many messages are in the history, and what was the last message in the list at the moment of the third model call? Explain how you got each answer.
Show answer
The history has 7 messages: 1 system message plus 2 messages for each of the 3 turns. At the third call, the history held 6 messages (1 system, 2 for each of the first two turns, and the new user message), and the last one was the third user message. The assistant reply is only appended after the call returns.
Exercise
Your logging code stores the list that your model function receives. Later, the logs show conversations that are longer than what the model actually saw. Why does this happen, and what is a one-line fix inside the model function?
Show answer
The logger stored a reference to the live history list, and the loop kept appending to it after the call. Store a snapshot instead, for example log.append(list(messages)). This shallow copy is enough because messages are not edited in place.