Sub topic 3
Keeping the Conversation as a List of Messages
This chapter assumes you know basic Python (functions, lists, dictionaries, exceptions) and can run programs in a terminal. You should also know that a chat API takes messages in and returns a reply. The previous chapters explained that these APIs are stateless and showed a minimal input loop. Here you will turn the memory of the conversation into a data structure.
The history is the memory
The model remembers nothing between requests. Whatever the bot "remembers" is a Python list that your program builds and sends in full on every turn. Each item in the list is a message, which is a dictionary with two keys:
rolesays who produced the message.contentholds the text.
Three roles matter for a basic chatbot:
| Role | Who writes it | Purpose |
|---|---|---|
| `system` | You, the developer | Sets the bot's behavior. Covered in the next chapter. |
| `user` | The person at the keyboard | Each question or statement. |
| `assistant` | The model | Each reply the model returned. |
Because messages are plain dictionaries, the history is easy to print, slice, test, and save as JSON.
How the list grows
Each successful turn adds exactly two messages: the user's text, then the model's reply. After two turns the list looks like this:
history = [
{"role": "system", "content": "You are a concise, helpful assistant."},
{"role": "user", "content": "My name is Priya."},
{"role": "assistant", "content": "Nice to meet you, Priya."},
{"role": "user", "content": "What is my name?"},
]When the program sends this list, the model sees the earlier turn and can answer "Priya". If you sent only the last message, it could not.
The loop that maintains it
This is the loop from the topic's first example. The two append calls are the whole memory mechanism.
def complete(messages):
"""Send the full message list to a model and return the reply text.
Replace this body with a call to your chosen provider's SDK."""
raise NotImplementedError
def main():
history = [{"role": "system", "content": "You are a concise, helpful assistant."}]
while True:
try:
user_text = input("you> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not user_text:
continue
if user_text == "/quit":
break
history.append({"role": "user", "content": user_text})
reply = complete(history)
history.append({"role": "assistant", "content": reply})
print(f"bot> {reply}")
if __name__ == "__main__":
main()Replace the body of complete with a call to your provider's SDK before running it. As written, it raises NotImplementedError.
Common errors
- Forgetting to append the reply. If you print the reply but never add it to
history, the model sees only your side of the conversation. Its later answers will seem to ignore what it said before. - Sending only the latest message. The bot then behaves as if every turn is the first.
- Creating the list inside the loop. Writing
history = [...]insidewhile Trueresets the memory each turn. Create it once, before the loop. - Breaking the alternation. Many providers reject or mishandle two
usermessages in a row, or a history that does not start with a user message after the system message. Keep the order user, assistant, user, assistant. - Mutating a list you did not mean to share.
historyis passed tocompleteby reference. Ifcompletemodifies it, your history changes too. Treat it as read-only inside the model function.
Why a plain list is enough
A list of dictionaries keeps three useful properties. It preserves order, which the model needs. It can be sliced, so the next chapters can trim old turns. It is JSON-compatible, so you can save it to disk and reload it. You do not need a class or a database yet.
Exercise
A learner's bot answers every question as if it were the first message. The code builds history = [system_message] at the top of the while True loop body, appends the user message, calls complete(history), and prints the reply. Give two separate defects and the fix for each.
Show answer
First, the list is recreated on every iteration, so earlier turns are discarded. Move the creation of history above the loop. Second, the assistant reply is never appended, so even with the list outside the loop the model would not see its own earlier answers. Add history.append({"role": "assistant", "content": reply}) after the call to complete.
Exercise
After the system message and three completed turns, how many messages are in the history, and which roles appear in which order?
Show answer
Seven messages. The order is system, then user, assistant, user, assistant, user, assistant. Each completed turn adds one user and one assistant message to the single system message.