Sub topic 8
Building a multi-turn conversation loop
This chapter assumes you can write basic Python, work with lists and dictionaries, and have called an HTTP API or an SDK before. You also need to know that each chat message has a role and content, and that the model only sees what you send in each request.
The idea: you keep the memory
A chat API is stateless. The server does not remember your last request. A multi-turn conversation is therefore something your code builds. You keep a list of messages, add each new user message to it, send the whole list, and add the model's reply to it before the next turn.
The loop has four steps:
- Append the user's text as a
usermessage. - Send the full history to the model.
- Read the reply text.
- Append that text as an
assistantmessage.
A working loop
The history starts with a system message. It stays at the front for the whole conversation.
from openai import OpenAI
client = OpenAI()
history = [
{"role": "system", "content": "You are a helpful assistant. Keep answers under three sentences."}
]
def chat(user_text):
history.append({"role": "user", "content": user_text})
response = client.chat.completions.create(
model="MODEL_NAME", # replace with a chat model available to you
messages=history,
)
reply = response.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(chat("What is a list in Python?"))
print(chat("How do I add an item to it?"))The second question says "it". The model can resolve that word only because the first question and its answer are in history when the second request goes out.
After the two calls, history holds five messages in this order: system, user, assistant, user, assistant. Roles alternate after the system message, which is the ordering most providers expect.
What the loop sends
Each request is larger than the one before it. On turn three you send the system message plus both earlier exchanges plus the new question. The model reads all of it again, so you pay for those tokens again on every call. The reply to turn one is not cached by your code. It is only text in the list.
| Turn | Messages sent | Messages in history afterward |
|---|---|---|
| 1 | system, user | system, user, assistant |
| 2 | system, user, assistant, user | system, user, assistant, user, assistant |
| 3 | the five above, plus a new user | seven messages |
Common errors
- Forgetting to append the reply. If you skip step 4, the model sees only your questions. It will answer "it" questions as if it never said anything before.
- Using a fresh list per call. Creating
historyinside the function resets the conversation every time. - Appending the whole response object. Append a dictionary with
roleandcontent. Do not append the SDK response object itself. - Two user messages in a row. Some providers reject or merge consecutive messages of the same role. This happens when a call fails and you have already appended the user message. Remove it on failure, or append only after success.
- Sharing one global list between users. In a web service, keep one history per conversation, for example keyed by a session ID.
Growth and limits
The history grows without bound, but the context window does not. Long conversations will eventually fail or become expensive. A later chapter covers trimming in detail. The simplest approach keeps the system message and only the most recent turns:
def trim_history(messages, max_turn_messages=10):
system_messages = [m for m in messages if m["role"] == "system"]
others = [m for m in messages if m["role"] != "system"]
return system_messages + others[-max_turn_messages:]Pass trim_history(history) as messages when you call the API. Trimming an even number of messages keeps user and assistant turns paired. An odd count could leave the list starting with an assistant message, which some providers reject.
Exercise
Your chatbot answers the first question well, but when the user asks "Can you explain that more simply?", it replies as if it had never said anything. Your code builds history = [...] inside the chat function. What is wrong, and how do you fix it?
Show answer
Creating history inside the function resets the conversation on every call, so the model sees only the new user message. Move history outside the function (or store it per session) so it persists. Also make sure the assistant reply is appended after each call.
Exercise
After four completed turns, how many messages are in a history that began with one system message? What is the order of roles?
Show answer
Nine messages. The order is system, then user and assistant repeated four times: system, user, assistant, user, assistant, user, assistant, user, assistant.