Keep Conversation Context in an OpenAI API Chatbot
A chatbot needs a deliberate way to associate a follow-up with the correct conversation. The Responses API can link a new turn to a previous response ID. Keep that identifier alongside the conversation record on your server.
Worked example
Two turns in one model conversation
import OpenAI from "openai";
const client = new OpenAI();
const model = process.env.OPENAI_MODEL;
if (!model) throw new Error("Set OPENAI_MODEL first");
const first = await client.responses.create({
model,
input: "For this demo, the workshop room is Cedar-4. Acknowledge it."
});
const second = await client.responses.create({
model,
previous_response_id: first.id,
input: "Which room did I give you?"
});
console.log(second.output_text);Steps
- In a Node.js project, install the official openai SDK, set OPENAI_API_KEY in your server environment, and set OPENAI_MODEL to a model your project can use.
- Save the example as chat.mjs and run it. It sends a synthetic first turn, then links the follow-up to that response ID.
- In your app, bind the saved response ID to the authenticated conversation. When you start a new conversation, omit previous_response_id until there is a first response to reference.
What to check
- The linked follow-up should mention Cedar-4. Repeat the question in a fresh conversation with no saved response ID and check that your app never sends a prior session's ID.
- Previous turns still contribute to input token usage. If you use developer instructions, supply the current instructions with the request rather than assuming a previous request's instructions will carry forward.