Building Multi-Turn Conversations with Agents
Introduction & Overview
Welcome to the first lesson of this course on coordinating OpenAI agent workflows in JavaScript. In this course, you'll learn how to build conversational AI applications that can handle multi-turn conversations — that is, dialogues in which the user and the agent exchange several messages back and forth, rather than just a single question and answer.
A key challenge in building these applications is maintaining context: making sure the agent remembers what was said earlier in the conversation so its responses stay relevant and coherent. This is especially important for real-world use cases like travel assistants, customer support bots, or tutoring systems.
In this lesson, you'll see how to use the OpenAI Agents SDK for JavaScript to manage conversation history using the history property returned by the run function. You'll learn how to pass this history back into the agent for each new turn, enabling your agent to respond in a way that feels natural and context-aware.
By the end of this lesson, you'll know how to build stateful, multi-turn conversations in JavaScript using the OpenAI Agents SDK.
Understanding Multi-Turn Conversations
A multi-turn conversation is a dialogue in which the user and the agent exchange several messages, building up a conversation history. For example, a user might ask for a travel recommendation, then follow up with questions about the best time to visit or what to pack. The agent needs to remember previous messages to provide relevant and accurate responses.
A typical conversation history might look like this:
The main challenge is maintaining the context. If the agent forgets what was said earlier, its answers may become confusing or repetitive. By keeping track of the entire conversation history and providing it to the agent each time, you ensure the agent can generate answers that make sense in the context of the ongoing dialogue.
Using the history Property to Manage Conversation State
In the OpenAI Agents SDK for JavaScript, every time you call the run function, it returns a result object that includes a history property. This history array contains all the messages exchanged so far — both from the user and the agent.
To continue a conversation, you simply append new user messages to this history array and pass the updated array back into the next run call. This way, the agent always has access to the full conversation context, allowing it to generate coherent, context-aware responses.
Let's walk through a practical example to see how this works in code.
