Message Management and Multi-Turn Conversations
🎯 Introduction
In the previous article, you learned to control model generation. In a real chat, however, users often leave parts of a question implicit. They might ask for an introduction to TypeScript, then say, "Explain that more simply." If the second request contains only this sentence, the model has no basis for knowing what to simplify.
Continuing with AIHubMix + the OpenAI SDK, this article explains how to pass message history through messages and build a continuous conversation with two real model calls. We will then consider what happens as the history grows.
🧱 Why Multi-Turn Conversations Need Message History
Chat Completions generates answers from the messages included in the current request. A previous call does not automatically tell the model what your program sent last time.
Suppose the user sends these two questions in sequence:
User: Introduce TypeScript in one sentence.
Model: TypeScript is a programming language that adds a type system to JavaScript.
User: Explain that more simply.
The second question does not mention TypeScript. To identify the subject of the follow-up, include the previous question and answer in the second request.
| Contents of the second request | Context available to the model |
|---|---|
| Only "Explain that more simply" | It cannot identify the text to rewrite and must guess or ask for more information |
| First question + first answer + follow-up question | It can continue using the earlier explanation of TypeScript |
What matters is whether your application supplies the context required for the current question, rather than whether the model appears to have memory.
How Should You Organize Message History?
Text Generation and Model Parameters introduced system and user. Multi-turn conversations add the important assistant role, which represents what the model said previously.
const messages = [
{ role: "system", content: "Answer technical questions in concise, accurate Chinese." },
{ role: "user", content: "Introduce TypeScript in one sentence." },
{ role: "assistant", content: "TypeScript is a programming language that adds a type system to JavaScript." },
{ role: "user", content: "Explain that more simply." }
];
These messages represent response instructions, the user's first question, the model's answer, and a follow-up question. Keeping them in conversational order lets the model distinguish the current question from earlier exchanges.
The assistant text above is a written example illustrating the message structure. In an application, append the actual answer returned by the first request to messages, rather than hard-coding an answer beforehand.
🛠 Make Two Real Model Calls
Continue with the ai-sdk-course project from the previous two articles. Use Node.js 24.x and openai@7.62.0, reusing AI_API_KEY, AI_BASE_URL, and AI_MODEL from .env. You do not need to reinstall dependencies.
Create 03.conversation.mjs in the project root:
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.AI_API_KEY,
baseURL: process.env.AI_BASE_URL
});
const messages = [
{
role: "system",
content: "Answer technical questions in concise, accurate Chinese."
},
{
role: "user",
content: "Introduce TypeScript in one sentence."
}
];
// Turn 1: Send the question and save the actual model answer
const first = await client.chat.completions.create({
model: process.env.AI_MODEL,
messages
});
const firstChoice = first.choices[0];
const firstAnswer = firstChoice?.message?.content;
if (firstChoice?.finish_reason !== "stop" || !firstAnswer?.trim()) {
throw new Error(`Invalid answer in turn 1 (finish reason: ${firstChoice?.finish_reason ?? "unknown"})`);
}
messages.push({ role: "assistant", content: firstAnswer });
console.log("Turn 1 answer:", firstAnswer);
// Turn 2: Add the follow-up and include all previous messages
messages.push({ role: "user", content: "Explain that more simply." });
const second = await client.chat.completions.create({
model: process.env.AI_MODEL,
messages
});
const secondChoice = second.choices[0];
const secondAnswer = secondChoice?.message?.content;
if (secondChoice?.finish_reason !== "stop" || !secondAnswer?.trim()) {
throw new Error(`Invalid answer in turn 2 (finish reason: ${secondChoice?.finish_reason ?? "unknown"})`);
}
messages.push({ role: "assistant", content: secondAnswer });
console.log("Turn 2 answer:", secondAnswer);
Run this from the project root:
node --env-file=.env 03.conversation.mjs
If your network requires a local HTTP proxy to reach AIHubMix, use the approach verified in Introduction to AI SDKs and Environment Setup:
HTTPS_PROXY=http://127.0.0.1:7890 NODE_USE_ENV_PROXY=1 node --env-file=.env 03.conversation.mjs
Your terminal might display:
Turn 1 answer: TypeScript is a programming language that adds a type system to JavaScript.
Turn 2 answer: Think of TypeScript as JavaScript with type checking, helping you catch some errors earlier while writing code.
This is illustrative output; the actual wording depends on the model. The important point is that the second turn continues explaining TypeScript, regardless of its exact phrasing.
Which Messages Does Each Request Send?
Although the code calls chat.completions.create() twice, the two calls send different messages:
| Request | Contents of messages |
|---|---|
| Turn 1 | system response instructions → user first question |
| Turn 2 | system response instructions → user first question → assistant first answer → user follow-up |
The order of the two appends is essential: after turn 1 returns, add the actual firstAnswer to the history as an assistant message. Before requesting turn 2, add the new user follow-up.
Both steps are required. Adding only the second question leaves the model without the earlier discussion. Keeping only the first question while discarding its answer also prevents the model from knowing exactly what it explained previously.
After turn 2, the code appends secondAnswer to messages. The array now contains both complete exchanges, ready for a third turn.
Here, messages exists only while the current Node.js program runs. To reuse the history on the next model call, pass it again. Persisting Conversation History will cover database persistence to restore chats after a server restart or page refresh.
⚖️ Message History Keeps Growing
The example has only two turns, so its history is short. Including every message each time makes subsequent requests progressively larger.
| Current turn | Contents required in this request |
|---|---|
| Turn 1 | First user question |
| Turn 2 | Turn 1 question and answer + second question |
| Turn 3 | First two exchanges + third question |
| Turn 10 | First nine exchanges + tenth question |
The table omits the system message, which remains present throughout. Longer histories generally use more input tokens, potentially increasing costs and approaching the model's context window limit.
Can You Keep Only the Most Recent Turns?
Yes, depending on your application. The simplest approach is to keep general instructions and select the most recent complete exchanges.
For example, assume the first entry in messages is a system message, followed by complete exchanges in user, assistant order, with no unanswered user message at the end:
const recentMessages = [
messages[0],
...messages.slice(1).slice(-6)
];
This keeps at most the last three complete exchanges (six messages) as the history for the next request, after which you append the new user message. If an unanswered user message is already present, this slice no longer guarantees three complete exchanges. Separate completed history from the current question first.
However, the most recent messages may not contain the most important information. If the user requested "Use TypeScript examples from now on" in the first turn, dropping the earliest messages may remove that instruction. Real applications often distinguish lasting requirements from ordinary conversation history instead of mechanically removing the oldest messages.
For now, focus on maintaining message history manually. Later courses cover more complex long-term memory, summary compression, and agent memory strategies.
❓ Knowledge Check
Q1: Why include the first model answer in the second request? Is the first question alone enough?
A follow-up may refer to the exact wording or content of the previous answer. For example, "Expand on your second point" cannot reliably identify that point without the preceding answer, even if the original question is retained.
Q2: Is message history the same as chat records stored in a database?
No. Message history is the context supplied to the model for this request, and may include only part of a conversation. Database chat records are data the application saves to display, query, and restore sessions. They can overlap but serve different purposes.
🧪 Exercise
Using 03.conversation.mjs, complete these exercises:
- Change the first question to "Explain Vue 3's reactivity system in one sentence" and the second to "Explain it again using a form input scenario". Check whether the second answer continues discussing reactivity.
- Temporarily send only one
usermessage in the second request, omitting the first exchange. Compare the answers and explain the difference. An occasional correct guess does not mean the model received the history. - Restore the full history and confirm that, after two turns,
messagescontains onesystemmessage + twousermessages + twoassistantmessages in conversational order.
Success criteria: Make two model calls independently, know when to append user and assistant messages, and explain why follow-up questions depend on historical context.
🎉 You have implemented a multi-turn conversation and learned how to pass message history. Next, you will stream output so generated content appears incrementally.
