Maintain conversation state across LLM API calls

A follow-up prompt needs the earlier conversation to interpret phrases such as β€œmake it shorter.” With the Responses API, a stored response ID can connect the next request to its history. Your application still owns the conversation record, its user access rules and the order in which turns are committed.

Choose a state strategy

Use Python 3.14 and openai==3.58.0. Configure OPENAI_API_KEY securely and set OPENAI_MODEL to a Responses-compatible model available to your account. The example makes two generation requests when run against the real service.

This procedure uses previous_response_id with stored responses. Other supported choices include explicitly supplying the prior input and output items, or using a Conversations object for durable state. Choose one strategy for a request. conversation and previous_response_id cannot be supplied together. Conversation-state guide , Responses reference .

Chain two completed turns

Save this script as conversation.py. Its fixed instructions are supplied on both requests because top-level instructions are specific to the request that provides them.

Python
import os
from openai import OpenAI

instructions = "Help edit release notes. Do not invent product features."
model = os.environ["OPENAI_MODEL"]

def require_text(response):
    if response.status != "completed":
        raise RuntimeError("The turn did not complete")
    refused = any(
        part.type == "refusal"
        for item in response.output if item.type == "message"
        for part in item.content
    )
    if refused or not response.output_text.strip():
        raise RuntimeError("The turn has no usable text answer")
    return response.output_text

with OpenAI(timeout=30.0, max_retries=0) as client:
    first = client.responses.create(
        model=model,
        instructions=instructions,
        input="Write release notes for a CSV export feature.",
        store=True,
    )
    print(require_text(first))
    latest_id = first.id

    second = client.responses.create(
        model=model,
        instructions=instructions,
        previous_response_id=latest_id,
        input="Make it one sentence and keep only the stated feature.",
        store=True,
    )
    print(require_text(second))
    latest_id = second.id

The second request includes the first response's ID and only the new user message. The model can use the chained context to resolve β€œit.” Wording is nondeterministic, so the important observable checks are that the second request references the first ID and that the application advances its pointer only after accepting a completed answer.

Persist the pointer with its owner

For a service, store the latest response ID beside your application's conversation ID and authenticated owner ID. Look it up through an ownership-checked query. Never put all users behind one global latest_id, and do not accept an arbitrary previous-response ID from a client as proof of access.

Serialize turns within one conversation, or use a version check when updating the pointer. Two requests based on the same previous ID create branches. If branching is not part of the product, a conditional update can reject a stale writer instead of silently overwriting the newer turn. Save the accepted input, response ID and completion state together for recovery.

Do not automatically replay a timed-out turn without a recovery policy. A timeout does not prove the provider never processed the request. The sample disables SDK retries to make each attempted request explicit, while a production service should define its own bounded retry and reconciliation behavior. SDK error and retry behavior .

Account for retention and context growth

Chaining reduces the conversation data you send manually. It does not make earlier input free or remove context-window limits. Establish a summarization or conversation-reset policy as histories grow. If managing history manually, preserve the API's required output items and tool interactions rather than retaining only visible text.

store=True is an intentional storage choice. Review the account's applicable data controls and retention settings before using this pattern with sensitive information. store=False belongs to a different state-management design and is not a promise that all provider logging disappears. Data controls .

The two-turn payload sequence, repeated instructions and failure-before-pointer-update behavior were checked with mocked responses. No remote conversation was created during verification.

Question provenance

This article addresses OpenAI API continuing conversation in a dialogue , asked by Charmalade on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored. No answer text or code is reproduced.

Author: Herman Schoenfeld