Sub topic 8
Building a Multi-Turn Conversation Loop
What this chapter assumes
You should already know the role and content fields of a chat message. You should also know that a chat API is stateless, meaning the server keeps no memory between requests. The code uses Python with the OpenAI and Anthropic SDKs, and it assumes you have an API key set in your environment. Replace MODEL_NAME with a chat model you can use.
This chapter turns those ideas into a working loop. It also covers the errors that show up once you run that loop for more than a few turns.
The working model
A multi-turn conversation is a list that you grow yourself. Each turn follows the same four steps:
- Append the new user message to the list.
- Send the whole list to the API.
- Read the reply text from the response.
- Append that text to the list as an assistant message.
The model never "remembers" turn 1 when it answers turn 2. You send turn 1 again, inside the history, and the model reads it as part of the input. Your list is the conversation, and the API only transforms it into one more message.
A minimal chat function
This is the smallest version that works. The history starts with one system message, and every call to chat extends it.
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" and "an item" without naming Python or lists. The model can resolve "it" only because the first question and its answer are in the list you sent.
What each request contains
The history grows by two messages per turn, so each request is larger than the last.
| Turn | Messages sent | Contents |
|---|---|---|
| 1 | 2 | system, user 1 |
| 2 | 4 | system, user 1, assistant 1, user 2 |
| 3 | 6 | system, user 1, assistant 1, user 2, assistant 2, user 3 |
| n | 2n | system plus every earlier pair, plus the new user message |
The system message is sent every time, but it is stored once. You keep it at the start of the list and never add it again.
This growth has a cost. Providers bill for input tokens on every request, so the total tokens you pay for across a conversation grow faster than the conversation length. A long chat also eventually exceeds the model's context window. The last section covers trimming.
Wrapping the state in a class
A module-level history list works in a demo. In a real program, every user session needs its own list. If two users share one global list, they see each other's messages. A small class keeps the state and the logic together.
from openai import OpenAI
class Conversation:
def __init__(self, client, model, system_prompt):
self.client = client
self.model = model
self.messages = [{"role": "system", "content": system_prompt}]
def send(self, user_text):
self.messages.append({"role": "user", "content": user_text})
try:
response = self.client.chat.completions.create(
model=self.model,
messages=self.messages,
)
except Exception:
# Remove the unanswered user message so the history stays valid.
self.messages.pop()
raise
reply = response.choices[0].message.content or ""
self.messages.append({"role": "assistant", "content": reply})
return replyTwo details in send matter in practice:
- The
tryblock removes the user message if the request fails. Without it, a network error or rate limit leaves a user message with no answer. A retry then appends a second user message, and the history contains two user turns in a row. Some providers reject that, and others handle it in ways you did not intend. content or ""guards against aNonecontent value. This can happen when a reply has no text, for example when the model returns a tool call instead of text.
An interactive loop
Add a terminal loop on top of the class to get a working chat program.
from openai import OpenAI
def main():
convo = Conversation(
OpenAI(),
"MODEL_NAME", # replace with a chat model available to you
"You are a helpful assistant. Keep answers under three sentences.",
)
print("Type 'quit' to exit.")
while True:
text = input("you> ").strip()
if text.lower() in {"quit", "exit"}:
break
if not text:
continue
print("bot>", convo.send(text))
if __name__ == "__main__":
main()The loop skips empty input. Sending an empty user message wastes a request, and some APIs reject empty content.
The same loop with the Anthropic Messages API
The loop is identical except for where the system prompt goes. The Anthropic API takes it as a top-level system argument, so the messages list holds only user and assistant turns. It also requires max_tokens.
import anthropic
client = anthropic.Anthropic()
SYSTEM = "You are a helpful assistant. Keep answers under three sentences."
messages = []
def chat(user_text):
messages.append({"role": "user", "content": user_text})
response = client.messages.create(
model="MODEL_NAME", # replace with a model available to you
max_tokens=300,
system=SYSTEM,
messages=messages,
)
reply = response.content[0].text
messages.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?"))Common errors
Forgetting to append the assistant reply
If you append the user message but not the reply, the next request contains two user messages in a row. The model sees every question you asked and none of its own answers. The symptom is that the model repeats itself or loses the thread. Always store the reply before returning it.
Storing the response object instead of the text
response.choices[0].message is an object, not a dictionary with the fields you want. Appending it directly can fail validation or send the wrong shape. Build a plain dictionary with role and content as shown above.
Repeating the system message
If you insert the system message at the start of every chat call, the history fills with duplicates. These cost tokens and can confuse the model. Create the system message once, when the conversation starts.
Sharing one list across sessions
A global list is shared by every caller. In a web server with many users, create one Conversation per session and store it by session ID.
Ignoring truncated replies
Replies can stop early when they hit the output token limit. The OpenAI response reports this as finish_reason == "length", and the Anthropic response reports stop_reason == "max_tokens". If you store a cut-off reply, the model sees its own half-finished sentence on the next turn. Check the stop reason and decide whether to raise the limit, retry, or tell the user.
Letting history grow without limit
Every turn adds tokens. At some point the request is rejected for exceeding the context window, or each call becomes slow and expensive. Plan for this before you ship.
Keeping the history bounded
The simplest strategy keeps the system message and only the most recent messages.
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:]Call it before each request, for example messages=trim_history(convo.messages). This keeps the stored list complete and sends only the trimmed copy.
Pick an even number for max_turn_messages. An odd number can cut a user and assistant pair in half, so the trimmed history starts with an orphaned assistant message. Some providers require the first non-system message to be a user message.
Trimming has a trade-off. The model forgets anything older than the window, including facts the user stated early on, such as their name or a constraint on the task. Alternatives include summarizing old turns into one message, or pinning important facts into the system message. Both are more work than dropping messages, and a summary can lose detail.
Checklist for a correct loop
- The system message is created once and stays first in the list.
- Each turn appends the user message, sends the full list, then appends the reply as an assistant message.
- A failed request removes the unanswered user message.
- Each session owns its own list.
- Stop reasons are checked for truncation.
- The history sent to the API is bounded.
Exercise
Your chat program works for the first question, but on the second turn the model answers as if it never saw the first one. The code appends the user message before each call but never appends the response. What is wrong, and what is the fix?
Show answer
The assistant reply is never stored in the history, so each request contains only user messages and no earlier answers. The API is stateless, so the model sees only what you send. Fix it by appending {"role": "assistant", "content": reply} to the history after each response, before the next user message is added.
Exercise
A request fails with a rate-limit error inside your send method, and you catch it and ask the user to try again. On the retry, the history contains two user messages in a row. How do you prevent this, and where in the code does the fix go?
Show answer
Remove the unanswered user message when the request fails, for example by calling pop() on the messages list inside an except block around the API call, and then re-raise the error. Alternatively, build a copy of the history with the new user message for the request, and commit the user message and reply to the stored history only after the call succeeds.
Exercise
A conversation has one system message and 14 user and assistant messages. You call trim_history(messages, 5). How many messages are returned, and what is the risk of using 5?
Show answer
Six messages are returned: the system message plus the last five of the others. Five is odd, so the oldest kept message is an assistant message whose user question was dropped. Some providers reject a history that starts with an assistant message, and the model loses the question that the reply answered. Use an even number such as 4 or 6.