> ## 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.

# Responses 上下文压缩

> 压缩完整历史，保留返回窗口后继续对话。

长对话应在超出模型上下文窗口之前处理历史增长。[独立压缩端点](/zh/api-reference/responses-compact)可返回新的上下文窗口；它不是生成最终回答，也不是任意渠道都支持的摘要接口。先确认同一模型和渠道同时支持 `/responses/compact` 与 `/responses`，以及压缩项的保留和回放。

## 运行压缩后续聊

安装现有 Python 示例依赖。脚本使用一段固定的示范对话，先压缩，再追加新问题并生成文本，共两次请求。真实应用应换成自己保存的完整输入、输出、工具结果及推理项。

```sh theme={null}
export API_BASE_URL="https://gateway.example.com/v1"
export API_KEY="YOUR_API_KEY"
export API_MODEL="YOUR_MODEL_ID"
.venv/bin/python examples/compaction.py
```

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

history = [
    {"role": "user", "content": "Plan a two-day visit to Kyoto without driving."},
    {"role": "assistant", "content": "Day one: eastern temples. Day two: Arashiyama by train."},
]
instructions = "Answer briefly in plain text. Preserve the user's travel constraints."
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:
        compacted = client.post("/responses/compact", cast_to=dict, body={
            "model": os.environ["API_MODEL"], "input": history,
            "instructions": instructions,
        })
        if (not isinstance(compacted, dict) or compacted.get("error")
                or compacted.get("object") != "response.compaction"):
            raise ValueError("Invalid compaction response.")
        window = compacted.get("output")
        if not isinstance(window, list) or not window:
            raise ValueError("Empty compacted window.")
        found_compaction = False
        for item in window:
            if not isinstance(item, dict) or not isinstance(item.get("type"), str) or not item["type"]:
                raise ValueError("Invalid context item.")
            if item["type"] == "compaction":
                encrypted = item.get("encrypted_content")
                if not isinstance(encrypted, str) or not encrypted.strip():
                    raise ValueError("Missing encrypted content.")
                found_compaction = True
        if not found_compaction:
            raise ValueError("Missing compaction item.")
        # Keep every returned item, in order, including unknown metadata.
        next_input = [*window, {"role": "user", "content": "Add a rainy-day alternative."}]
        result = client.responses.create(
            model=os.environ["API_MODEL"], input=next_input,
            instructions=instructions, store=False,
        )
        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"
                    or any(part.type != "output_text" for part in item.content)):
                raise ValueError("Unexpected or incomplete output item.")
        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. Original history must be retained.")
    except (ValueError, TypeError, AttributeError):
        raise SystemExit("Invalid compaction or continuation. Original history must be retained.")
```

## 保存与回放规则

独立压缩返回 `object: response.compaction` 和 `output`，不能按普通 Responses 的 `status` / `output_text` 读取。完整保留 `output` 的顺序、条目和额外字段，用它替换下一轮上下文窗口，然后追加新输入。不要只取 `compaction` 项，也不要把旧历史再次拼接进去。

`encrypted_content` 是不透明状态，不要解码、修改或将它当作可读摘要。压缩输入仍必须适配模型上下文窗口。相关协议行为见 [OpenAI Compaction 指南](https://developers.openai.com/api/docs/guides/compaction)。

示例每次显式发送 `instructions`，使用 `store: false` 续聊；这不构成网关、日志或上游的数据保留承诺。压缩不会自动同步你的数据库、业务状态或权限规则。

## 失败与兼容性

* 压缩失败或返回空窗口时保留原始历史，不继续生成，也不自动删除旧内容。
* 压缩成功、续聊失败时保留原始历史和有效压缩窗口，由应用选择恢复位置；不要自动重复整个流程。
* 多渠道负载均衡可能让两次请求落在不兼容的上游。与管理员确认模型路由、凭据和状态兼容性，不能仅凭相同模型 ID 推断可回放。
* 自动 `context_management`、保存响应 ID、后台执行属于独立能力，不能由压缩路由存在推断支持。Responses 检索只覆盖[插件任务响应](/zh/guides/background-responses)，不提供通用上游检索或 REST 删除 / 取消接口，见[接口支持范围](/zh/guides/api-coverage)。

示例为文本续聊，只校验压缩窗口结构和最终文本完成状态，不证明压缩保留了所有事实。真实应用要检查关键约束、工具结果关联和长会话质量；本地 fixture 不验证密文有效性。

[多轮对话](/zh/guides/conversations) · [生产接入](/zh/guides/production)

[Read in English](/en/guides/compaction)

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


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