Lompat ke konten

Pelajaran 5 ยท Generating Text

Conversation State: Multi-Turn Chats

Build multi-turn chats with a manual history list, previous_response_id or the Conversations API, and manage storage, retention, cost and context limits.

A model does not remember your last request on its own. If a user writes "make it shorter," the model needs to see what "it" is. Conversation state is the history that gives each new turn its context. You decide who keeps it: your program, or OpenAI's servers on your behalf.

There are three approaches. Each is useful, and they differ in control, storage and convenience.

Three ways to keep state

Manual history You resend the items
Response chaining previous_response_id
Conversation object A durable server record

In every case, earlier tokens are still processed.

1 / 2

Manual history

You keep a list and send all of it each time. After each reply, you add the model's output items, then the next user message.

Python
# Read-only
history = [{"role": "user", "content": "Suggest a name for a hiking club."}]

first = client.responses.create(model="gpt-6.2-sol", input=history, store=False)

history += first.output          # keep every output item
history.append({"role": "user", "content": "Make it shorter."})

second = client.responses.create(model="gpt-6.2-sol", input=history, store=False)
print(second.output_text)

Add the whole output list, not only the text. With reasoning models, the output can contain reasoning items and other details that belong in the next request. For stateless requests, reasoning items carry encrypted content that you pass back unchanged. Also avoid editing earlier items. OpenAI's guidance says that changing history can cause reasoning to be dropped, which can lower quality and raise token use.

Chaining with previous_response_id

Instead of resending history, pass the ID of the previous response.

Python
# Read-only
first = client.responses.create(
    model="gpt-6.2-sol", input="Suggest a name for a hiking club."
)
second = client.responses.create(
    model="gpt-6.2-sol",
    previous_response_id=first.id,
    input="Make it shorter.",
)

Your code is simpler, but the service now stores the earlier responses. Chaining does not make history free: all earlier input tokens in the chain are still billed as input tokens.

The Conversations API

For long-lived chats that continue across sessions or devices, you can create a conversation object and reference it.

Python
# Read-only
conversation = client.conversations.create()

response = client.responses.create(
    model="gpt-6.2-sol",
    conversation=conversation.id,
    input=[{"role": "user", "content": "Suggest a name for a hiking club."}],
)

The conversation stores items such as messages, tool calls and tool outputs. Save the conversation ID in your own database, next to the user it belongs to, and always check that the signed-in user owns it before you use it.

Storage and retention

As of December 2026, OpenAI's documentation says that responses are stored by default, for 30 days or longer (its pages word the period slightly differently), and you can turn this off with store=False. Items in a conversation are not limited by that 30-day period. Organizations approved for Zero Data Retention have store treated as false, and some features that need stored state may not be available to them.

Before you choose, ask what your privacy policy promises and what your users expect. The production checklist returns to data handling.

History grows, so manage it

Every model has a context window, the most tokens it can handle in one request, counting input, output and reasoning. A long chat can approach it, and even before that it gets slower and more expensive. You have several options.

  • Trim: keep the developer rules and only the latest turns.
  • Summarize: replace old turns with a short summary you ask the model to write.
  • Start fresh: begin a new conversation when the topic changes.
  • Server-side compaction: the Responses API can compact long context, with a threshold setting or a separate compact endpoint. See the current compaction guide.

This stand-in shows trimming by whole turns. It estimates tokens with a rough rule of four characters per token, which is only a teaching shortcut.

Python Trim old turns to fit a token budget

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real histories with tool calls need extra care: a tool call and its result must be kept or removed together. For exact input counts, the API has a token counting endpoint, shown in tokens, costs and caching.

State is not long-term memory

A conversation history is short-term context. If your app should remember a user's preferences next month, store those facts in your own database, show users what you keep, let them delete it, and add only the relevant facts to a new request. Long-term agent memory goes deeper.

Never share one history list between users. A global variable in a web server can easily mix two people's messages. Key every history by user and conversation, and check ownership.

Choose an approach

Your situation A reasonable choice
Single question and answer No state at all
You need full control or minimal server storage Manual history with store=False
A short chat in one session previous_response_id
A chat resumed over days or across devices A conversation object

Whatever you choose, plan what happens when the state is gone. A stored response can expire, a user can ask for deletion, or your own database can lose the ID. Your app should handle a "not found" error by starting a new conversation, perhaps with a short summary that you kept yourself.

Deleting data

If users can delete a chat in your app, deletion should reach every copy: your database, your logs and backups according to your retention policy, and any server-side objects you created with the API. Check the API reference for how to delete responses and conversations, and test that your delete button really does it. A button that only hides a chat on screen misleads the user.

Also consider shared devices and support staff. Limit who can read stored chats, and record access.

Test multi-turn behavior

Single-turn tests miss many chat bugs. Write short scripts of several turns and check the later answers. Does "make it shorter" refer to the right text? Does a rule from the developer message still hold after ten turns? What happens after you trim history? What if the user changes the topic and then returns? Run the same scripts again after you change your trimming or summary logic.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In manual state handling with reasoning models, what should you add to history?

    Output can include reasoning and other items that the next request should receive.
  2. 2. Are earlier tokens free when you use previous_response_id?

    Chaining saves you code and upload work, not input token charges.
  3. 3. What does store=False do?

    By default, responses are stored for a period; store=False opts out.
  4. 4. Which is a good way to handle a very long chat?

    Keep the important rules and recent turns, and reduce older material.

Summary

  • Models need the relevant history in each turn.
  • You can resend items yourself, chain responses, or use a conversation object.
  • Keep all output items and do not rewrite earlier ones.
  • Know what is stored and for how long, and check conversation ownership.
  • Manage growing history to control context size and cost.

Next: Streaming Responses

Progres Anda disimpan di browser ini. Tidak perlu akun.