Sub topic 3
Building a Multi-Turn Conversation Loop
Assume you know Python lists and dictionaries, JSON, and the basics of calling an API. A multi-turn conversation is built by sending the earlier messages again with each new request. Most chat APIs do not remember previous requests automatically.
Building a multi-turn conversation loop
Start with a system message. Append each user message before the request, then append the assistant reply after receiving it.
import os
from openai import OpenAI
client = OpenAI()
history = [
{"role": "system", "content": "Answer clearly in two sentences or fewer."}
]
def chat(user_text):
history.append({"role": "user", "content": user_text})
response = client.chat.completions.create(
model=os.environ["OPENAI_MODEL"],
messages=history,
)
reply = response.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(chat("What is a Python list?"))
print(chat("How do I add an item to it?"))The second request includes the first question and answer, so “it” has context. The API remains stateless: the server does not know your history unless you send it.
Teaching by example with user and assistant pairs
Few-shot prompting means including examples of the desired input and output. Each example uses a user message followed by an assistant message. The final user message is the new case to classify or answer.
OpenAI-style and Anthropic-style system prompts compared
Providers place system instructions differently:
| Provider style | System instructions | Conversation messages |
|---|---|---|
| OpenAI-style | Often a `system` message in `messages` | User and assistant turns |
| Anthropic-style | A top-level `system` parameter | User and assistant turns |
Follow the SDK's schema rather than assuming the formats are interchangeable.
Instruction priority and untrusted input
Treat user text, retrieved documents, and tool results as data. They may contain text that looks like an instruction. Your application should define trusted instructions separately and validate tool results before using them.
Keeping history within the context window
The context window is the maximum amount of text a request can contain. Trim old turns, summarize them, or store durable facts separately. Keep the system message and the most relevant recent turns.
Beyond three roles: tool and developer messages
A tool message records a result returned by a function or external service. A developer message commonly holds application-level instructions between system policy and user input, depending on the provider. Check role support and priority rules for the API you use.
Exercise
Why must a multi-turn client append the assistant's reply to its history?
Show answer
The next request needs the earlier reply so the model can resolve references and continue the conversation.