> ## Documentation Index
> Fetch the complete documentation index at: https://docs.inputapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 多轮对话

> 维护消息历史，让后续问题引用前文。

## 消息历史由谁保存

Chat Completions 每次请求只看到本次发送的 `messages`。复用同一个 SDK 客户端或 API Key，并不会自动把上一次的消息加入请求。

一个普通文本会话按顺序发送：用户问题、模型回复、下一条用户问题。不同用户和不同会话的历史要分开保存；同一会话并发提交时，应固定本次历史快照，避免回复顺序错乱。

## 两轮完整示例

先按 [Python SDK](/zh/guides/python.md)安装依赖并设置三个环境变量，选择支持 Chat Completions 的普通文本模型。保存为 `conversation.py`，运行 `python conversation.py`。示例会发起两次真实请求，第二次携带第一次返回的文本。

```python theme={null}
import os
from openai import OpenAI, APIConnectionError, APIStatusError

messages = []
with OpenAI(
    base_url=os.environ["API_BASE_URL"].rstrip("/"),
    api_key=os.environ["API_KEY"],
    timeout=60.0,
    max_retries=0,
) as client:
    try:
        for prompt in ["Suggest a short name for a coffee shop.", "Explain that name in one sentence."]:
            messages.append({"role": "user", "content": prompt})
            result = client.chat.completions.create(
                model=os.environ["API_MODEL"],
                messages=messages,
            )
            choice = result.choices[0] if result.choices else None
            if (choice is None or choice.finish_reason != "stop"
                    or choice.message.refusal or choice.message.tool_calls
                    or not choice.message.content):
                raise SystemExit("Conversation turn did not produce a complete text reply.")
            messages.append({"role": "assistant", "content": choice.message.content})
            print(choice.message.content)
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). Check the request logs.")
    except APIConnectionError:
        raise SystemExit("Connection failed. Check the API address and network.")
```

此例仅处理普通文本，并在拒答、截断或工具调用时停止。带工具调用的会话必须保留完整的 assistant 工具调用和对应工具结果；需要推理字段或其他协议扩展的模型，也应按其协议保存必要字段，不能只复制 `content`。参见[工具调用](/zh/guides/tool-calling.md)。

## 控制上下文长度

发送前检查目标模型的上下文上限，为当前输入和回复留出空间。历史越长，每次请求携带的数据越多。可保留最近的完整轮次，并对更早的内容做业务允许的摘要；摘要可能丢失细节，不能代替必须精确保留的原文。

不要把工具调用与它的结果拆开裁剪，也不要为了缩短历史而移除应用必要的系统指令。收到上下文超限错误时，先调整历史，再重试；直接重发同一负载通常无法解决。

## Responses 的会话状态

Responses 可以由调用方在 `input` 中显式携带必要上下文。使用 `previous_response_id` 则依赖渠道的响应保存、ID 可见性和路由行为，需要部署管理员确认；不要混用来自其他服务或其他渠道的响应 ID。

后续请求中的系统指令、工具定义等，应按所用模型和协议要求重新提供，不要把响应关联当作“所有配置自动继承”。详见 [Responses 参考](/zh/api-reference/responses.md)。

## Python：Responses 显式维护历史

保存为 `responses-conversation.py`，按 [Python SDK](/zh/guides/python.md)配置后运行 `python responses-conversation.py`。每轮重新发送 `instructions` 和完整历史，不使用 `previous_response_id`，不依赖服务端保存上一轮响应。

此例要求渠道支持 Responses 输入项重放、`store: false` 和 `include: ["reasoning.encrypted_content"]`。需要推理上下文的模型必须保留响应中的相关项目；如果渠道不支持这些字段或无法返回模型所需状态，请先确认兼容方案，不能仅删除推理项来绕过错误。`store: false` 不承诺网关或上游的日志保留策略。

```python theme={null}
import os
from openai import OpenAI, APIConnectionError, APIStatusError

history = []
with OpenAI(base_url=os.environ["API_BASE_URL"].rstrip("/"),
            api_key=os.environ["API_KEY"], timeout=60.0, max_retries=0) as client:
    try:
        for prompt in ["Suggest a short name for a coffee shop.", "Explain that name in one sentence."]:
            history.append({"role": "user", "content": prompt})
            result = client.responses.create(
                model=os.environ["API_MODEL"], input=history,
                instructions="Answer briefly in plain text.",
                store=False, include=["reasoning.encrypted_content"],
            )
            if result.status != "completed" or not result.output_text.strip():
                raise ValueError("No complete text reply.")
            for item in result.output:
                if item.type == "reasoning":
                    continue
                if item.type != "message" or item.status != "completed":
                    raise ValueError("Unexpected or incomplete output item.")
                if any(part.type != "output_text" for part in item.content):
                    raise ValueError("Refusal or unsupported message content.")
            # Keep full output items, including encrypted reasoning and message metadata.
            history.extend(item.model_dump(exclude_none=True) for item in result.output)
            print(result.output_text)
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). No automatic retry.")
    except APIConnectionError:
        raise SystemExit("Connection failed. No automatic retry.")
    except (ValueError, TypeError, AttributeError):
        raise SystemExit("Conversation turn did not produce a complete text reply.")
```

每轮先验证完成状态、非空文本和拒答，再将整个 `output` 加入历史。测试覆盖推理项、加密内容及消息 `phase` 的保留；不只复制 `output_text`。任一轮失败就停止，不把失败响应加入下一轮。第一轮已打印的完整回复仍保留。

参考：[OpenAI 会话状态说明](https://developers.openai.com/api/docs/guides/conversation-state)。

[Read in English](/en/guides/conversations.md)

[提示词缓存](/zh/guides/prompt-caching.md) · [推理模型](/zh/guides/reasoning-models.md) · [上下文管理](/zh/guides/context-management.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.